Pattern matching: multi constructors to same branch

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Pattern matching: multi constructors to same branch

Thiago Negri
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
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe
Reply | Threaded
Open this post in threaded view
|

Re: Pattern matching: multi constructors to same branch

Michael Sloan
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 <[hidden email]> 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
> [hidden email]
> http://www.haskell.org/mailman/listinfo/haskell-cafe

_______________________________________________
Haskell-Cafe mailing list
[hidden email]
http://www.haskell.org/mailman/listinfo/haskell-cafe