如何将元素转换为表单?

时间:2015-08-20 11:05:14

标签: elm

如何将Mouse.position转换为Form,以便将其显示在拼贴中?以下代码显示<Signal>而不是实际的鼠标坐标:

render (x, y) =
    let mousePos = toForm (show Mouse.position)
    in collage 400 400 [mousePos]

奇怪的是,在此示例http://elm-lang.org/examples/mouse-position中,show函数实际上将Mouse.position转换为带坐标的字符串,但这是因为show函数用于过滤将Signal(Int, Int)转换为Signal值的元组。

所以我的问题是,如何将Signal(Int, Int)转换为Form,以便显示元组值?

1 个答案:

答案 0 :(得分:4)

您正在寻找Graphics.Collage.toForm类型的Element -> Form

听起来你也不太了解Signal.map正在做什么。它需要一个函数应用于Signal的每个值。在以下示例中,我尝试在多个上下文中使用它。

import Graphics.Element exposing (..)
import Graphics.Collage
import Graphics.Collage exposing (Form)
import Mouse

--This is the function you are trying to construct.
--It takes in a position, converts it to an element,
--using show and then converts it to a Form.
formPosition : (Int, Int) -> Form
formPosition pos = 
  let element = show pos -- element : Element 
  in Graphics.Collage.toForm element

-- We now want to apply our formPosition function to the
-- Signal containing all mouse position changes.
-- So we use Signal.map to apply formPosition to all values
-- of Mouse.position
formSignal : Signal Form
formSignal = Signal.map formPosition Mouse.position

-- Eventually we want to render this on the screen and the
-- function to do this requires a List Form not just a single
-- Form. So we write a function which returns a Singleton list
-- and apply it to each value in our formSignal.
formListSignal : Signal (List Form)
formListSignal = Signal.map (\n -> [n]) formSignal


-- Finally, we must turn that into a Signal Element to render
-- on the screen. We partially apply Graphics.Collage.collage
-- to return an element of size 400x400 and apply it to the 
-- values of formListSignal by using Signal.map again
elementSignal : Signal Element
elementSignal = Signal.map (Graphics.Collage.collage 400 400) formListSignal

-- Finally we hand this off to main and it renders
main : Signal Element
main = elementSignal

更简单的版本可能会将所有转换合并为一个函数。我只想强调Signal.map的工作原理。我希望这有帮助!