Using items in a list as arguments

Posted by Travis Brown on Stack Overflow See other posts from Stack Overflow or by Travis Brown
Published on 2010-05-24T18:27:06Z Indexed on 2010/05/24 18:31 UTC
Read the original article Hit count: 201

Suppose I have a function with the following type signature:

g :: a -> a -> a -> b

I also have a list of as—let's call it xs—that I know will contain at least three items. I'd like to apply g to the first three items of xs. I know I could define a combinator like the following:

($$$) :: (a -> a -> a -> b) -> [a] -> b
f $$$ (x:y:z:_) = f x y z

Then I could just use g $$$ xs. This makes $$$ a bit like uncurry, but for a function with three arguments of the same type and a list instead of a tuple.

Is there a way to do this idiomatically using standard combinators? Or rather, what's the most idiomatic way to do this in Haskell? I thought trying pointfree on a non-infix version of $$$ might give me some idea of where to start, but the output was an abomination with 10 flips, a handful of heads and tails and aps, and 28 parentheses.

(NB: I know this isn't a terribly Haskelly thing to do in the first place, but I've come across a couple of situations where it seems like a reasonable solution, especially when using Parsec. I'll certainly accept "don't ever do this in real code" if that's the best answer, but I'd prefer to see some clever trick involving the ((->) r) monad or whatever.)

© Stack Overflow or respective owner

Related posts about haskell

Related posts about functional-programming