How to create a list of list of numbers in Haskell

萝らか妹 提交于 2020-01-21 19:32:06

问题


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 where to start as I am new to Haskell programming I was thinking that the function would be something like this:

mkBoard m n= [m | ???? take n (repeat 0)]

But I am not sure if this would be the correct approach.

Thank you for your help.


回答1:


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



回答2:


There is no need to use list comprehension here. We can make use of replicate :: Int -> a -> [a] that will convert an Int n and an a to a list that repeats that value n times.

We thus can construct a list of three 0s with replicate 3 0. We can then use replicate a second time to construct a list that contains that list two times for example.

mkBoard :: Num n => Int -> Int -> [[n]]
mkBoard m n = replicate m (replicate n 0)


来源:https://stackoverflow.com/questions/59190195/how-to-create-a-list-of-list-of-numbers-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!