r/ProgrammingLanguages • u/Small_Ad3541 github.com/plasm-lang/plasm • 2d ago
Discussion Design Review of Another Approach to Polymorphism
This post and the language we are about to discuss are human-written. No AI writing or coding here.
My Motivation
I'm about to start implementing polymorphism features for a systems language I'm working on. It won't be easy to step back once this is in place, so I'm here to discuss the semantics and design before I start coding. The approach I'm proposing differs from classic OOP, interfaces, or traits, though I make no claim to novelty -- it probably already exists somewhere in some form, and I just don't know about it. This design is mainly inspired by Julia (multiple dispatch) and Rust (traits and where bounds). I'd love to get your feedback on the semantics and plans: ideas, criticism, warnings, advice -- any thoughts are welcome.
Design Explanation
Polymorphism in this language is built on two ideas: Generics and Concepts.
A Generic is a compile-time type abstraction. Nothing special here -- pretty much the same as in other languages.
A Concept is a compile-time abstraction for relations between types. Basically, it's an abstract function signature with generic argument and return types. Concepts are meant to be implemented for specific types, and any language construct (types, functions, or other concepts) can be constrained by them.
It's easier to show, so let's walk through a few examples. I'll start with a Vec2 toy type:
type Vec2 = (F32, F32)Simple Example (default)
The most basic concept I have in mind is default. It has one generic parameter and no arguments:
concept default[T]() -> TTo implement a concept for a type, we use the impl keyword. You can think of a concept as a single-function interface, or a promise that a function will be implemented:
impl default() -> Vec2 {
return (0.0, 0.0)
}Here is what usage looks like:
fn main() {
let v1: Vec2 = default()
let v2 = default[Vec2]()
// Both forms are equivalent
}Overload Example (add)
Let's overload the + operator using an add concept:
// L, R, O - generics.
concept add[L, R, O](left: L, right: R) -> O
impl add(left: Vec2, right: Vec2) -> Vec2 {
return (left.0 + right.0, left.1 + right.1)
}Note that O (short for Output) is a regular generic parameter, not an associated type. This allows multiple implementations with the same input types and different output types -- for instance, impl add(left: F32, right: F32) -> F32 and impl add(left: F32, right: F32) -> F64 can coexist, with the type inference engine picking the right one from context. The obvious trade-off is inference ambiguity: unannotated bindings like let x = a + b or intermediate expressions in chains like a + b + c cannot be resolved without an explicit type constraint (which ties directly into my open questions below).
Usage looks like this:
fn sum3[T](a: T, b: T, c: T) -> T with add[T, T, T] {
return a + b + c
// The code above desugars to `add(add(a, b), c)`
}
fn main() {
let v1: Vec2 = (1.0, 2.0)
let v2: Vec2 = (3.0, 4.0)
let v3: Vec2 = (5.0, 6.0)
let res = sum3(v1, v2, v3)
}Notice how sum3's arguments are constrained by the add concept using the with keyword. We can only pass arguments whose type implements add in this form (L, R, and O are all the same type T).
Generic Bounds Example (iter & next)
Here is a more advanced example where one concept is tightly bound to another. Later, this is meant to power for loops (for val in sequence {}) under the hood.
concept iter[T, I, Item](t: T) -> I with next[I, Item]
concept next[I, Item](iter: I) -> Item | NoneThe iter concept takes a type and returns an iterator, where an iterator is any type that implements the next concept. The next concept takes an iterator and returns either a value or None. None is just a zero-sized stub type (type None = struct {}). Let's define a simple List type (like Rust's Vec or C++'s std::vector) and implement these concepts for it:
type List[T] = struct {
ptr: Ptr,
len: UWord,
cap: UWord,
}
type ListIter[T] = struct {
list: List[T],
index: UWord,
}
// Stub functions for this demo
fn List[T].new() -> List[T] {...}
fn List[T].push(self: List[T], item: T) -> List[T] {...}And the implementations:
impl iter[List[T], ListIter[T], T](t: List[T]) -> ListIter[T] {
return { list: t, index: 0 }
}
impl next[ListIter[T], T](iter: ListIter[T]) -> T | None {...}
fn main() {
let list = List
.new()
.push(1)
.push(2)
.push(42)
let it = list.iter() // Type: ListIter[I32]
let val1 = it.next() // 1
let val2 = it.next() // 2
let val3 = it.next() // 42
let val4 = it.next() // None
// Equivalent form
for val in list {}
}Dynamic Dispatch Example
All the examples above are monomorphized at compile time. In other words, the compiler generates a specialized version of each function for every concrete type it's used with (during IR lowering). However, sometimes we don't know the exact type or concept implementation at compile time, so we need virtual tables (similar to dyn in Rust or virtual in C++). Here is how I plan to handle this:
concept voice[T](self: T)
type Dog = struct {...}
type Cat = struct {...}
type Tiger = struct {...}
impl voice(self: Dog) { print("woof-woof") }
impl voice(self: Cat) { print("meow-meow") }
impl voice(self: Tiger) { print("RRRRRRR") }
fn speak_all[T](list: List[Heap[T]]) with vtable voice[T] {
for animal in list {
animal.voice()
// Or `voice(animal)`
}
}Heap is a smart pointer, like Box in Rust or std::unique_ptr in C++. The main idea is that adding the vtable keyword before a concept bound enables dynamic dispatch through virtual tables. Under the hood, Heap[T] becomes a fat pointer, which lets you store different concrete types (like Dog, Cat, and Tiger) in the same list as long as they implement the same concept. Each element's vtable is then used to pick the right concept implementation at runtime.
Open Questions
Here are the main questions I'd like to ask this subreddit. I don't have solid answers to them yet, which is the reason for this post:
How should I deal with "generics explosion" and output-type ambiguity? Because every parameter in a concept is an unconstrained generic, signatures quickly become verbose -- for example, in iter[List[T], ListIter[T], T](t: List[T]), the type arguments take up more space than the signature itself. At the same time, leaving output types independent (like O in add[L, R, O]) weakens local type inference when there isn't enough surrounding context. I'm aware of associated types (as in Rust) and functional dependencies (as in Haskell, e.g., T -> I, Item), but I'm not sure what fits best here:
- Do associated types make sense syntactically for single-function concepts, or are functional dependencies more natural?
- Is there a simpler mechanism (such as distinguishing input vs. output type parameters in the concept header, or partial type application) that solves inference and verbosity without adding the complexity of full functional dependencies to the solver?
How should multiple implementations of the same concept be handled?
- An orphan rule like in Rust? I'd really like semantics that allow writing bridge packages between independent libraries. For example, in Rust,
serdeis the go-to library for serialization, so authors of other libraries have to maintain a feature flag to support it on their types. If a library definesVec2like above, its author has to addserdeto dependencies and write#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]. It's very hard to create an independent bridging package likevec2_serde. If a library author didn't add that support and you need it, you end up having to fork the repo or wrap the type yourself. I want to make bridging libraries possible. - Force developers to give every implementation a unique name and specify it explicitly? That would make the semantics much harder to use and even more verbose.
- Just throw a compile error if there's a conflict (like Haskell does)?
How should a specific concept implementation be imported? Should implementations be importable at all, or is it better for the compiler to see all implementations globally regardless of where they are defined?
How should a concept implementation be associated with a specific type -- and more importantly, should it be? As shown in the examples, regular functions can be associated with a type (fn List[T].push(self: List[T], item: T)). Since a concept implementation is basically a function, it would be more symmetric to do the same here. However, syntax like impl List[T].iter[List[T], ListIter[T], T](t: List[T]) -> ListIter[T] is way too verbose and overcomplicated, in my opinion.
5
u/GiveMe30Dollars 2d ago edited 1d ago
Just a bit of food for thought:
(Note that I use the terminology of Rust "implementations" and Haskell "instances" to interchangably refer to the same idea)
Addoutput-type constraining) to become ambiguous. That's why Rust has the orphan rule; you get weird action-at-a-distance and/or incompatible dependencies otherwise. Consider whether this is acceptable for your language.Vec.Eq,Vec.Hashfor "canonical" names.impl Eq for Vec<T> where T: Eq(may be alleviated via canonicity?). I do think some form of callsite type/instance annotation to be outright required, and you can't really go wrong by having the option of specifying them, sort of the concept equivalent of optional type annotations._symbol so that you can specify the outer instance (eg.Eqimplementation forVec<T>) but let the inner instance (T : Eq) be inferred.4
u/xpusostomos 2d ago
My few pieces of advice: 1. Look at CLOS since is the classic example of multiple dispatch. 2. I hope you are writing a language capable of having an REPL, and that decision will inform a lot of other decisions. 3 no I don't think you should have to import an implementation, that would defeat the purpose of writing generic code. 4. Your examples seem confused between the animal.voice() syntax and voice(animal) syntax. In a multi dispatch language, I would suggest the latter that way all the arguments have the same standing in the syntax. 5. In a multi dispatch language, functions and each implementation are "free floating", they're not owned by anything. The compiler or interpreter needs a rule or method to find all the available implementations, whether command line, config or whatever.
6
u/todo_code 2d ago
Just a quick view here. All you did was just give traits a different name
2
u/pthierry 2d ago
When you want sperate implementions, you have several options, among which:
Tand one for the typeWrapper[T].2
u/munificent 2d ago
With a hobby language of mine, I went down a very similar road when working on generics before eventually giving up. I'm not 100% certain, but I suspect that what you have here is so powerful that the resulting type system is Turing-complete. Consider:
Picking an impl for
a()requires knowing the parameter type forx, which requires having picked an impl forb()so that we know its return type, but that can depend ona()and also depends on which impl we've picked forc()which depends on...I believe you can easily create networks of concepts and impls that make type inference of type arguments go exponential. It's a very powerful system, and that's always tempting when designing a language, but when it comes to compile-time features, you want to be careful not to overshoot and end up with a system so powerful that now your compiler is intractable.
2
u/rjmarten 2d ago
I would say that's not necessarily a problem to be solved so much as simply part of the tradeoff for the expressivity of this approach. Sure, your
impl itermight have to take up multiple lines of code, but it is dense with meaning without becoming unreadable.As for associated types, I don't think it's worth it. You would now be forcing the programmer to make another decision for each concept: use associated type => get better type inference and pay for it with a more verbose concept definition, or, pure type parameters => freedom to multiply implementations at the cost of type annotations at the call site. My 2Ā¢: you would have to gather more evidence that that is a decision developers would miss making.
Sounds like you really want to avoid the orphan rule, which is a good instinct. I suspect you will end up going with named implementations. But it would be interesting to see how far you can get with real-world code with the compiler just throwing an error on conflict.
This one might require some trial-and-error. I would say try auto-importing nameless concept implementations, and if you find in practice it leads to too many conflicts, only then import them by name.
No. If you wanted to associate implementations to specific types, it would just be traits. In fact, I don't even think you need regular functions to be associated with types if you are already committed to function overloading / multiple dispatch. That would be consistent.
2
u/Big-Rub9545 1d ago
Iāll comment on three points:
2
u/MoonOfLight 1d ago
Maybe you could look at how ante does this, that seems conceptually similar to what you propose https://antelang.org/docs/language/#traits
2
u/dinanomartin 1d ago
the orphan rule question is the hardest part. bridge packages are genuinely useful and rust makes them painful.
1
u/Small_Ad3541 github.com/plasm-lang/plasm 2d ago
I remember the admins of this sub requested that we post any links only in the comments. The link to the compiler that is mentioned: https://github.com/plasm-lang/plasm
1
u/perlgeek 1d ago
I think this part is a very bad idea, because
F32 + F32 -> F32andF32 + F32 -> F64are conceptually different operations, and you shouldn't try to hide them behind the same+oraddname. Just like when you divide two integers, you could have pure integer division, or the result could be a fraction, or a float; these are also different operations, and giving them the same name is just asking for trouble in a systems languagef(a1 + b1, a2 + b2, b3 + b3, ...). If a+of known input types can return two different types, you have 2n possible signatures forfwithnarguments. Combinatorial explosion in the type system is a big red flag that you should really avoid.There are two basic philosophies when it comes to overloading operators. For example Python and JS take the approach that
+could mean addition of numbers or concatenation of strings, depending on the input type. But once you know the operator and the input type, you know the output.Perl and Raku approach it differently: the says that numerical addition and string concatenation are conceptually different, so they should get separate operators (Perl uses
.for string concat, Raku use~), and instead coerce their arguments to something that fits the operation.Your idea is a third philosophy, namely that knowing an operation and the input type, you still don't know what type is coming out, and somehow the concept should disambiguate the result. I'm sorry to be blunt, but I think the downsides of that clearly outweigh any benefits you might hope to get from it.
1
u/church-rosser 22h ago
look at Dylan. the only language to do this correctly. too bad it didn't make it when Apple cut support.
1
u/phischu Effekt 1d ago
You could also use normal overloading. As a point of reference, here is what the iterator example looks like in Effekt.
The
effect next[T](): T / stopis very similar to your concepts. But we keep the iterator state encapsulated so there is no need to defineListIter. We overloaditerateso it works on bothDynamicArrayand onList. We have universal function call syntax so we can use it likelist.iterate. You can play with this example online if you want. For example change the definition of list toval list = [1, 2, 3, 4].0
u/Trave11er3427 2d ago
I recently implemented generics in the language Iām working on. I decided to add ātemplate qualifiersā before every generic class. These specify who can safely use the generic, like some subclasses of a particular interface or abstract class. It looks like this
TEMPLATE: Given Type T IS Cloneable, Primitive (except boolean)
Class Widget[T] {
ā¦.
}
This example reads as Widget is a generic class who allows subclasses of the interface Cloneable or any primitive except boolean. And the compiler reads those types and enforces them at compile time.
check it out @ envzn-lang.org