peri4n
peri4n

Reputation: 1421

Apply function and wrap in tuple in Haskell

I am looking for a way to write a function that applies a provided function and wraps argument and function result inside a tuple. Such as:

applyZip :: (a -> b) -> a -> (a,b)
applyZip f x = (x, f x)

Is there a more idiomatic way to write this in Haskell, preferably with library code?

Edit: I was just genuinely interested in other approaches to solve this. If you find your self in the same problem, implementing the function yourself with a descriptive name might be preferable.

Upvotes: 3

Views: 217

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can use:

import Control.Monad(ap)

applyZip :: (a -> b) -> a -> (a,b)
applyZip = ap (,)

Here we work with the ap :: Monad m => m (a -> b) -> m a -> m b function.

Upvotes: 7

Related Questions