haskell 高阶函数未采用正确的参数

ttcibm8c  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(133)

我有一个在haskell中创建高阶函数的练习,它需要我创建的另一个函数。

multiplyFive :: [Int] -> [Int]
multiplyFive [] = []
multiplyFive (x:xs) = (x * 5) : multiplyFive xs

然后我创建这个函数来添加给定列表中的所有数字

addAll :: ([Int] -> [Int]) -> [Int] -> Int
addAll fn [] = 0
addAll fn (x:xs) = x + addAll fn xs

我正在努力

main :: IO()
main = do 
    print(addAll multiplyFive [1..4])

输出应该是50,但它给了我10的输出

q3qa4bjr

q3qa4bjr1#

你只需要把 * fn传递给递归调用,你不用 * fn把它应用到元素上。因此,addAll应该是:

addAll :: ([Int] -> [Int]) -> [Int] -> Int
addAll fn xs = go (fn xs)
  where go [] = 0
        go (x : xs) = x + go xs

然而,该函数可以简化为:

addAll :: (Foldable f, Num b) => (a -> f b) -> a -> b
addAll = (sum .)

multiplyFive就是:

multiplyFive :: Num a => [a] -> [a]
multiplyFive = map (5 *)

相关问题