1

Given a Signal, how does one get its historical values?

Something like

--current value
Signal.pastValue(0, Mouse.x)

--previous value
Signal.pastValue(1, Mouse.x)

--previous nth value
Signal.pastValue(n, Mouse.x)

I've tried using Signal.foldp, but it seems that it either returns a current or accumulated value dependant on the event number.

category
  • 2,113
  • 2
  • 22
  • 46

1 Answers1

3

Elm doesn't keep track of historical values on its own, but you could use foldp to build a list of any type of signal like this:

history : Signal a -> Signal (List a)
history =
  Signal.foldp (::) []

The most recent signal value is prepended to that list. To see it in action, you could past this full example into http://elm-lang.org/try

import Graphics.Element exposing (show)
import Mouse

main =
  Signal.map show <| history Mouse.x

history : Signal a -> Signal (List a)
history =
  Signal.foldp (::) []

Running that example may shed light on why historical values aren't kept by default: You can quickly bloat your memory. That being said, elm-reactors time-travelling debugger keeps history around, but only for debugging purposes. This isn't something you'd normally want in production.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • Thanks very much - I've adapted it to `Signal.map show <| Signal.map2 getHistory (Signal.constant 2) (makeHistory Mouse.isDown)` for example, to keep the present and current Signal values. It's quite amazing how the above `history` function uses the `(::)` operator. – category Apr 04 '16 at 18:08