Why doesn't this Elm code work? (Example provided with expected output)
-
21-12-2019 - |
Question
I'm trying to make an elm program that outputs the following pattern :
3 4 2 3 2 4 ...
Here is my Elm Code :
main = lift asText agent
delta = lift (\x -> -1) (fps 1)
agent = foldp update 3 delta
update : Int -> Int -> Int
update x y = x + y + (threshold x)
threshold : Int -> Int
threshold x = if (x < 3) then x
else 0
This is what I think the code should be saying
3 + -1 + 0 = 2
2 + -1 + 3 = 4
4 + -1 + 0 = 3
3 + -1 + 0 = 2 ... etc
However this is not the output. I think I'm confused as to how the signals update ...
Solution
There are a few things keeping your code from giving you 3
then 2
then 4
then 3
again. (Which is not exactly what you describe at the start of your question, but you do at the finish so I'll go with that. )
Argument order of update
If you look at the type of foldp
,
foldp : (a -> b -> b) -> b -> Signal a -> Signal b
you'll notice that the last value calculated is the second argument to the update function you supply. So if you make your update
function
update y x = x + y + (threshold x)
then you should be closer to what you wanted you function to be.
Meaning of threshold
threshold
returns x
when x < 3
, so when the last x
was 2
, it'll return 2
, so you'll get:
3 + -1 + 0 = 2
2 + -1 + 2 = 3
3 + -1 + 0 = 2
2 + -1 + 2 = 3
Now I'm not sure what you're after but if you add a +1
to threshold
you should get close to the output you were expecting.
Conclusion
With these changes your code would look like:
main = lift asText agent
delta = lift (\x -> -1) (fps 1)
agent = foldp update 3 delta
update : Int -> Int -> Int
update y x = x + y + (threshold x)
threshold : Int -> Int
threshold x = if (x < 3) then x+1
else 0