alanrgan / rust-interpreter

0 stars 0 forks source link

Add closures #2

Closed alanrgan closed 7 years ago

alanrgan commented 7 years ago

Closure syntax

\<a,b,....,n> -> STATEMENT

Example:

\a -> { a + 1; }

Closures will have type Func<(T1,T2,...,Tn), K> where Ti corresponds to the type of the argument at position i, and K corresponds to the return value of the closure.

Examples

The following is the signature for a function that takes a closure that takes no arguments and returns an int fn foo(f: Func<_, int>) : int { return f(); } assert(foo(\_ -> 5), 5)

Closures copy any referenced variables from the calling environment.

alanrgan commented 7 years ago

What would the type of x be in the following statement: let x: ? = \a,b -> a+b;

Without a type inference system similar to that in Haskell, the type of x is completely ambiguous.

Closures would be better expressed in full form with explicitly annotated types as such:

let x: Func<(int, int), int> = fn(a: int) : int {
   return a + b;
}
alanrgan commented 7 years ago

Hopefully once basic type inference is implemented, types will not have to be explicitly annotated in let statements.

let x = fn(a: int) : int { return a + b; }

alanrgan commented 7 years ago

Implemented via this commit