Reputation: 22460
Is there is a succinct way to change the return type of a function?
Consider for example comparing
in Data.Ord
. It returns an Ordering
. Yet I am only interested in whether the two items are equal or not. So I need to convert the resulting Ordering
to a Bool
.
A straight forward way I can think of is:
isEqualOn f x y = if comparing f x y==EQ then True else False
(or isEqualOn f x y = comparing f x y==EQ
as here as pointed out in the comments).
Is there a more compositional way to do this (sort of adapting comparing
or writing it in a pointless manner) without having to write out everything? Ideally, I am looking for something that works on n-ary functions as well.
-- Update --
As suggested by the answers/comments, the specific example above (isEqualOn
) can be implemented using the standard on
function as on (==)
. However, my question is about the general technique to change function return types in a compositional/pointless manner as exemplified by the SEC approach in the comments.
Upvotes: 3
Views: 407
Reputation: 9891
As mentioned you can use the function on
from Data.Function, but
perhaps you are looking for the operator ==
which returns a Bool
.
In which case your function can be written as:
isEqualOn f x y = fx == fy
and personally I would never write this particular function but "inline" it where it is used.
On the more general matter of "changing the return type". What you are looking for is composition:
isEq Eq = True
isEq _ = False
equal x y = isEq (comparing x y)
or more haskell flavored:
equal x = isEq . comparing x
Upvotes: 0
Reputation: 77951
Your definition of isEqualOn
would be the same as on (==)
:
\> import Data.Function (on)
\> :t (on (==))
(on (==)) :: Eq a1 => (a -> a1) -> a -> a -> Bool
for example to compare on absolute value:
\> let isEqualOn = on (==)
\> isEqualOn abs 2 (-2)
True
Upvotes: 5