Is there a function in Prelude to pair a value with that value applied to the function?

I am looking for a function that looks something like this:

withSelf :: (a -> b) -> a -> (a, b) withSelf fx = (x, fx)

I searched Hoogle for such a function; I searched for (a -> b) -> a -> (a, b) and a -> (a -> b) -> (a, b) , none of which were final. The Hackage page on Data.Tuple does not have what I'm looking for.

I know that it is trivial to write, but I want, when possible, to write an idiomatic Haskell and not reinvent the wheel.

+6
source share
2 answers

The (id &&&) section does what you want:

 > import Control.Arrow > :t (id &&&) (id &&&) :: (a -> c') -> a -> (a, c') > (id &&&) succ 4 (4,5) 
+7
source

If you do not want to use Control.Arrow , you can always use Applicative :

 withSelf f = (,) <$> id <*> f 

Many people will probably really understand this right away, but for something so simple, it's pretty stupid.

Edit

As stated in comment , this can be written even more succinctly, since

 withSelf = ((,) <*>) 

At first it surprised me, but actually it is very simple: for (->) r , fmap = (.) , So the <$> id completely redundant!

+7
source

Source: https://habr.com/ru/post/984393/


All Articles