Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - apply tuple of functions to tuple of values?

I have a tuple of values representing some state, and want to translate it by an addition (shift). My values are a longer version of ( Int, [Int], Int), and I want something conceptually (but not literally) like this:

shift n = ??? (+n) (id, map, id)     -- simple(?)

which would be equivalent to:

shift n (a, b, c) = (a+n, map (+n) b, c+n)

I am happy to just go with this explicit function usage, but wondered it there was a more idiomatic point-free version using Applicative or Arrows or ..., or if they would just end-up obfuscating things. I thought that the point-free version shows the basic structure of the operation more clearly.

like image 213
guthrie Avatar asked Sep 29 '14 03:09

guthrie


1 Answers

You can just write

shift n (a,b,c) = (a+n, map (+n) b, c+n)

Or define new combinators similar to Arrow's (***) and (&&&),

prod3 (f,g,h) (a,b,c) = (f a, g b, h c)     -- cf. (***)
call3 (f,g,h)  x      = (f x, g x, h x)     -- cf. (&&&)
ap3    f      (a,b,c) = (f a, f b, f c)
uncurry3  f   (a,b,c) =  f a    b    c

and then call

prod3 ( (+n), map (+n), (+n) ) (a,b,c)

or even (with appropriately set operator precedences)

ap3 ($ (+n)) (id, map, id) `prod3` (a,b,c)

Or, if you'd write your triples as nested pairs, you could use

Prelude Control.Arrow> ( (+5) *** map (+5) *** (+5) ) (1,([2,3],4))
(6,([7,8],9))

So for nested pairs,

shift' :: (Num b) => b -> (b, ([b], b)) -> (b, ([b], b))
shift' n = ( (+n) *** map (+n) *** (+n) )

(see also Multiple folds in one pass using generic tuple function)

like image 141
Will Ness Avatar answered Sep 20 '22 00:09

Will Ness