Use sharing in the Alternative instance of Maybe
Christian Maeder
Christian.Maeder at dfki.de
Thu Dec 15 13:16:23 CET 2011
Am 15.12.2011 11:02, schrieb Jon Fairbairn:
> Christian Maeder<Christian.Maeder at dfki.de> writes:
>
>> Am 14.12.2011 13:17, schrieb Bas van Dijk:
>>> 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
>>
>> I suggest to directly write this using case:
>>
>> l<|> r = case l of
>> Nothing -> r
>> Just _ -> l
>
> Why not
>
> plus1 Nothing r = r
> plus1 l@(Just x) _ = l
>
> or the equivalent written with<|>?
Obviously, that's a matter of taste. I consider multiple fundefs as
unnecessary syntactic sugar basically for pretty printed text books and
maybe for teaching. In teaching, I find that beginners tend to be less
able to use appropriate case expressions, though.
(Also many list comprehensions are mere map or filter expressions)
In a single fundef all arguments are uniquely named. It's clear when an
argument is not used at all.
In multiple fundefs you can get warnings for unused arguments for the
particular case, which may be an advantage but als makes corresponding
arguments look different. (Consistent naming of arguments is not enforced.)
In fact, I would not even mind much if I had to write my definitions like:
plus1 = \ l r -> case l of ...
I claim, that multiple fundefs provoked this discussed non-sharing code
(and the fall-through case).
Cheers Christian
More information about the Libraries
mailing list