[Haskell-cafe] list comprehension with multiplegenerator|targets
Mateusz Kowalczyk
fuuzetsu at fuuzetsu.co.uk
Mon Nov 10 06:50:09 UTC 2014
On 11/10/2014 04:24 AM, Donn Cave wrote:
> quoth Raphaël_Mongeau <raphaelsimeon at gmail.com>
>
>> This :
>> pv a = [t | Just t <- pvc a]
>> is strange, can we really do pattern matching inside list comprehension?
>
> Sure, but from a list - I'm sorry, I meant "map pvc a", not "pvc a".
>
> pv a = [t | Just t <- map pvc a]
> where
> pvc A = Just 'A'
> pvc B = Just 'B'
> pvc _ = Nothing
>
> You know, the pattern match in the list comprehension is just what
> I wanted it for in the first place - remember ['A' | A <- s] ?
> That's OK, it just isn't useful because I can do this for only
> one target.
>
>> ... and I think is more clear with a lambdaCase.
>
> lambdaCase is a great thing, but given that it's hardly any different
>
>> pv l = catMaybes $ flip map l $ \case
>> A -> Just 'A'
>> B -> Just 'B'
>> _ -> Nothing
>
> from
>
> pv l = catMaybes $ map pvc l
> where
> pvc A = Just 'A'
> pvc B = Just 'B'
> pvc _ = Nothing
catMaybes . map f = mapMaybe f
Also I wonder if laziness saves us here: in the original program we
effectively do map and filter at the same time. If we were to take
(catMaybes . map f) with strict evaluation then we'd be traversing
twice: once to map and once to catMaybes… Just something to think about,
I think performance would be no worse anyway, at least not by much.
> ... in this case I don't think we're desperate enough to use a
> nonstandard extension.
I wouldn't worry about using a ‘non-standard’ extension: you're probably
not going to stick to H98 or H2010 in non-trivial programs either way.
LambaCase is just a trivially expandable sugar anyway, modulo clean
identifier name.
--
Mateusz K.
More information about the Haskell-Cafe
mailing list