defining a function with a block

38 views
Skip to first unread message

Eyal Farago

unread,
Jan 16, 2014, 5:05:41 AM1/16/14
to treehugg...@googlegroups.com
Hi,
I want to define a function that returns a value but does so in a compound statement.

the result should be something like this:

def foo(prm1 : Int) = {
...
...
x+y
}

notice that this is basically a valid Scala function definition, scala does not require a return type and allows one to 'assign' a body to a function.

I've tried to generate something like this with TreeHugger_2.10 v0.3.0 by doing this:

DEF("toBean") := BLOCK(stmts)

where stmts is a list of trees, this generates a procedure:

def toBean {
...
  }

as you can see, no assignment is generated :-(, this actually behaves like the docs says it should, but it doesn't make to much sense as replacing the block with LIT(0) will generate a function instead of a procedure.

according to the docs, I can workaround this issue by supplying a return type to DEF, which may be reasonable in this case, but I'd like to know:
sf there's a way to omit the return type, supply a block and still get a function definition instead of a procedure?

thanks,
Eyal.

Eugene Yokota

unread,
Jan 23, 2014, 12:35:01 AM1/23/14
to treehugg...@googlegroups.com
Hi Eyal,

Sorry about the late response. I was on a vacation for a while, and still catching up on things.

DEF("toBean") := BLOCK(stmts) not generating def toBean = {....} is an unfortunate design error.
Because treehugger uses (DEF("put") withParams(PARAM("x", IntClass)): Tree) for procedure declaration,
calling mkTree(BLOCK(stmts)) producing a procedure definition may be defensible,
but the problem is that this procedure behavior only happens when BLOCK appears at rhs:

scala> DEF("toBean") := LIT(0)
res0
: treehugger.forest.DefDef = DefDef(Modifiers(, , Map()),toBean,List(),List(List()),TypeTree(),Literal(Constant(0)))


scala
> treeToString(res0)
res1
: String = def toBean = 0

Since this behavior could be deeply ingrained to the user code, I can't change := BLOCK(...) at this point.
A lighter weight workaround may be to introduce a dummy type called InferredClass that can be used in place for the return type.
Could you open a github issue linking to this thread?

-eugene

Eyal Farago

unread,
Jan 23, 2014, 2:01:02 AM1/23/14
to treehugg...@googlegroups.com
Hi Eugene, 
thanks for your reply, I'll try to open an issue in github, never done it before so I hope I'd manage to do so and link it to this thread.

I think a better solution would be to introduce a new operator that can be used instead of :=, or a new builder that can be used instead of DEF.

BTW, does VAL suffer from the same behavior?

i.e. the following is valid scala:

val x = {
val y = 4
val z = 5
y+z
}

Scala doesn't require an explicit type for x, I hope treehugger doesn't as well :-)

thanks,
Eyal.
Reply all
Reply to author
Forward
0 new messages