我对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搞乱,所以如果我遗漏任何重要信息,请告诉我。
答案 0 :(得分:1)
缩进f
和nf
:
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