GeneralBecos
GeneralBecos

Reputation: 2556

Applying tuple of functions to a tuple

I'm trying to apply a tuple of functions to a tuple of values

λ> let foo = ((+1), (*3), ((:)5))  #Each function has type: a -> a

λ> let bar  = (1, 5, [0])          #Each value of the corresponding tuple has type a

How do I implement:

toImplement foo bar = ?

such that:

λ> toImplement foo bar
-> (2, 15, [0,5]) # using foo and bar above

How can you implement this in general for any valid foo and bar (of the same length)?

[I looked at this problem, but it is implemented for a fixed type. I require a general implementation]

Motivation:

I'm trying to write folds efficiently.

let acc1 = \x acc -> x*x:acc
let acc2 = (+)
foldr (\x acc -> (acc1 x (fst acc), acc2 x ( snd acc))) ([],0) [1..10]
> ([1,4,9,16,25,36,49,64,81,100],55)

I have 2 different accumulators acc1 & acc2 that loop over the list exactly once. I'd like to do this for arbitrary number of accumulators all of whom have type a -> b [where a is the type of the elements in the list and b is of the type of the output of the accumulator] It looks clumsy, having to access the tuples using fst and snd :/

Upvotes: 2

Views: 1013

Answers (1)

zerkms
zerkms

Reputation: 254906

As mentioned in the comments, haskell does not allow one to implement generic functions for tuples of arbitrary size. Hence you need to implement a particular function for every size separately.

Eg:

toImplement3 :: (b0 -> c0, b1 -> c1, b2 -> c2) -> (b0, b1, b2) -> (c0, c1, c2)
toImplement3 (f1, f2, f3) (a1, a2, a3) = (f1 a1, f2 a2, f3 a3)

Upvotes: 6

Related Questions