Mixing static content and signals in Elm

Elm is awesome, but sometimes, the simplest things prove to be surprisingly challenging.

You can easily create a HTML page showing an image:

import Graphics.Element exposing (..)

main : Element
main =
    image 200 200 ("./images/Mimas_moon.jpg")

and you can just as easily create a HTML page showing the current mouse position:

import Mouse
import Signal
import Graphics.Element

main =
  Signal.map Graphics.Element.show Mouse.position

but creating a HTML page that displays both is not as easy as you would imagine. I finally settled for

import Mouse
import Signal
import Graphics.Element exposing (..)
import Graphics.Collage exposing (..)
import List

toCollage : List Form -> Element
toCollage lst =
  collage 600 400 lst

combine : List (Signal a) -> Signal (List a)
combine = List.foldr (Signal.map2 (::)) (Signal.constant [])
main : Signal Element
main =
  Signal.map toCollage
     (combine
      [ Signal.map toForm (Signal.map Graphics.Element.show Mouse.position)
      , Signal.constant(move (200,-100) (toForm (image 200 200 ("./images/Mimas_moon.jpg"))))
      ])
This code
- takes the current Mouse position (which is a Signal)
- converts it to a Signal Form using Signal.map toForm
- creates and moves an image
- converts it to a Signal Form using Signal.constant
- puts these two elements into a List [ Signal Form ]
- uses combine to convert this List [ Signal Form ] to a Signal List [ Form ]
- finally uses Signal.map toCollage to create a collage out of this list








295 Words

2015-10-23T14:49:00.004-07:00