Search code examples
rascal

Returning values and statements from functions


I am wondering about the difference in behaviour between using the return statement and defining a function with the pattern foo() = Expression

It's my understanding from: Funtions that a function body can be = Expression and return takes either nothing or an Expression

The reason I am asking is that by my understanding of the documentation the following shouldn't work:

map[int,int] foo(map[int,int] env) = env[0] = 1;

Which it doesn't (causing a parse error) since assignment is a Statement. However, if I slightly modify this function:

map[int,int] foo(map[int,int] env) { return env[0] = 1; }

This seems to work. I am confused because I though return should only take expressions. Also, it looks like from playing around on the REPL this assignment returns a Value so it would be nice be able to define functions that assign and return the modified map.

Maybe I am missing something here though.


Solution

  • Your understanding is fine. The return statement has some extra flexibility though to allow returning the value produced by selected statement kinds such as 'for' and assignment apparently too. See the syntax definition of the return statement in the Rascal grammar here

    In future versions we may remove all restrictions and allow statements everywhere.