如何使用随机数的地图功能

时间:2014-11-15 15:09:11

标签: random elm

此代码来自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." ]

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

1 个答案:

答案 0 :(得分:2)

在您的代码中,您drawPentagon <~ p的类型为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." ]

这是你想要做的吗?