koka-lang / koka

Koka language compiler and interpreter
http://koka-lang.org
Other
3.16k stars 151 forks source link

[Feature Request] Allow operator identifiers as fields in a struct. #557

Open AZMCode opened 1 week ago

AZMCode commented 1 week ago

This feature request is for allowing operator identifiers to be used as fields of a struct.

The motivating example for this is the simulation of typeclasses using implicit parameters.

For example, say a "numeric" typeclass is made:

pub struct num<a> {
    plus: (a,a) -> a
    minus: (a,a) -> a
    multiply: (a,a) -> a
}

An instance of this typeclass could then be used in a function as:

pub fun generic-pow<a>(x: a, y: a, .?num-instance: num<a>): a
    // Implementation here, using the functions provided in num-instance

However, as it stands this pattern breaks down when the function identifiers are operators, for example, this doesn't compile

pub struct num<a> {
    (+): (a,a) -> a
    (-): (a,a) -> a
    (*): (a,a) -> a
}

with the error

invalid syntax
unexpected identifier (operator) "(+)"
expecting ";", constructor field or "}"

And thus it is currently impossible for a typeclass to include operators, using this pattern.

I understand, however, that more considerations would have to be made about the associativity and priority of the operators, since the proposed snippet of code doesn't address that.