'Haskell Recursion Function (guards required)
Can someone tell me what's wrong with my implementation of this Haskell palindrome checker? Note: Before calling this on the the input string, the string is "cleaned" to get rid of case discrepancies and any non-alphabet characters.
checkPalindromeClean :: [Char] -> Bool
checkPalindromeClean inpString
| length inpString == 0 = True
| length inpString == 1 = True
| head inpString == last inpString = checkPalindromeClean (init (tail inpString))
otherwise False
Here is the (cryptic) error message I am receiving:
jdoodle.hs:43:42: error:
• Couldn't match expected type ‘Bool -> Bool -> Bool’
with actual type ‘Bool’
• The function ‘checkPalindromeClean’
is applied to three value arguments,
but its type ‘[Char] -> Bool’ has only one
In the expression:
checkPalindromeClean (init (tail inpString)) otherwise False
In an equation for ‘checkPalindromeClean’:
checkPalindromeClean inpString
| length inpString == 0 = True
| length inpString == 1 = True
| head inpString == last inpString
= checkPalindromeClean (init (tail inpString)) otherwise False
|
43 | | head inpString == last inpString = checkPalindromeClean (init (tail inpString))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
Solution 1:[1]
otherwise is a condition too (it is an alias of True), and therefore should be used as a guard as well, so:
checkPalindromeClean :: [Char] -> Bool
checkPalindromeClean inpString
| length inpString == 0 = True
| length inpString == 1 = True
| head inpString == last inpString = checkPalindromeClean (init (tail inpString))
| otherwise = False
Using length :: [a] -> Int, init :: [a] -> [a] and last :: [a] -> a all run in ?(n), therefore the algorithm will run in ?(n2), which is not very efficient.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
