Reputation: 262
In Haskell (and quite similar in Prolog / Erlang), we can define a length function over lists as:
length [] = 0
length (x:xs) = 1 + length xs
In Rascal, I was able to create a definition like this using:
int length([]) = 0;
int length([x,xs*]) = 1 + length(xs);
The "*" disappears on the right hand side of the recursive case of length. I know that it might exist a reason for that, but I could not figure it out. Is there a better approach for defining recursive functions over lists using pattern matching in Rascal?
Upvotes: 1
Views: 428
Reputation: 1406
There are various aspects of your question that I want to address:
*
to indicate just that.We are in a transitional phase where we are moving from the postfix * to a prefix *. So the second rule can be (and in the future should be) written as:
int length([x,*xs]) = 1 + length(xs);
You may want to explore the reducer expression that can be used to write various fold-like functions:
int length(list[int] xs) = ( 0 | it + 1 | x <- xs );
It consists of three parts:
it
is set to this initial value.it
, here: it + 1
. It has as effect it = it + 1
.[*x, a]
: match the element at the end of a list[*x, *x]
: split the list in two equal halves [*a, x, *b, x, *c]
: find two duplicate elementsint length([x,*xs]) = 1 + length([*xs]);
, of course this also generalizes, so this is also possible: [*xs, 2, *xs]
where the *
operator simply removes one layer of list nesting. Upvotes: 2