1

I should get Maybe UserId from maybeAuth

I am going to do it this way:

... = do
  muserId <- (entityKey <$>) <$> maybeAuth
...

So, I am looking to map Functor inside another Functor. I heard about Functor composition, is it my case?

Can I improve it using Functor Composition or something else?

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
mkUltra
  • 2,828
  • 1
  • 22
  • 47
  • 1
    Given that you claim to be in a `do` block, you probably can't improve it much. [Functors compose, but monads don't.](https://stackoverflow.com/q/7040844/791604) But see also [`MaybeT`](https://stackoverflow.com/q/33005903/791604), depending on what you want to happen with `Nothing`s. – Daniel Wagner Sep 09 '19 at 18:33
  • @DanielWagner There's a (slim) chance he's in `ApplicativeDo`. – Joseph Sible-Reinstate Monica Sep 09 '19 at 18:58

1 Answers1

3

As a general approach, you could use Data.Functor.Compose. Here's an example that composes a list of maybes:

Prelude Data.Functor.Compose> ff = Compose [Just 42, Just 1337, Nothing, Just 2112]
Prelude Data.Functor.Compose> :t ff
ff :: Num a => Compose [] Maybe a
Prelude Data.Functor.Compose> fmap (show . (+1)) ff
Compose [Just "43",Just "1338",Nothing,Just "2113"]
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 5
    Of course, `getCompose (fmap f (Compose x))` isn't a huge improvement over `fmap (fmap f) x`. – chepner Sep 09 '19 at 19:21
  • (Unless you want to factor out a helper like `let deepMap f = getCompose . fmap f . Compose in deepMap entityKey maybeAuth`.) – chepner Sep 09 '19 at 19:22
  • I found this library that looks interesting: https://hackage.haskell.org/package/composition-extra-2.0.0/docs/Data-Functor-Syntax.html#v:-60--36--36--62- – mkUltra Sep 09 '19 at 19:43
  • Do you think `fmap f <$> x` looks better? – mkUltra Sep 11 '19 at 12:10