7
\$\begingroup\$

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
Jeff Vanzella
4,3182 gold badges24 silver badges33 bronze badges
asked Aug 15, 2013 at 20:56
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

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

SuperBiasedMan
13.5k5 gold badges37 silver badges62 bronze badges
answered Oct 10, 2013 at 9:27
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.