How to create a list of list of numbers in Haskell

前端 未结 2 956
隐瞒了意图╮
隐瞒了意图╮ 2021-01-25 12:58

I need to create a function that makes a board of size row and column and then populate that with zeros. mkBoard 2 3 would make [[0,0,0],[0,0,0]]

I don\'t really know w

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-25 13:45

    As @arrowd already mentioned, there is a replicate function for take n (repeat x). You can create one row of your board with replicate n 0, and then create a board of such rows like mkBoard m n = replicate m (replicate n 0).

    Also you can create more generic version of this function to fill the field with any value:

    genericMkBoard :: a -> Int -> Int -> [[a]]
    genericMkBoard x m n = replicate m (replicate n x)
    

    And define your mkBoard with partial application:

    mkBoard = genericMkBoard 0
    

    UPD: Also you can make it like this to be more consistent with replicate (thanks to @chepner):

    replicate2D m n x = replicate m (replicate n x)
    
    mkBoard m n = replicate2D m n 0
    

提交回复
热议问题