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?
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.
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)
(->) 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 >>= (==)
Yes.
palindrome :: String -> Bool
palindrome = ap (==) reverse
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With