对列表[0..n]应用函数并对列表中的元素求和的Haskell程序
我想创建函数allSum,它应该以这种方式声明对列表[0..n]应用函数并对列表中的元素求和的Haskell程序,haskell,Haskell,我想创建函数allSum,它应该以这种方式声明 allSum:: (Int->Int)->(Int->Int) 这就是它应该做的: (allSum f) n = f (0 )+ f (1)+ f (2) +…+ f (n) 这是我的尝试: sum1 = foldr (+)0 allSum:: (int->int) -> (int->int) allSum f = \n -> ( sum1 [ f(x)| x <-[0..n
allSum:: (Int->Int)->(Int->Int)
这就是它应该做的:
(allSum f) n = f (0 )+ f (1)+ f (2) +…+ f (n)
这是我的尝试:
sum1 = foldr (+)0
allSum:: (int->int) -> (int->int)
allSum f = \n -> ( sum1 [ f(x)| x <-[0..n]])
sum1=foldr(+)0
allSum::(int->int)->(int->int)
allSum f=\n->(sum1[f(x)| x如果您将int
更改为int
,它将正常工作:
sum1 = foldr (+) 0
allSum :: (Int -> Int) -> (Int -> Int)
allSum f = \n -> sum1 [ f(x) | x <- [0..n] ]
类型为Int
,大写字母为I
。而不是Int
。此外,请始终记住发布错误或比“它不起作用”更具信息性的内容。你说的“不起作用”是什么意思?是否出现错误?是否编译但未给出正确的结果?谢谢。它只是int而不是int。无点变量allSum f=sum.map f.enumFromTo 0也很好看。
allSum :: (Int -> Int) -> (Int -> Int)
allSum f = \n -> sum . fmap f $ [0..n]