Ask Your Question
0

How to patternmatch a specific constructor in a list?

asked Jan 24

JasperT gravatar image JasperT
33 1 5 11

Hi,

Can I match on constructors in a list and get a list of that specific constructor? Something like this:

list[MyType] lst = [a(1), b(1), c(1), a(2), b(2), c(2)];
if ([A*, b(_) B*, C*] := lst) {
    println("got the b's: <B>");
}

Thanks,

Jasper

delete close flag offensive retag edit

1 Answer

Sort by ยป oldest newest most voted
1

answered Jan 24

PaulKlint gravatar image PaulKlint flag of Netherlands
373 5 16 33
http://www.cwi.nl/~paulk

updated Jan 24

The short answer is no. The reason is that b(_) is not a legal type. There are, fortunately, other ways to solve this.

Assuming that MyType is for instance:

data MyType = a(int i) | b(int i) | c(int i);

and that your goal is to filter out all b(_) occurrences from the list, something like

[ X | X:b(_) <- lst]; (with value [ b(1), b(2)])

may solve your problem. Observe the X:b(_) that matches each element of MyType with b(_) and assigns it to X when it matches. See http://tutor.rascal-mpl.org/Courses/Rascal/Patterns/Abstract/Labelled/Labelled.html for details.

link delete flag offensive edit

Comments

Thanks, I think I was just too deep in the code. After this answer it was very easy to figure it out.

JasperT (Jan 24)edit

Your answer

Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!
[hide preview]
Also see the Rascal Tutor.

Question tools

Follow

subscribe to rss feed

Stats

Asked: Jan 24

Seen: 15 times

Last updated: Jan 24