isPalindrome :: String -> Bool isPalindrome s = s == reversedString s reversedString ::…
Private research annotation
Sign in to add a private research label or note.
- User
isPalindrome :: String -> Bool isPalindrome s = s == reversedString s
reversedString :: String -> String reversedString [] = [] reversedString (x:xs) = reversedString xs ++ [x]
Why doesnt this work, but this does:
isPalindrome :: String -> Bool isPalindrome s = s == reverse s
- Assistant
The first version doesn't work because of how lists (including strings, which are lists of characters) are compared in Haskell. Specifically, your custom
reversedStringfunction is the issue. It correctly reverses the string, but it can be quite inefficient on larger strings due to its use of for appending a single element, which has linear complexity. This inefficiency might not be obvious on smaller inputs, but it makes a significant difference for larger inputs.