Matching not working

MrGumby
Mausschubser
Beiträge: 65
Registriert: 16. Apr 2013 15:07

Matching not working

Hi,
I can not see, why this shouldn't match, but it doesn't: I have

Code: Alles auswählen

maybeMethod= Some(Method(New('Dummy,WrappedArray()),WrappedArray()))
but when matching maybeMethod, it jumps straight over

Code: Alles auswählen

case Some(Method(body, params))
to case _.

Can anybody explain, why this doesn't work? Also maybe why Symbol* and Expr* become WrappedArrays? I can't find a lot of material on regex patterns in Scala....

Talaron
Mausschubser
Beiträge: 85
Registriert: 26. Apr 2012 11:34

Re: Matching not working

Sorry for the long delay, but maybe some explanation is still helpful for you or others:

The *-parameters are not supposed to be regular expressions or something like this but simply a way to allow methods (or in our case case classes) to take an arbitrary number of arguments (the keyword if you wanna Google that is varargs). Maybe the test cases are also helpful to see how you can use *-parameters.

This also means that instead of

Code: Alles auswählen

maybeMethod= Some(Method(New('Dummy,WrappedArray()),WrappedArray()))
you can simply write

Code: Alles auswählen

maybeMethod= Some(Method(New('Dummy)))
as no parameters are also a possible option.

If you ever need to convert an actual List[X] into a "list" of parameters for a function expecting X*-arguments, you can simply write

Code: Alles auswählen

New('Dummy, myScalaList:_*)
to perform the necessary conversion.

Also, you can do the opposite to convert *-arguments into a list in pattern matching by writing

Code: Alles auswählen

case New(className, args @ _*)
We already have some comments and the conversion shown above in the template for the task, so for your work you can simply assume that args is a regular list.

Oh and about your posted code: Your code fragment probably doesn't work because your pattern matching doesn't do the @ _* part, which means that it specifically requires the matched method to have exactly one parameter (while WrappedArray() is equivalent to no parameters).

MrGumby
Mausschubser
Beiträge: 65
Registriert: 16. Apr 2013 15:07

Re: Matching not working

Thanks, that explanation would have been nice to have in the task description...
Mind you, that not everyone in this course does know the tweaks of Scala and researching this makes the task so much more time-consuming.

Talaron
Mausschubser
Beiträge: 85
Registriert: 26. Apr 2012 11:34

Re: Matching not working

Thanks for the feedback! Although I'm not one of the organizers of the lecture, I'm sure they appreciate it.

In their defense however, the term "varargs", how to match them and even an example usage for the Seqn-case are already given in the template with a (probably not sufficiently detailed) comment.