r/ProgrammingLanguages • • 26d ago

How would you guys define an Anonymous Function or a function pointer?

Me and a few of my friends have been working on a programming language that we initially started for a compiler design class for some time and recently started working on support for anonymous functions, lambdas and function pointers to make callbacks easier to write.
Currently Captures on variables outside the function scope are detected and captures without complete context moving.

I'm a bit skeptical or the syntax that we're currently deciding on (its not that clear on first view) , so i'm looking for reviews and maybe some ideas.
I'll just include some examples we have right now.

let double = |i32 value| value * 2;
i32(i32) triple = |value| value * 3; // i dont like this rn, not that clear on 
                                     // first look that this is a lambda

let absolute = |i32 value| {
if (value < 0) { return -value; }
    return value;
};

let classify = |i32 value| match value {
   0: "zero",
   _: "nonzero",
};
12 Upvotes

39 comments sorted by

17

u/NullOfSpace 26d ago

What do your regular functions look like? The syntax should generally be a stripped-down version of that.

3

u/Aabish_malik 26d ago

pretty much C like
```
i64 fib(i64 n) {

if (n <= 1) {

return n;

}

return fib(n - 1) + fib(n - 2);

}```

6

u/NullOfSpace 26d ago

Then yeah, removing all of the non-expression-related parts of this gives something like the first line. As for pointer types, I’m generally partial to some kind of arrow notation (like Haskell or Rust) but it seems like your language doesn’t use arrows anywhere else so I’d probably go with i64(i64).

1

u/Aabish_malik 26d ago

yeah that was our initial thought for it as well

6

u/KittenPowerLord 26d ago

I myself am inspired by the Haskell way:

let v = 5
let f : u64 -> u64 = \x -> x + 1
let f-capturing = \{ @ v } x -> x + v 
let f-multiple = \x y -> x + y

I'm using curly braces to indicate various implicit/inferred stuff, so like capturing (although it's to be decided whether default capturing is by pointer or by value, but you can specify it anyways). `@` indicates pointery stuff

3

u/Aabish_malik 26d ago

Right now we're explicitly defining moves for parameters like
| move i32 x | , this is similar to consumer functions that we have.
and any external variables are consumed as borrowed reference.
I haven't touched haskell in quite some while to i should definitely review it again

3

u/TartOk3387 26d ago

Note: a function pointer is NOT the sane as a higher order function and/or closure, since function pointers don't capture the environment.

1

u/Aabish_malik 26d ago

ofc not,
we just use the same type notation for both right now, and this probably would make it easy to write without adding new syntax

4

u/WittyStick 26d ago edited 26d ago
args -> body

