Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function to reverse function call

Tags:

haskell

I have a lambda \x f -> f x that is being used in a foldM operation, where x is a value and f :: a -> b.

Is there a built-in function that does this?

Can I replace

foldM (\x f -> f x) ...

with some f'

foldM f' ...

I thought that flip would do this, but it takes three arguments (flip :: (a -> b -> c) -> b -> a -> c)

It is probably similar to |> in F#.

like image 689
Ralph Avatar asked May 30 '12 12:05

Ralph


2 Answers

You can use flip id or flip ($) (as ($) is just a special id for functions):

Prelude> flip id 3 (+2)
5
Prelude> flip ($) 7 (>10)
False

This is an interesting use of partial application: id f x with f being a function is just f x. Obviously, this is also the same as (flip id) x f, so flip id is the function you are looking for.

If you feel adventurous, try inferring the type of flip id or flip ($) manually. It's fun :)

like image 107
Niklas B. Avatar answered Oct 05 '22 18:10

Niklas B.


Yes, it's called flip :: (a -> b -> c) -> b -> a -> c, e.g. flip (>) 3 5 == True. More infos and source on hackage: flip.

What you want is simply to reverse the arguments of function application, right? Well, since ($) is function application, by using flip you may write flip ($) :: b -> (b -> c) -> c. Let see what happens. Here is the source for the two prelude functions:

-- from Hackage:
($)                     :: (a -> b) -> a -> b
f $ x                   =  f x

-- from Hackage:
flip                    :: (a -> b -> c) -> b -> a -> c
flip f x y              =  f y x

So, basically if you put together the types, flip ($) becomes

flip ($) :: 
  b        ->    -- type of x, argument of y and second argument of ($)
  (b -> c) ->    -- type of y, function applied by ($) as its first argument
  c        ->    -- result of the application "y x"

If you follow the actual definitions of the functions:

flip ($) = (\f x y -> f y x) ($)    -- from flip's def.
         = \x y -> ($) y x          -- partial application
         = y x                      -- from ($)'s def.
like image 25
Riccardo T. Avatar answered Oct 05 '22 18:10

Riccardo T.