DEV Community


Posted on


Palindrome Program using Haskell

I try to learn the syntax of different programming languages. In this blog I have written the program to find whether a number is a palindrome or not using 6 different programming languages. These languages include C, C++, Java, Python, Perl, and Ruby.

I tried learning functional programming and wrote a program to find whether a number is a palindrome number using Haskell. The program for finding palindrome using Haskell is given below.

Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”.

-- Main function which takes input and prints palindrome or not by using the function palindrome to check
main :: IO ()
main = do
    print "Enter a number: "
    inputStr <- getLine 
    let input = read inputStr :: Integer
    if palindrome input then
        print $ show input <> " is a palindrome number"
        print $ show input <> " is not palindrome number"

-- palindrome function which checks whether the number is a palindrome by comparing with the reverse of the number
palindrome :: Integer -> Bool
palindrome x = reversal x == x

-- reversal function for calculating the reverse of the number
reversal :: Integral a => a -> a
reversal = go 0
  where go a 0 = a
        go a b = let (q,r) = b `quotRem` 10 in go (a*10 + r) q
Enter fullscreen mode Exit fullscreen mode

Top comments (0)