#43 Closure syntax

brian Fri 10 Feb 2006

One of the things that has been bothering me about our closure syntax is that it doesn't jive well with how we do braces:

list.each
{
  |Str s|
  s.dosomething
}

If we make the transition to change how we do braces, then we could do this:

list.each { |Str s|
   s.dosomething
}

Another option I've been thinking about is to move the |sig| outside of the braces:

list.each |Str s|
{
  s.dosomething
}

What do you guys think?

andy Fri 10 Feb 2006

I think outside the sig makes more sense anyways, since that is how other methods are declared:

list.each |Str s| { ... }
list.each |Str s|
{
  ...
}

Also, that way, its consistent in both single and multi line styles - instead of using a different sytanx a la Ruby.

brian Fri 10 Feb 2006

Ok, I reworked the compiler and tests to use the |...| {...} syntax:

list.each |Str s| { echo(s) }

list.each |Str s|
{
  echo(s)
}

list.each |Str s, Int i|
{
  echo("list[" + i + "] = '" + s + "'")
}

map.each |Str val, Str key|
{
  echo(key + " = " + val)
}

Actually I like it a lot better - it looks more like a normal "method definition" of signature followed by method body. Plus it looks better when you put the opening brace on it's own line.

I also fixed a grammar problem to allow method type literals:

Type f() 
{ 
  return |Int->Real|.type
}

brian Thu 22 Jun 2006

Previously if you wanted to do a no arg closure you could use a double pipe:

verifyErr(Err.type) || { Int.parse("x") }  // same as below
verifyErr(Err.type) |->Void| { Int.parse("x") }

I really disliked that, so now I allow you leave the braces off completely for no arg closures - but removed support for the double brace symbol. So now you write the above as:

verifyErr(Err.type) { Int.parse("x") } 

andy Thu 22 Jun 2006

Actually its a good thing you did that, because I saw that code in the test suite and thought you were doing some OR comparison somehow, and didn't really understand it. So this should clear up code as a side effect.

brian Tue 27 Jun 2006

We gotta change the no arg closure syntax because just a {} is likely going to conflict with "with blocks". Alternatives:

x.times || { doSomething() }
x.times | | { doSomething() }
x.times |-| { doSomething() }
x.times |->| { doSomething() }
x.times |,| { doSomething() }

andy Tue 27 Jun 2006

I vote |,|

brian Tue 27 Jun 2006

Ok I changed the syntax for no arg closures to be |,| - examples:

x.times |,| { echo("hello") }
verifyErr(Err.type) |,| { bad() }

If we change our mind or figure out later that we can use just braces, then at least that symbol will be easy to search and replace.

Login or Signup to reply.