[Haskell-cafe] Pattern matching: multi constructors to same branch

Michael Sloan mgsloan at gmail.com
Wed Sep 12 01:04:48 CEST 2012


I've seen this asked before, and I think some languages support it (ML
maybe?).  One way to do this is with view patterns:

g f C = [f C]
g f (getVN -> (v, n)) = f v : g f n

getVN v@(A _ n) = (v, n)
getVN v@(B _ n) = (v, n)

(I changed the recursive call to g - figured you meant passing along f)

If you need to still have match clauses after that, for falling
through when it's not something that getVN matches, then have it yield
a Maybe, and match on Just.

-Michael

On Tue, Sep 11, 2012 at 9:43 AM, Thiago Negri <evohunz at gmail.com> wrote:
> Is it possible to capture more than one constructor in a single
> pattern matching?
> I mean, is it possible to generalize the following pattern matching of
> A and B to a single branch?
>
> g f C = [f C]
> g f v@(A _ n) = f v : g n
> g f v@(B _ n) = f v : g n
>
> For example:
>
> g f C = [f C]
> g f v@(A|B _ n) = f v : g n
>
> Or:
>
> g f v =
>     case v of
>         C -> [f C]
>         A|B -> f v : g (n v)
>
>
> Thanks.
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe



More information about the Haskell-Cafe mailing list