Search code examples
if-statementfrpelm

if-then statements involving signals


I am getting stuck writing a simple if-then statement in Elm involving signals.

What if the conditional is itself a Signal type? I would like to change the Mouse Down example on the Elm website:

import Graphics.Element exposing (..)
import Mouse

main : Signal Element
main =
  Signal.map show Mouse.isDown

It will either say True or False depending on whether the Mouse is up or down. What if I want it to say "Up" or "Down"? My Boolean function could say:

<!-- language: haskell -->

f : Bool -> String
f x = 
 if x then "&uarr;" else "&darr;"

but when I change the main function I get a type mismatch.

<!-- language: haskell -->

main : Signal Element
main =
  Signal.map show ( f Mouse.isDown)

Error #1:

The 2nd argument to function `map` has an unexpected type.

10|   Signal.map show ( f Mouse.isDown)
As I infer the type of values flowing through your program, I see a conflict
between these two types:

    Signal a

    String

Error #2:

The 1st argument to function `f` has an unexpected type.

10|   Signal.map show ( f Mouse.isDown)
As I infer the type of values flowing through your program, I see a conflict
between these two types:

    Bool

    Signal Bool

Solution

  • It's basically the same thing as with show :: Bool -> Element. You're not passing the Signal into that function, but rather you map the function over the Signal. It works the same with your f:

    import Mouse
    import Graphics.Element exposing (Element, show)
    
    f : Bool -> String
    f x = if x then "&uarr;" else "&darr;"
    
    updown : Signal String
    updown = Signal.map f Mouse.isDown
    
    main : Signal Element
    main = Signal.map show updown
    

    Or in short, with composition: main = Signal.map (show << f) Mouse.isDown.