【问题标题】:try to define filter function myself in Haskell and failed尝试在 Haskell 中自己定义过滤器功能并失败
【发布时间】:2021-12-28 22:42:23
【问题描述】:

尝试如下定义过滤函数

myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f [] = []
myFilter f (x:xs) 
  | f x = x : myFilter xs 
  | otherwise = myFilter xs

我将它放入名为 myfilter.hs 的文件中并加载到 ghci。我收到以下错误

myfilter.hs:5:26: error:
    • Couldn't match expected type: a1 -> Bool
                  with actual type: [a]
    • In the first argument of ‘myFilter’, namely ‘xs’
      In the expression: myFilter xs
      In an equation for ‘myFilter’:
          myFilter f (x : xs)
            | f x = x : myFilter xs
            | otherwise = myFilter xs
    • Relevant bindings include
        xs :: [a] (bound at myfilter.hs:3:15)
        x :: a (bound at myfilter.hs:3:13)
        f :: a -> Bool (bound at myfilter.hs:3:10)
        myFilter :: (a -> Bool) -> [a] -> [a] (bound at myfilter.hs:2:1)
  |
5 |   | otherwise = myFilter xs
  |                          ^^
Failed, no modules loaded.
ghci>

错误是什么以及如何解决它

【问题讨论】:

    标签: haskell filter higher-order-functions


    【解决方案1】:

    您应该使用谓词f 和列表的其余部分xs 调用myFilter,所以:

    myFilter :: (a -> Bool) -> [a] -> [a]
    myFilter f [] = []
    myFilter f (x:xs) 
      | f x = x : myFilter f xs -- ← call with f as first parameter
      | otherwise = myFilter f xs

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 2019-04-16
      • 1970-01-01
      • 2013-05-04
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      相关资源
      最近更新 更多