我需要在 Haskell 中使用递归来做一个回文检查器来完成家庭作业。该函数应该接受一个字符串并返回一个Bool
. 尝试编译时,出现错误,"Couldn't match type ‘Bool’ with ‘[Char]’."
我对 Haskell 很陌生,所以我确定我只是忽略了一些愚蠢的事情,但我想我还是会寻求一些帮助。我在下面粘贴了我的代码,以及我收到的完整错误。
isPalindrome :: String -> Bool
isPalindrome s
| isPalindrome ((null s) || (length s == 1)) = True
| isPalindrome ((s !! 0) /= (s !! (length s - 1))) = False
| otherwise = isPalindrome (tail (init s))
我的实现检查输入字符串是否为空或大小为 1,如果是则返回 true。如果不是,它检查第一个字符和最后一个字符是否不同,如果不同,则返回 false。否则,它会再次调用自身,传入字符串中第一个和最后一个字符被截断。
main.hs:15:19: error:
• Couldn't match type ‘Bool’ with ‘[Char]’
Expected type: String
Actual type: Bool
• In the first argument of ‘isPalindrome’, namely
‘((null s) || (length s == 1))’
In the expression: isPalindrome ((null s) || (length s == 1))
In a stmt of a pattern guard for
an equation for ‘isPalindrome’:
isPalindrome ((null s) || (length s == 1))
|
15 | | isPalindrome ((null s) || (length s == 1)) = True
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
main.hs:16:19: error:
• Couldn't match type ‘Bool’ with ‘[Char]’
Expected type: String
Actual type: Bool
• In the first argument of ‘isPalindrome’, namely
‘((s !! 0) /= (s !! (length s - 1)))’
In the expression: isPalindrome ((s !! 0) /= (s !! (length s - 1)))
In a stmt of a pattern guard for
an equation for ‘isPalindrome’:
isPalindrome ((s !! 0) /= (s !! (length s - 1)))
|
16 | | isPalindrome ((s !! 0) /= (s !! (length s - 1))) = False
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^