【发布时间】:2017-04-16 18:36:16
【问题描述】:
我对 Haskell 有点陌生,但我已经解决了这个问题几个小时,但没有运气。
我正在尝试实现类似于过滤器的东西,除了一个谓词和列表被传递给一个函数,它返回一个由两个列表组成的元组,一个被谓词过滤,一个不被谓词过滤。
divideList :: (a -> Bool) -> [a] -> ([a],[a])
divideList p xs = (f, nf) where
f = doFilter p xs
nf = doFilter (not . p) xs
doFilter :: (a -> Bool) -> [a] -> [a]
doFilter _ [] = []
doFilter p (x:xs) = [x | p x] ++ doFilter p xs
第二个函数doFilter 可以正常工作。它将过滤器应用于其列表并吐出适当的列表。 (即如果我只使用doFilter (>3) [1,2,3,4,5,6] 它将正常工作)
我的问题是第一个功能。当我使用divideList (>3) [1,2,3,4,5,6] 时,我得到了一些Variable not in scope 错误。错误如下:
AddListOperations.hs:20:23: error:
Variable not in scope: p :: a -> Bool
AddListOperations.hs:20:25: error: Variable not in scope: xs :: [a]
AddListOperations.hs:21:31: error:
Variable not in scope: p :: a -> Bool
AddListOperations.hs:21:34: error: Variable not in scope: xs :: [a]
就像我说的那样,我只是在玩 Haskell 几天,所以如果我遗漏了任何重要信息,请告诉我。
【问题讨论】:
-
您需要缩进
f = ...和nf = ...否则无法知道它们是否附加到divideList。 -
我不敢相信这就是全部...非常感谢
-
顺便说一句,Hoogle would have told you
partition是你想要的功能。
标签: haskell