Use sharing in the Alternative instance of Maybe

Bas van Dijk v.dijk.bas at gmail.com
Wed Dec 14 13:17:08 CET 2011


On 14 December 2011 12:51, Michael Snoyman <michael at snoyman.com> wrote:
> Out of curiosity, does this actually bypass an extra allocation, or is
> GHC smart enough to notice the possibility to share?

With optimizations on, GHC seems to be smart enough. Since the
optimized core of:

plus1 Nothing  r = r
plus1 (Just x) _ = Just x

Looks like:

Maybe.plus1 =
  \ (@ a_acI)
    (ds_dcO :: Data.Maybe.Maybe a_acI)
    (r_abo :: Data.Maybe.Maybe a_acI) ->
    case ds_dcO of wild_X6 {
      Data.Maybe.Nothing -> r_abo;
      Data.Maybe.Just x_abp -> wild_X6
    }

Which is equivalent to the optimized core of:

plus2 Nothing r = r
plus2 l       _ = l

Which looks like:

Maybe.plus2 =
  \ (@ t_acG)
    (ds_dcK :: Data.Maybe.Maybe t_acG)
    (r_abq :: Data.Maybe.Maybe t_acG) ->
    case ds_dcK of wild_X7 {
      Data.Maybe.Nothing -> r_abq;
      Data.Maybe.Just ipv_scU -> wild_X7
    }

With -O0 the core of plus1 looks like:

Maybe.plus1 =
  \ (@ a_acG)
    (ds_dcM :: Data.Maybe.Maybe a_acG)
    (r_abm :: Data.Maybe.Maybe a_acG) ->
    case ds_dcM of _ {
      Data.Maybe.Nothing -> r_abm;
      Data.Maybe.Just x_abn -> Data.Maybe.Just @ a_acG x_abn
    }

Cheers,

Bas



More information about the Libraries mailing list