1

此代码来自http://elm-lang.org/edit/examples/Intermediate/Stamps.elm。我做了一个小改动,见下文。

import Mouse
import Window
import Random

main : Signal Element
main = lift2 scene Window.dimensions clickLocations

-- for a good time, remove "sampleOn Mouse.clicks" ;)
clickLocations : Signal [(Int,Int)]
clickLocations = foldp (::) [] (sampleOn Mouse.clicks Mouse.position)

scene : (Int,Int) -> [(Int,Int)] -> Element
scene (w,h) locs =
  let p = Random.float (fps 25)
      drawPentagon p (x,y) =
          ngon 5 20 |> filled (hsla p 0.9 0.6 0.7)
                    |> move (toFloat x - toFloat w / 2, toFloat h / 2 - toFloat y)
                    |> rotate (toFloat x)
  in  layers [ collage w h (map (drawPentagon <~ p) locs) // I want to change different color each time, error here!
             , plainText "Click to stamp a pentagon." ]

使用地图功能时如何传递信号?

4

1 回答 1

2

在您的代码中,您有drawPentagon <~ pwhich 的类型Signal ((Int, Int) -> Form)

地图的类型map : (a -> b) -> [a] -> [b]是导致类型错误的原因。它基本上是在说,这map是期待一个功能a -> b,但你已经给了它一个Signal ((Int, Int) -> From).

尝试完成您正在做的事情的一种方法是制作p一个参数scene并用于lift3传入Random.float (fps 25). 所以,你最终会得到这个:

import Mouse
import Window
import Random

main : Signal Element
main = lift3 scene Window.dimensions clickLocations (Random.float (fps 25))

-- for a good time, remove "sampleOn Mouse.clicks" ;)
clickLocations : Signal [(Int,Int)]
clickLocations = foldp (::) [] (sampleOn Mouse.clicks Mouse.position)

scene : (Int,Int) -> [(Int,Int)] -> Float -> Element
scene (w,h) locs p =
  let drawPentagon p (x,y) =
          ngon 5 20 |> filled (hsla p 0.9 0.6 0.7)
                    |> move (toFloat x - toFloat w / 2, toFloat h / 2 - toFloat y)
                    |> rotate (toFloat x)
  in  layers [ collage w h (map (drawPentagon p) locs)
             , plainText "Click to stamp a pentagon." ]

这是你想做的吗?

于 2014-11-15T16:47:34.383 回答