Home > other >  Combining swap and pair function in haskell
Combining swap and pair function in haskell

Time:10-12

I am very new to haskell and i have begun reading the book 'programming in haskell'. I came across the function called swap

swap (x,y) = (y,x) 

and the function pair.

pair x y = (x,y) 

Then i began to wonder if it was possible to combine these two functions somehow like this

swapPair x y = (y,x) 

and using the two priar functions as help functions.

CodePudding user response:

The most obvious way this can be done is

swapPair x y = swap (pair x y)

which is the same as

swapPair x y = swap $ pair x y

Because y appears only at the end of both sides, it can be eta-reduced. That requires changing the application operator to a composition one:

swapPair x = swap . pair x

As Willem Van Onsem showed, this can be made completely point-free. I would not recommend that, but here's how it works: you first consider that the . operator is itself a function that's being applied to some arguments

swapPair x = (.) swap (pair x)

Then this can be written as a composition again:

swapPair x = (.) swap . pair $ x

eta-reduce

swapPair = (.) swap . pair

and finally operator section syntax can be applied:

swapPair = (swap .) . pair

CodePudding user response:

You can use these with:

swapPair :: a -> b -> (b, a)
swapPair = (swap .) . pair

Here we thus pass the two parameters first to pair to create a 2-tuple, and then we apply swap on that 2-tuple.

But we can do this without swap and pair, and just work with:

swapPair :: a -> b -> (b, a)
swapPair = flip (,)
  • Related