HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajor

Palindrome test in Haskell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
palindrometesthaskell

Problem

I am new to Haskell and, coming from a OO/procedural programming background, I want to make sure my code follows the functional way of doing things. I built this short module to test if a given string is a palindrome (same backwards and forwards, case-sensitive) and I am simply wondering if this is the most "Haskell" way to do it. Any criticism is greatly appreciated.

module PalindromeTest (isPalindrome) where

isPalindrome :: String -> Bool

isPalindrome w
 | nChars <= 1           = nChars == 1
 | nChars == 2           = firstElem == lastElem
 | firstElem /= lastElem = False
 | firstElem == lastElem = isPalindrome (take (nChars - 2) (tail w))
 where firstElem = head w
       lastElem  = last w
       nChars    = length w

Solution

I would just write

isPalindrome w = w == reverse w


Short, and very easy to understand! And in this case it's also a lot more efficient, but that's another story...

Code Snippets

isPalindrome w = w == reverse w

Context

StackExchange Code Review Q#24340, answer score: 22

Revisions (0)

No revisions yet.