Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial application in Haskell with multiple arguments

Given some function f(x1,x2,x3,..,xN) it is often useful to apply it partially in several places. For example, for N=3 we could define g(x)=f(1,x,3). However, the standard partial application in Haskell does not work this way and only allows us to partially apply a function by fixing its first arguments (because all functions actually only take one argument). Is there any simple way to do something like this:

g = f _ 2 _
g 1 3

with output the value of f 1 2 3? Of course we could do a lambda-function

g=(\x1 x3 -> f x1 2 x3)

but I find this quite unreadable. For example, in Mathematica it works like this, which I find quite nice:

g=f[#1,2,#2]&
g[1,3]

with output f[1,2,3].

Edit: Maybe I should say somehting more about the motivation. I would like to use such partially applied functions in point-style compositions, i.e., in expressions like this:

h = g. f _ 2 . k

to get h 3 = g(f(k(3),2)).

like image 377
Henrik Wilming Avatar asked Sep 20 '14 17:09

Henrik Wilming


1 Answers

You could read this question on how to change the order of arguments, then use partial application, but really the cleanest and clearest way of doing that currently in Haskell is just directly:

g x y = f x 2 y
like image 57
AndrewC Avatar answered Sep 20 '22 02:09

AndrewC