Knitting

I am trying to draw a list of objects, but cannot get it to work. Secondary question: how to create a "loop for loop" using ELM.

I have

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 = ?????

      

I'm trying to get somethign liek this to work

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

                ]

      

In particular, a collage has several things that it needs to build:

   [ 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  
   ]

      

+3


source to share


1 answer


You are looking for a function map

.

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

This means that you can apply some function to a list of things and return a list of results.



You are very close to what you have here. I've filled in some gaps to help you make progress! Good luck!

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 become Car
-- and all b 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)

      

+4


source







All Articles