Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I rewrite this palindrome verifier in point-free style?

I have this snippet of code:

palindrome :: String -> Bool
palindrome x = x == reverse x

Is there any way to rewrite this in a point-free style?

like image 967
user2852456 Avatar asked Oct 13 '13 19:10

user2852456


4 Answers

Yes, because any function can be written in point-free style. Here, the Applicative instance for (->) r (aka Reader) does this for you, because

(f <*> g) x = f x (g x)

You may recognize this as the S-combinator from SKI calculus (return is K by the way).

Your Palindrome checker is written as

x == reverse x

which in infix form reads

(==) x (reverse x)

and by comparison with the <*> definition above this leads to the expression

isPalindrome x = ((==) <*> reverse) x

where you can drop the trailing x to get the solution

isPalindrome = (==) <*> reverse

which is probably less readable than the original expression and should not be used for that reason. Point-free style is for readability, and only useful in certian cases.

like image 57
David Avatar answered Nov 17 '22 22:11

David


You might think this method is cheating:

palindrome :: Eq a => [a] -> Bool
palindrome = palindrome'
  where palindrome' xs = xs == reverse xs

Of course there's also the applicative style that David and freyrs suggested:

palindrome'' :: Eq a => [a] -> Bool
palindrome'' = (==) <*> reverse

But how about this expression as a fold?

palindrome''' :: Eq a => [a] -> Bool
palindrome''' = (foldl (\b (x, y) -> b && x == y) True)
              . (uncurry zip)
              . reverse'
  where reverse' xs = (xs, reverse xs)
like image 37
Alexander Vieth Avatar answered Nov 17 '22 22:11

Alexander Vieth


(->) r is also a Monad, so your palindrome checker can be written with monadic bind, which is probably more readable than the Applicative solution above

palindrome :: String -> Bool
palindrome = reverse >>= (==)
like image 28
ademidov Avatar answered Nov 17 '22 22:11

ademidov


Yes.

palindrome :: String -> Bool
palindrome = ap (==) reverse
like image 1
Stephen Diehl Avatar answered Nov 17 '22 21:11

Stephen Diehl