榆树绘制列表

时间:2014-11-17 20:28:53

标签: elm

我正在尝试绘制对象列表但无法使其工作。 次要问题是如何使用ELM进行“for循环”。

我有一个

type Object a = { a | x:Float, y:Float, vx:Float, vy:Float }
type Car  = Object {}
type Cars = [Car]

displayCar =  move (car.x,car.y) (filled white (rect 30 20))
displayCars = ?????

我正试图让这个工作得胜一筹

collage 100 100 [displayCar (head cars) -- does work
                 , displayCars cars -- does not work

                ]

特别是,拼贴画有多种需要绘制的内容:

   [ filled pongGreen   (rect gameWidth gameHeight)
   , displayObjHouse (game.houses !! 0) -- so ugly code
   , displayObjHouse (game.houses !! 1) -- so ugly code
   , displayObjHouse (game.houses !! 2) -- so ugly code
   , displayObjHouse (game.houses !! 3) -- so ugly code
   , displayObjHouse (game.houses !! 4) -- so ugly code
   , displayCars cars -- does not work  
   ]

1 个答案:

答案 0 :(得分:4)

您正在寻找功能map

map : (a -> b) -> [a] -> [b]

这意味着您可以将某些功能应用于事物列表并返回结果列表。

你非常接近你拥有的东西。我填补了一些空白,以帮助你不断进步!祝你好运!

type Object a = { a | x:Float, y:Float, vx:Float, vy:Float }
type Car = Object {}
type House = Object { residents : Int }

displayCar : Car -> Form
displayCar car =  move (car.x,car.y) (filled black (rect 30 20))

displayCars : [Car] -> [Form]
displayCars cars = map displayCar cars

-- map : (a -> b) -> [a] -> [b]
-- In our particular example, we plug in our functions
-- displayCar : Car -> Form
-- since display car is the first argument to map, all a's become Car
-- and all b's become Form
-- So the type of map in this instance is ((Car -> Form) -> [Car] -> [Form]

someCars : [Car]
someCars = [ { x = 100, y = 10, vx = 0, vy = 0 }
           , { x = 35, y = 100, vx = 0, vy = 0 }
           , { x = 0, y = 0, vx = 0, vy = 0 }
           ]

someHouses : [House]
someHouses = [ { x = 20, y = -100, vx = 0, vy = 0, residents = 3 }
             , { x = -20, y = -50, vx = 0, vy = 0, residents = 3 }
             , { x = 160, y = -150, vx = 0, vy = 0, residents = 3 }
             ]  

displayHouse : House -> Form
displayHouse house = move (house.x, house.y) (filled blue (rect 30 50))

main : Element
main = 
  let houses = map displayHouse someHouses
      cars   = map displayCar someCars
  in collage 400 400 (houses ++ cars)