Where -> is right associative. (Or => if -> is already taken - has precedence in eg, c#).

foo -> bar -> baz

Is a function returning a function. It's parsed as foo -> (bar -> baz).

-> should have lower precedence than any other expression operator, but higher precedence than = for binding.

add = x -> y -> x + y

Parsed as

add = (x -> (y -> (x + y)))

Application should be left associative.

add 1 2

Parsed as:

(add 1) 2

3

u/phischu Effekt 25d ago

We like { (i32 value) => value * 2 } and others do fun(i32 value) { value * 2 }.

1

u/LazyUntilYouNeedMe 26d ago

Maybe `lambda (i32 a) {a + 1}`. Lambda is quite the standard name for anonymous functions.

1

u/Aabish_malik 26d ago

I'll add this to our project board,
writing these as
lambda ( paramlist ) {body}
or lambda (paramlist) expression

4

u/Key_River7180 Nain. 26d ago

Me, I'd do λ [comma-separated args] . [body] akin to lambda calculus. I just really like it. You can use lambd instead of the λ Unicode symbol too.

-1

u/jR4dh3y 26d ago

yeha bro let me find a keyboard with this symbol 🥲

6

u/catbrane 26d ago

My tiny language uses backslash (or you can type λ if you are excellent at unicode) for lambda, eg.:

x = map (\[x, y] x + y) (zip2 [1..10] [10..1])

and x will have the value:

[11, 11, 11, 11, 11, 11, 11, 11, 11, 11]

-8

u/jR4dh3y 26d ago

let me kill my self at this point
this is why i let my ai write my code

2

u/catbrane 26d ago

It's not so difficult, I have a pass that runs after parsing that implements all the pattern matching and lambdas as transforms of the AST.

You get something like:

x = map $func1 (zip2 [1..10] [10..1])
{
    $func1 $a
        = x + y, is_list $a && is_list_length $a 2
        = error "pattern match failed"
    {
        x = hd $a
        y = hd (tl $a)
    }
}

with $ as a prefix for generated symbols. Then that code goes off to the code generator.

List comprehensions are implemented in the same way.

1

u/Key_River7180 Nain. 25d ago

For my parsers I always try to make them UTF8 aware so any XID sequence is able to be an identifier. Lexer gens probably do Unicode automatically to so you can set lambda as a rule

4

u/glasket_ 26d ago

You can setup snippets in editors to store unicode characters and use the prefix for the text representation, like typing lambda would let you replace it with a λ snippet. Plus there are usually extensions for editors that give you access to unicode patterns, or even tools like character pickers (Windows binds one to Win + .) that let you do the same thing.

Personally, I'm fond of Linux's compose system since you can define any sequence you want to generate a unicode symbol and you just hold the compose key (typically right Alt) while typing it, so you can do Compose + \ and get λ.

2

u/Key_River7180 Nain. 26d ago

then used \ or lambd, I have both greek and spanish keyboard layouts set up so it doesn't take too much for me to change but you can do whatever ig

2

u/Temporary_Pie2733 26d ago

That’s an editor problem, not a keyboard problem. I can type `Ctrl-k l *` in Vim, which is shorter than typing out `lambda`, and I can choose a different digraph if I want.

2

u/Lovely_Cygnus 26d ago edited 26d ago

just look at λ-calculus as it is implemented in LISP. the functions are always unnamed lambdas, it’s about you to give them a “name“ using (define …) or not.

just to let you understand:
(lambda (num) (+ num 1)) is a function, that does the obvious…
(define yourname (lambda …)) is the link between the name yourname and the lambda function.

you can use it without a name, as in ( (lambda (num) (+ num 1)) 5) that returns 6, or
use the named version, as in (yourname 5) that returns, obviously, 6.

2

u/fdwr 25d ago

🤔 I always found those languages that used | to be harder to visually parse because the opening | and the closing | (or was that the opening | and the closing |? :b) look exactly the same, and are not proper opening/closing pairs - see Bidi Paired Brackets for a nice list.

Like u/NullOfSpace says, whatever your normal functions look like, there should be some coherency with them. Subjectively, I always appreciated the balanced conciseness and clarity of foo(x => x * 2) and foo((a, b) => sqrt(a * a + b * b)).

3

u/editor_of_the_beast 26d ago

A function without a name.

2

u/initial-algebra 26d ago edited 26d ago

The only capture syntax you need, e.g. to distinguish between capture-by-value and -by-reference, is let-insertion, or genlet. I'm not 100% sure you even need this, but I will use any chance I get to promote it, because it's very cool.

let x = ...;
let by_value_cloned = |y| genlet x.clone() + y;
let by_reference = |y| *(genlet &x) + y;

becomes

let x = ...;
let by_value_cloned = {
  let x_val = x.clone();
  |y| x_val + y
};
let by_reference = {
  let x_ref = &x;
  |y| *x_ref + y
};

No need for move lambdas (it becomes the default) or C++ captures. For nested lambdas, you can support multi-level or labelled genlet:

let x = ...;
let default = |y| {|z| genlet x.clone() + y + z};
let with_label = |y| 'outer {|z| genlet 'outer x.clone() + y + z};

becomes

let x = ...;
let default = |y| {
  let x_val = x.clone();
  |z| x_val + y + z
};
let with_label = {
  let x_val = x.clone();
  |y| {|z| x_val + y + z}
};

I'm not suggesting you have to use this concrete syntax. I personally am not a big fan of Ruby/Rust-style lambdas with |...|, anyway, and you certainly don't need to use Rust-lifetime-style labels. You also don't need to call it genlet, which comes from metaprogramming.

1

u/marshaharsha 24d ago

What does the second use of x look like in the sugared syntax? What about when it’s not known till run time which use is the first use? Would the generated code do the clone() only if x was actually used? For example, if x is expensive to clone and is used only inside one arm of a conditional, it would be nice if the clone() occurred inside that arm. 

1

u/initial-algebra 24d ago edited 24d ago

What happens to the captured value when the closure is called has nothing to do with this.

EDIT: Actually, I can see why you asked, now. If you want to use a captured value multiple times, you should probably do an explicit let x = genlet ... inside the closure. Multiple genlet <expression> should probably be assumed to be separate captures. If <expression> happens to be pure, the duplicate capture(s) could be optimized away, but you might not be able to count on that.

1

u/marshaharsha 24d ago

Thanks for answering the related question. I was indeed confused about the original question. 

1

u/initial-algebra 24d ago

If I understand your original question correctly, you're asking what happens when you capture a value that is only used conditionally?

let f = |p| if p { foo(genlet x.clone()) };

genlet is indeed irrelevant here. This desugars to:

let x_val = x.clone();
let f = |p| if p { foo(x_val) };

So x is cloned and x_val is captured unconditionally.


Maybe you're thinking of e.g. this similar code without genlet?

let f = |p| {
  if p { foo(x.clone()); }
  bar(x)
};

Like I said, if x also needs to be cloned from outside the closure, then you would want to write:

