【问题标题】:Haskell error: Variable not in scopeHaskell错误:变量不在范围内
【发布时间】: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


【解决方案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 是来自Data.Listpartition

【讨论】:

  • 谢谢,我刚刚意识到我需要的只是一些缩进。是否根据谓词(la 过滤器)对列表进行分区?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2021-01-05
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多