Trying to learn FRP and Elm. Is the program below "ok" from the perspective of FRP and Elm? What could be improved? The program can be executed here: http://elm-lang.org/try
import Random
import Mouse
data Fruit = Apple | Orange | Banana | Melon | Guava
rand = Random.range 0 4 (Mouse.clicks)
fruit n = if | n == 0 -> Apple
| n == 1 -> Orange
| n == 2 -> Banana
| n == 3 -> Melon
| otherwise -> Guava
fruitText = toForm <~ (asText <~ (fruit <~ rand))
time = lift (inSeconds . fst) (timestamp (fps 40))
scene dy form = collage 300 300 [move (0, 100 * cos dy) form]
main = lift2 scene time fruitText
1 Answer 1
Two months late, but I will try to answer nevertheless. ;-)
Since your rand
already makes sure the numbers will be valid indices for your fruits, you don't have to use so many if cases. The rest looks OK to me, but I made some annotations in the source.
import Random
import Mouse
-- Sometimes empty lines can improve readability.
data Fruit = Apple | Orange | Banana | Melon | Guava
-- For module global declarations, it is often helpful to
-- explicitly annotate the types.
fruits : [Fruit]
fruits = [Apple, Orange, Banana, Melon, Guava]
-- especially for functions :)
fruit : Int -> Fruit
fruit n = head <| drop n fruits
rand : Signal Int
rand = Random.range 0 ((length fruits) - 1) Mouse.clicks
-- exercise: Try to figure and annotate the remaining types. ;-)
fruitText = toForm <~ (asText <~ (fruit <~ rand))
time = lift (inSeconds . fst) (timestamp (fps 40))
scene dy form = collage 300 300 [move (0, 100 * cos dy) form]
main = lift2 scene time fruitText
btw: share-elm.com is a bit easier for showing elm code to someone than making him copy paste to elm-lang.org/try.
See: http://share-elm.com/sprout/52567327e4b0d6a98b1531c7