简体   繁体   中英

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?

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
 palindrome :: String -> Bool
 palindrome = uncurry (==) . (id &&& reverse)

(&&&) is defined in Control.Arrow so that (f &&& g) x = (fx, gx) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM