Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the flip function do?

Tags:

purescript

I am a newbie to purescript. This is the book Leanpub-purescript in which I'm learning. I can't understand what flip funtion is. Is that similar to swapping concepts?

> :type flip
forall a b c. (a -> b -> c) -> b -> a -> c

which means a value goes to b, then b to a, then c is itself??. I'm struck with this. Please explain flip concept and if the book I'm referring is not good, suggest some other materials

like image 858
Previnkumar Avatar asked Aug 29 '26 07:08

Previnkumar


1 Answers

The flip function reverses the order of arguments of a two-argument function. Consider a simple subtract function:

subtract :: Int -> Int -> Int
subtract a b = a - b

subtract 4 3
-- 4 - 3 = 1

If flip is called on the subtract function, it changes which number is being subtracted from:

(flip subtract) 4 3
-- 3 - 4 = -1

It also works with functions of differing argument types:

showIntAndString :: Int -> String -> String
showIntAndString int string = (show int) <> string

showIntAndString 4 "asdf"
-- "4asdf"

(flip showIntAndString) "asdf" 4
-- "4asdf"

If it makes more sense to you, try looking at flip as a function which accepts a two-argument function as an argument and returns another two-argument function as a result:

flip :: forall a b c.
    (a -> b -> c) -- takes a function
    -> (b -> a -> c) -- returns a function with flipped arguments

One of the use cases for flip is when you want to partially apply a function, but the argument you want to partially apply is on the second place. You can then flip the original function, and partially apply the resulting function.

like image 100
bklaric Avatar answered Sep 02 '26 15:09

bklaric