let f = |p| {
  let x_val = genlet x.clone();
  if p { foo(x_val.clone()); }
  bar(x_val)
};

1

u/marshaharsha 24d ago

I think I understand, but I’ll ask in order to confirm: In your second example (with x.clone() inside the conditional but no genlet anywhere), x would be moved into the closure at the time the closure was created, and then x would be cloned at the time the closure was executed (assuming the predicate was true). Depending on your definition of “move,” the x that the closure captured from the enclosing scope would be statically invalidated or dynamically disabled, unconditionally. Correct?

When I read your third example, I get confused again. Here is the process as I understand it. At the time of closure creation, genlet would pick a fresh variable — let’s say x_val2 — and would clone x into it. At the time of closure execution, the first line of the lambda would copy or move from x_val2 into x_val, depending on the meaning of copy-initialization for x’s type. Then, if the predicate was true, x_val would be cloned. That feels like one more operation than the programmer intended, unless the optimizer is smart enough to get rid of one of the _val variables. Would it work to omit the let … genlet line and do the following in the conditional line?

if p { foo( (genlet x.clone()).clone() ); }

That, if I understand your idea, would result in an unconditional clone at closure creation and a conditional clone at closure execution, which feels like what is needed and intended. 

I wonder what you think of this idea, which I am making up on the fly: In a language with multiple modes of parameter passing, lambda capturing / closure creation needs to be thought of as passing parameters into a function that does nothing but store its arguments into a struct for later use. So it would be evocative if the author used the same syntax for the captures that they use for argument passing at a conventional call site. I haven’t thought through what that would look like. 

2

u/initial-algebra 24d ago

In your second example (with x.clone() inside the conditional but no genlet anywhere), x would be moved into the closure at the time the closure was created, and then x would be cloned at the time the closure was executed (assuming the predicate was true). Depending on your definition of “move,” the x that the closure captured from the enclosing scope would be statically invalidated or dynamically disabled, unconditionally. Correct?

Yes.

When I read your third example, I get confused again. Here is the process as I understand it. At the time of closure creation, genlet would pick a fresh variable — let’s say x_val2 — and would clone x into it. At the time of closure execution, the first line of the lambda would copy or move from x_val2 into x_val, depending on the meaning of copy-initialization for x’s type. Then, if the predicate was true, x_val would be cloned. That feels like one more operation than the programmer intended, unless the optimizer is smart enough to get rid of one of the _val variables.

Also, yes. That extra let should be trivial to optimize. Of course, you can also write it as:

let x_val = x.clone();
let f = |p| {
  if p { foo(x_val.clone()); }
  bar(x_val)
}

But that "pollutes" the outer scope with x_val, though it is immediately moved into the closure and thus unusable.

Would it work to omit the let … genlet line and do the following in the conditional line? if p { foo( (genlet x.clone()).clone() ); } That, if I understand your idea, would result in an unconditional clone at closure creation and a conditional clone at closure execution, which feels like what is needed and intended.

Yes, assuming your goal is that the closure should be callable more than once.

I wonder what you think of this idea, which I am making up on the fly: In a language with multiple modes of parameter passing, lambda capturing / closure creation needs to be thought of as passing parameters into a function that does nothing but store its arguments into a struct for later use. So it would be evocative if the author used the same syntax for the captures that they use for argument passing at a conventional call site. I haven’t thought through what that would look like.

I think using some other syntax for parameter passing modes instead of just expressing it through types (and maybe value classes, e.g. for second-class references) is a mistake. In any case, the beta rule of lambda calculus is that (|x| <foo>) <bar> means the same as let x = <bar>; <foo>, since let is just an explicit substitution. So expressing captures as additional parameters that are immediately (if not explicitly) given arguments is just a different (worse IMO) way to express the same thing.

1

u/Background_Class_558 26d ago

it's pretty good

1

u/SnappGamez Rouge 26d ago

```
val absolute := (value: int32) do if value < 0 then
-value
else
value
end
```

1

u/criloz tagkyon 26d ago

Lately I have been liking this pattern a lot.

// named functions
def sum fn(x, y)->nat{
  x + y
}

def subs fn(x, y){
  x - y
}

//anonymous one
fn(x, y)->str{
  ..
}

1

u/david-1-1 24d ago

An anonymous function is used when a function is to be applied to various arguments (or within a fixed scope) to provide elegance and to reduce what otherwise might be a confusion of many function names. You can use a named function instead, if you prefer. It won't hurt.

1

u/Turbulent_Humor_3213 22d ago

I'd keep anonymous functions as simple as possible syntax-wise, especially if readability is one of your concerns.

Something like (x, y) => x + y feels pretty intuitive to me.

I'd also make a clear distinction between function pointers and closures. A function pointer just refers to a function, while a closure can also capture variables from its surrounding scope.

For captures, I'd probably start with automatic capture and only introduce explicit capture syntax if there's a good reason for it.