Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

cascading if conditions

50 views
Skip to first unread message

blufox

unread,
Jun 16, 2012, 1:05:39 AM6/16/12
to
Hello,
I have a set of if conditions of this form,

case fna of
Just x -> x
Nothing -> case fnb of
Just y -> y
Nothing -> case fnc of
Just z -> z
Nothing -> defaltval

Is there a standard way to capture this pattern?

Regards,
blufox

Paul Rubin

unread,
Jun 16, 2012, 2:23:02 AM6/16/12
to
blufox <blu...@gmail.com> writes:
> case fna of
> Just x -> x
> Nothing -> case fnb of
> Just y -> y
> Nothing -> case fnc of
> Just z -> z
> Nothing -> defaltval
>
> Is there a standard way to capture this pattern?

I don't know if this is standard:

import Data.Maybe (catMaybes)

head . catMaybes $ [fna, fnb, fnc, Just defaltval]

blufox

unread,
Jun 16, 2012, 2:31:28 AM6/16/12
to
I didn't realize I could use that. I assumed that it would execute each
function and collect the results, but I now see that lazy evaluation would
ensure that only required functions are evaluated.

Thanks :)

Michael Karcher

unread,
Jun 16, 2012, 1:23:06 PM6/16/12
to
Paul Rubin <no.e...@nospam.invalid> wrote:
> I don't know if this is standard:
>
> import Data.Maybe (catMaybes)
>
> head . catMaybes $ [fna, fnb, fnc, Just defaltval]

Another solution (relying on the MonadPlus instance of Maybe):

import Control.Monad (msum)

msum [fna, fnb, fnc, Just defaultval]

Regards,
Michael Karcher

Paul Rubin

unread,
Jun 16, 2012, 1:32:32 PM6/16/12
to
use...@mkarcher.dialup.fu-berlin.de (Michael Karcher) writes:
> Another solution (relying on the MonadPlus instance of Maybe):
> import Control.Monad (msum)
> msum [fna, fnb, fnc, Just defaultval]

Oh nice, I like that better than my kludgy answer.

import Control.Monad (mplus)

fna `mplus` fnb `mplus` fnc `mplus` Just defaultval

should also work.

Paul Rubin

unread,
Jun 16, 2012, 2:43:22 PM6/16/12
to
Paul Rubin <no.e...@nospam.invalid> writes:
> import Control.Monad (mplus)
>
> fna `mplus` fnb `mplus` fnc `mplus` Just defaultval
>
> should also work.

Actually I think the following is better still in terms of naturalness:

import Data.Maybe (fromMaybe)
import Control.Monad (mplus)

fromMaybe defaultval $ fna `mplus` fnb `mplus` fnc

alternatively:

import Data.Maybe (fromMaybe)
import Control.Monad (msum)

fromMaybe defaultval $ msum [fna, fnb, fnc]

blufox

unread,
Jun 17, 2012, 1:27:37 AM6/17/12
to
> Another solution (relying on the MonadPlus instance of Maybe):
>
> import Control.Monad (msum)
>
> msum [fna, fnb, fnc, Just defaultval]
>
> Regards,
> Michael Karcher

Thanks, these are perfect .
--
blufox

chb hemma

unread,
Jun 24, 2012, 5:36:43 PM6/24/12
to
-- Make a helper:
infixr 2 |||
(|||) :: Maybe a -> a -> a
(Just a) ||| _ = a
Nothing ||| d = d

-- Use it like this:
fna ||| fnb ||| fnc ||| defaultval
0 new messages