function application with lambda in haskell?

194 Views Asked by At

Having this code to test:

-- | this function checks if string or list are a palindrome
    isPalindrome :: (Eq a) => [a] -> Bool
    isPalindrome x =
        if reverse x == x
            then True
            else False

I managed to write this:

-- | how do I remove ugly parentheses our of here?
palindromeTest verb = isPalindrome ((\verb -> verb ++ reverse verb) verb )  == True
    where types = verb::String

Parentheses look disgusting, how do I work them out?

1

There are 1 best solutions below

4
On BEST ANSWER

palindromeTest

Your expression:

(\verb -> verb ++ reverse verb) verb

does not make much sense: an equivalent expression would be:

(\x -> x ++ reverse x) verb

since verb in the lambda expression was locally scoped. But you know what x is: it is verb. So you can replace the expression with:

verb ++ reverse verb

Or in full:

palindromeTest verb = isPalindrome (verb ++ reverse verb) == True

We can also eliminate the == True, since \x -> x == True is equivalent to id:

palindromeTest verb = isPalindrome (verb ++ reverse verb)

Finally the where types = verb::String is useless as well: Haskell is statically typed, types are resolved at compile time. So this statement does not adds anything. You can restrict the type of verb in the type signature of the function:

palindromeTest :: String -> Bool
palindromeTest verb = isPalindrome (verb ++ reverse verb)

isPalindrome

Just like in palindromTest it is useless to write == True, there is no reason to write = True, and = False if this is based on a condition: simply return the condition itself:

-- | this function checks if string or list are a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = reverse x == x

You can make it more compact by using ap:

import Control.Monad(ap)

-- | this function checks if string or list are a palindrome
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome = ap (==) reverse