嘗試定義過濾函式如下
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>
錯誤是什么,我該如何解決
uj5u.com熱心網友回復:
您應該myFilter使用謂詞f和串列的其余部分進行呼叫xs,因此:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/398723.html
上一篇:使用ghc編譯但不使用cabalnew-run編譯的代碼
下一篇:哈斯克爾||缺少空元素
