jakt icon indicating copy to clipboard operation
jakt copied to clipboard

First-class functions and function types

Open nooga opened this issue 2 years ago • 1 comments

I think the language could benefit from having first-class functions neatly integrated into the syntax and type system.

Both C++ and Rust use "special syntax" for lambdas. C++ types for lambdas are (to my knowledge) nothing like function types and their semantics feels needlessly complex in my opinion.

Jakt still has a chance of being much more intuitive.

Let functions be objects of a function type, function type syntax follows function declaration syntax:

let f = function(x: i32) => x + 1 
// f : function(i32) -> i32

Pass functions to other functions:

frob.frobnicate(callback: function(result) {
  // ...
})
// frob.frobnicate : function(callback: function(anonymous result: FrobResult))

Using -> for return types maps nicely to function type notation:

function hello() -> function(String) -> String {
  return function(who: String) -> String {
    return "well hello " + who + "!"
  }
}
// hello : function() -> function(String) -> String 
// hello() : function(String) -> String

One could even take values of functions (or even bound methods) and treat them as ordinarily typed objects that could be passed to any function expecting to receive a function:

function compose<A, B, C>(f1: function(A) -> B, f2: function(B) -> C) -> function(A) -> C => function(a: A) => f2(f1(a))

function foo(x: i32) -> i32 {
  return x * 42
}

let f = compose(foo, function(x) => x + 96)
// f : function(i32) -> i32

I'm not proposing to make Jakt a functional-heavy language or make it so that it imposes functional style on the programmer. I just think that having lambdas is inevitable and it would be super nice if they were well integrated instead of bolted on as special guests.

nooga avatar May 22 '22 18:05 nooga

This is extremely good, the syntax looks fantastic, go ahead!

kleinesfilmroellchen avatar May 22 '22 18:05 kleinesfilmroellchen

Wasn't this already implemented?

maddanio avatar Oct 03 '22 16:10 maddanio

Wasn't this already implemented?

I think it was. I wrote this in the first days of jakt but didn't have time to work on this. Nonetheless, I think the current implementation seems to be very close to what I tried to describe here.

nooga avatar Oct 03 '22 16:10 nooga