【发布时间】:2017-07-09 05:43:11
【问题描述】:
所以我正在从现实世界的 haskell 书中做练习,并使用 foldl 为 takeWhile 函数编写了以下代码。
myTakeWhile' :: (a->Bool) -> [a] -> [a]
myTakeWhile' f xs = foldl step [] xs
where step x xs | f x = x:(myTakeWhile' f xs)
| otherwise = []
这会产生以下错误,我无法理解。
Couldn't match type ‘a’ with ‘[a]’
‘a’ is a rigid type variable bound by
the type signature for myTakeWhile' :: (a -> Bool) -> [a] -> [a]
at p1.hs:17:17
Expected type: [a] -> [a] -> [a]
Actual type: a -> [a] -> [a]
Relevant bindings include
step :: a -> [a] -> [a] (bound at p1.hs:19:11)
xs :: [a] (bound at p1.hs:18:16)
f :: a -> Bool (bound at p1.hs:18:14)
myTakeWhile' :: (a -> Bool) -> [a] -> [a] (bound at p1.hs:18:1)
In the first argument of ‘foldl’, namely ‘step’
In the expression: foldl step [] xs
【问题讨论】:
-
你确定这个练习没有要求你使用
foldr吗?使用foldl实现takeWhile毫无意义。用foldr实现比较简单。 -
练习没有提到使用哪个折叠。