无法匹配预期类型 [Int] Haskell

问题描述

我是 Haskell 的新手,所以我不太了解它的大部分错误。我在尝试创建一个使用 foldl() 读取列表然后乘以 2(它会自动反转它)的高阶函数时遇到错误,我使用另一个 foldl() 来读取它,从而将其反转为原始顺序。

我会感谢我得到的任何帮助。

这里是错误

Couldn't match expected type ‘[Int]’
                  with actual type ‘t0 Integer -> [Integer]’
    • Probable cause: ‘foldl’ is applied to too few arguments
      In the first argument of ‘reverses’,namely
        ‘(foldl (\ acc x -> (2 * x) : acc) [])’
      In the expression: reverses (foldl (\ acc x -> (2 * x) : acc) [])
      In an equation for ‘multthr’:
          multthr = reverses (foldl (\ acc x -> (2 * x) : acc) [])
   |
16 | multthr = reverses(foldl(\acc x-> (2*x):acc)[])
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^

这是源代码

reverses::[Int] ->[Int]
reverses = foldl(\acc x-> x:acc)[]

multthr::[Int]->([Int]->[Int])
multthr = reverses(foldl(\acc x-> (2*x):acc)[]) 

解决方法

您需要使用 (.) 组合您的两个折叠,而不是将一个应用于另一个:

reverses :: [a] -> [a]
reverses = foldl (\acc x-> x:acc) []

---- multthr :: [Int] -> ([Int] -> [Int])  -- why??
multthr :: [Int] -> [Int]
---- multthr = reverses (foldl(\acc x-> (2*x):acc)[])  -- causes error
multthr = reverses . foldl (\acc x-> (2*x):acc) [] 

所以我们有

> multthr [1..5]
[2,4,6,8,10]
it :: [Int]

(.) 是函数组合,定义为 (f . g) x = f (g x)

你可以做一个foldl,而不是做两个foldr

mult2 = foldr (\x r -> (2*x) : r) []

但是这只是简单的map (2*)