如何在Haskell中创建数字列表 [英] How to create a list of list of numbers in Haskell
问题描述
我需要创建一个函数来制作一块行和列大小的板,然后用零填充它. mkBoard 2 3将使 [[0,0,0],[0,0,0]]
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]]
我真的不知道从哪里开始,因为我是Haskell编程的新手,我当时认为该函数应该是这样的:
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.
谢谢您的帮助.
推荐答案
正如@arrowd所述,take n (repeat x)
有一个replicate
函数.您可以使用replicate n 0
创建木板的一行,然后创建诸如mkBoard m n = replicate m (replicate n 0)
这样的行的木板.
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)
并使用部分应用程序定义:
mkBoard = genericMkBoard 0
UPD :您也可以使它与replicate
更加一致(感谢@chepner):
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
这篇关于如何在Haskell中创建数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!