Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 将函数应用于列表中的列表_Haskell - Fatal编程技术网

Haskell 将函数应用于列表中的列表

Haskell 将函数应用于列表中的列表,haskell,Haskell,我想要一个函数,它在一个列表的每个列表([[],[],[])中生成元素的和,如果它被添加到该列表中,则为0和1,否则为1 我试过这个,但它只是正确的头的名单,我不知道如何使其他人 func :: Matrix -> Matrix func (Matr size (x:xs)) |sum(x) `mod` 2 == 0 = (Matr size ((0:x):xs)) |otherwise = (Matr size ((1:

我想要一个函数,它在一个列表的每个列表([[],[],[])中生成元素的和,如果它被添加到该列表中,则为0和1,否则为1

我试过这个,但它只是正确的头的名单,我不知道如何使其他人

 func :: Matrix -> Matrix
 func (Matr size (x:xs))
                |sum(x) `mod` 2 == 0 = (Matr size ((0:x):xs))
                |otherwise = (Matr size ((1:x):xs))
在我的努力下:

 [1,1,0,0]
 [1,0,0]
 [1,1,0]
我想要的是:

 [1,1,0,0]
 [1,1,0,0]
 [0,1,1,0]

谢谢。

当您想对列表中的所有元素应用相同的操作时,不要使用显式递归,让
映射
为您这样做

func :: Matrix -> Matrix
func (Matr size xs) = Matr size $ map prependParity xs
  where prependParity x
               | even $ sum x  = 0:x
               | otherwise     = 1:x

当您想对列表的所有元素应用相同的操作时,不要使用显式递归,让
map
为您这样做

func :: Matrix -> Matrix
func (Matr size xs) = Matr size $ map prependParity xs
  where prependParity x
               | even $ sum x  = 0:x
               | otherwise     = 1:x

好!!我认为显式递归应该是那些“最后手段”的情况之一。事实上,我希望以高阶函数为首的函数编程文本能让人们进入正确的思维模式,并在最后勉强解释递归。真正的黄金在于抽象出迭代本身,而不是通过递归来实现它。请注意,
sum x`mod`2==0
相当于
(偶数.sum)x
@user1161318:我同意,不过记住递归并记住这些高阶函数本身就使用它也无妨。很好!我认为显式递归应该是那些“最后手段”的情况之一。事实上,我希望以高阶函数为首的函数编程文本能让人们进入正确的思维模式,并在最后勉强解释递归。真正的黄金在于抽象出迭代本身,而不是通过递归来实现它。请注意,
sum x`mod`2==0
相当于
(偶数.sum)x
@user1161318:我同意,尽管记住递归并记住这些高阶函数本身使用它还是无妨的。