alanrgan / rust-interpreter

0 stars 0 forks source link

First-class functions #8

Closed alanrgan closed 7 years ago

alanrgan commented 7 years ago

Functions should be able to be returned from other functions:

fn foo() : Func<int, _> {
    return fn(a: int) { print(a); };
}
foo()(3); // should print 3

Considerations

What scope will the returned function be defined in, and how will chained function calls be handled? In the above example, foo() needs to be evaluated before '3' is passed into the returned function.

Proposed solution is to push parameters onto a queue and then consume the queue at its head two at a time:

// Queue, where first element is the base function
foo -> [] -> [3] -> $
// reduces to
bar -> [3] -> $
// reduces to
baz -> $ // which then reduces to a single value
alanrgan commented 7 years ago

With regard to scope, we have to consider the following cases:

Returning a FnPtr

fn foo() : Fn<_,_> {
     let x: Fn<_,_> = fn { print("hi"); };
     return x;
}

The function fn { print("hi"); }; is not defined in the caller scope and only a FnPtr is returned.

Chained returns

fn foo() : Fn<_,_> {
    return fn { print("hi");};
}

fn bar() : Fn<_,_> {
    return foo();
}

Possible solution

Pass definition upstream