Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "unpack" a list as individual arguments in Haskell? [duplicate]

Is there builtin or idiomatic way in Haskell to "unpack" the elements of a list and treat them as individual arguments to a function?

For example, if I have f :: a -> b -> c -> d -> e is there something compact like

f (unlist x)

accomplishes

let x = [1,2,3,4] in f (x!!0) (x!!1) (x!!2) (x!!3) 

or at least a less "shouty" (too many !! repetitions) way to unpack a list of known length in general (so that it can be used as arguments to a function, in this case).


Essentially what I'm looking for is something like what Sequence@@ does in Mathematica:

f[Sequence@@{1, 2, 3, 4}]
like image 251
orome Avatar asked Sep 13 '15 18:09

orome


1 Answers

It wouldn't be particularly useful in Haskell type system:

  1. As Mephy points out, you'd need a separate function for each list length, and it would fail at runtime when passed a list with wrong length;
  2. All arguments would have to have the same type.

Given this, use of tuples makes more sense than lists, as it avoids both problems; the standard library includes uncurry which does this for functions of 2 arguments, and you could define uncurry3, etc. by analogy:

uncurry3                 :: (a -> b -> c -> d) -> ((a, b, c) -> d)
uncurry3 f (a, b, c)     =  f a b c
like image 178
Alexey Romanov Avatar answered Oct 15 '22 10:10

Alexey Romanov