[Haskell-cafe] apply function arguments in a list

Neil Brown nccb2 at kent.ac.uk
Mon Oct 5 10:43:49 EDT 2009

Michael Mossey wrote:
> If I have a list containing the arguments I want to give to a 
> function, is there a general way to supply those arguments in a 
> compact syntax?
> In other words, I could have
> args = [1,2,3]
> f x y z = ...
> I would write
> t = f (args!!0) (args!!1) (args!!2)
> but there may be a neater, more general syntax.
In general, the problem is that you can't guarantee ahead of time that 
the list will have three elements, so however you write it, you'll turn 
a compile-time error (wrong number of args to function) into a run-time 
error (!! says index is invalid).  The neatest way is probably:

t [x,y,z] = f x y z

Which will give a slightly better error if the list is the wrong size.  
If your function takes many arguments of the same type, perhaps you 
could generalise it to take a list of arbitrary size, and do away with 
requiring three arguments?  Alternatively, use tuples if you want an 
easy way to carry the arguments around together:

args = (1, 2, 3)
f x y z = ...

uncurry3 f (x,y,z) = f x y z

t = uncurry3 f

(uncurry already exists, I think uncurry3 is one you have to add yourself).


More information about the Haskell-Cafe mailing list