Haskell错误:变量不在范围内

时间:2017-04-15 17:26:05

标签: haskell

我对Haskell有点新意,但我已经在这个问题上工作了几个小时没有运气。

我试图实现类似于过滤器的东西,除了谓词和列表被传递给一个函数,它返回一个由两个列表组成的元组,一个由谓词过滤,另一个不是。< / p>

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搞乱,所以如果我遗漏任何重要信息,请告诉我。

2 个答案:

答案 0 :(得分:1)

缩进fnf

divideList :: (a -> Bool) -> [a] -> ([a],[a])
divideList p xs = (f, nf) where
  f  = doFilter p xs
  nf = doFilter (not . p) xs

毕竟,where阻止在哪里停止?

顺便说一句,divideList partition来自Data.List

答案 1 :(得分:0)

感谢Alec,我发现我需要做的就是缩进where下面的陈述:

divideList :: (a -> Bool) -> [a] -> ([a],[a])
divideList p xs = (f, nf) where 
    f = doFilter p xs
    nf = doFilter (not . p) xs