[英]Couldn't match expected type [Int] Haskell
I am new to Haskell so I don't quite understand most of its errors.我是 Haskell 的新手,所以我不太了解它的大部分错误。 I have encountered an error trying to make a higher order function that uses foldl()
to read a list and then multiply it by 2 (it automatically reverses it) and I use another another foldl()
just to read it, in so reversing it to its original order.我在尝试创建更高阶 function 时遇到错误,它使用foldl()
读取列表,然后将其乘以 2(它会自动反转它),我使用另一个foldl()
只是为了读取它,所以反转它到原来的顺序。
I would be thankful for any help I receive.我会感谢我收到的任何帮助。
here's the error这是错误
• 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)[])
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
here's the source code这是源代码
reverses::[Int] ->[Int]
reverses = foldl(\acc x-> x:acc)[]
multthr::[Int]->([Int]->[Int])
multthr = reverses(foldl(\acc x-> (2*x):acc)[])
You need to compose your two foldl's with (.)
, instead of applying one to the other:您需要用(.)
组合您的两个 foldl,而不是将一个应用于另一个:
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) []
so that we have所以我们有
> multthr [1..5]
[2,4,6,8,10]
it :: [Int]
(.)
is the functional composition, defined as (f. g) x = f (gx)
. (.)
是函数组成,定义为(f. g) x = f (gx)
。
Instead of doing the two foldl
's you can do one foldr
,而不是做两个foldl
你可以做一个foldr
,
mult2 = foldr (\x r -> (2*x) : r) []
but then this is nothing else but, simply, map (2*)
.但这只是简单的map (2*)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.