TopConcurrency   InterferenceFinal words on Grace - things we didn't explain!

Final words on Grace - things we didn't explain!

We will continue development of Grace. Compiler will continue to run on web page, but also looking at new implementations.

Like to explain one feature that we've brushed over - anonymous functions.

When we write {n: Number -> ...}, it actually represents an anonymous function that we can evaluate using the apply method.

For example,

   def printSqr = {n: Number -> print(n*n)}
   
   sqr.apply(7)
   sqr.apply(-3)

prints 49 and 9 on consecutive lines. We can also use that function in a for loop:

   for(1..10) do {n: Number ->
       print(n*n)
   }

The for loop is really a predefined method of the form:

    for(e:List<T>) do (b:Block1<T>)

where

   type Block1<T> = {apply(e:T) -> Done}

Thus can also write

   for(11..20) do (printSqr)

Can also define parameterless functions and apply them:

   def wait = {print "hello"}

   print "ready"
   wait.apply
   wait.apply

prints "ready", then "hello", "hello"

Can use this to define your own control constructs. Suppose I wanted a while loop that checked the condition after each iteration, rather than before. In particular, it always executes the body at least once. We can define it as:

// type of a block/function taking an argument of type T and returning Done.
type Block1D<T> = {
  apply(elt:T) -> Done
}

// type of a block/function that takes no arguments, but returns a value of type T.
type Block0<T> = {
  apply -> T
}
method do(blk:Block1D<T>)while(condBlk: Block0<Boolean>) -> Done {
  blk.apply
  while(condBlk)do(blk)
}

Now I can write

var n:Number := 10
do {
  print(n)
  n := n-1
} while {n > 0}

We can even define if-then-else that way!!

Pulling back the covers a bit more, we can see that classes are really just an abbreviation for a class returning an object:

class c.new(...) -> C {
    ...
    method m(...) --> T {...}
    ...

is an abbreviation for

def c = object{
    method new(...) -> C {
       object {
           ...
           method m(...) --> T {...}
           ...
       }
    }
}

TopConcurrency   InterferenceFinal words on Grace - things we didn't explain!