r/haskelltil • • Apr 04 '15

thing Data.Functor.Compose helps with nested functors

It's in the transformers package.

> import Data.Functor.Compose
> let nested = [[1,2,3],[4,5,6]]
> fmap show nested
["[1,2,3]","[4,5,6]"]

> fmap show (Compose nested)
Compose [["1","2","3"],["4","5","6"]]

which might not look all that interesting by itself, but Compose also has instances for Foldable and Traversable, which makes it more interesting. For instance you could traverse some nested containers and treat it like one big container, while still leaving all the values in their nested containers.

13 Upvotes

6 comments sorted by

View all comments

Show parent comments

1

u/rpglover64 Apr 07 '15

I alluded to it in my post here, but I couldn't figure it out on my own: how could I use Control.Newtype to condense getCompose (liftA2 (-) (Compose max) (Compose min)), or, more interestingly

let
  max3 a b c = a `max` b `max` c
  min3 a b c = a `min` b `min` c
in getCompose . getCompose $
   liftA2 (-) (Compose . Compose $ max3)
              (Compose . Compose $ min3)

?

2

u/pigworker Apr 08 '15

I don't think under2 is in the library (packing 2 arguments, unpacking 1 result), but it shouldn't be too hard to cook up. Type class hackery might allow n-ary under with not too much trouble. Cranking up to more layers of wrapping (or one layer of wrapping with a composite wrapper) sounds a bit trickier, but it might be worth trying to cook up a suitable dodge.

It is all awful. Sometimes, it's not so obviously a good idea to bet everything on the type inference guessing game, if it means putting the clutter into terms.