gale at sefer.org
Wed Dec 28 20:02:18 UTC 2016
Imants Cekusins wrote:
> foldl (<|>) Nothing [Nothing, Just 1, Nothing, Just 2]
> Just 1
Apart from Ollie's suggestion of asum, here are a few
more interesting points that come up from your
In your solution, you would want to use foldr, not foldl.
The left fold forces reading the entire list to the end even though
you already hit your Just. A right fold will short circuit. That also
means the right fold will even work with an infinite list, as long
as there is at least one Just somewhere in the list.
(Note that asum uses foldr under the hood. :))
And if you still do use a left fold, you'll want foldl' (from Data.List)
rather than foldl. The foldl from the Prelude will build up
a pile of unevaluated lazy thunks the size of your list, and
only then evaluate all the <|> calculations all at once. So
this will crash with a stack overflow error if your list is very
large. Whereas foldl' will perform all of the <|> calculations
one by one in constant memory.
More information about the Beginners