aplavin
aplavin

Reputation: 2229

Tuple mapping in Haskell

I don't know how it's usually called, but what I need is something like this:

f a b c = a + 2 * b + 3 * c

map f [(1,2,3), (4,5,6), (7,8,9)]

i.e. mapping list of n-tuples to a function with n separate arguments. Is there a built-in way to do this in Haskell?

P.S.: I've found uncurry just now, but it doesn't seem to work this way with 3 arguments, only with 2.

Upvotes: 0

Views: 2754

Answers (3)

is7s
is7s

Reputation: 3480

You can define your own function:

uncurry3 :: (a -> b -> c -> d) -> (a,b,c) -> d
uncurry3 f (a,b,c) = f a b c

map (uncurry3 f) [(1,2,3), (4,5,6), (7,8,9)]

Alternatively, you can use uncurryN from the tuple package which works for tuple sizes up to 15:

cabal install tuple

import Data.Tuple.Curry

map (uncurryN f) [(1,2,3), (4,5,6), (7,8,9)]

Upvotes: 8

Fred Foo
Fred Foo

Reputation: 363517

I'm not aware of any general solution to this problem, but the practical solution would be

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

Then

map (uncurry3 f) [(1,2,3), (4,5,6), (7,8,9)]

Upvotes: 0

jdevelop
jdevelop

Reputation: 12296

in general, no - because tuples are not so generic as lists, and may have different data types

however you may rework your tuples in the way of ((a,b), c) and then you may want to use either fst/snd combinations or Arrows to generalize your computations.

Upvotes: 2

Related Questions