尝试在 Haskell 中自己定义过滤器函数但失败了
try to define filter function myself in Haskell and failed
尝试定义过滤函数如下
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>
错误是什么以及如何解决
您应该使用谓词 f
和列表的其余部分 xs
调用 myFilter
,因此:
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f [] = []
myFilter f (x:xs)
| f x = x : myFilter <strong>f</strong> xs -- ← call with f as first parameter
| otherwise = myFilter <strong>f</strong> xs
尝试定义过滤函数如下
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>
错误是什么以及如何解决
您应该使用谓词 f
和列表的其余部分 xs
调用 myFilter
,因此:
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter f [] = []
myFilter f (x:xs)
| f x = x : myFilter <strong>f</strong> xs -- ← call with f as first parameter
| otherwise = myFilter <strong>f</strong> xs