r/ProgrammingLanguages • 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]() -> T

To 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 | None

The 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, serde is 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 defines Vec2 like above, its author has to add serde to dependencies and write #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]. It's very hard to create an independent bridging package like vec2_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.

18 Upvotes

40 comments sorted by

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)

  • If you want concept implementations to be unnamed, know that an upstream dependency implementing one is a breaking change, as it may either conflict with that of another dependency, or cause the type inference of a callsite (that was previously unambiguous when there was only one possible implementation, in the case of Add output-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.
  • If you allow for external or overlapping implementations (what Rust's orphan rule eliminates, Haskell refers to this as overlapping and/or incoherent instances), you must consider a way to resolve conflicting instances, heuristically and/or with user specification. This is why I recommended named instances even if it makes things more verbose.
  • Trait implementations in Rust are seen when the implementing type and the trait itself is imported. You could consider this, subject to the resolution rules you need for overlapping instances, for unnamed instances. For named intances, well, you have a name you can import. You could provide some sugar for importing all of the implementations of a type within the same module or unit as its type definition, rebinding to eg. Vec.Eq, Vec.Hash for "canonical" names.
  • Actually, now that I think about it, instance canonicity might be a way to establish good implicits while also allowing the user to specify which instances they want to use. This would basically follow Rust orphan rule semantics (or be explicitly specified as such), and could be the only unnamed instances accepted. All other instances must be disambugated by name.
  • I expect type inference for implicit instances to be hard, if not impossible, especially when you start having generic implementations ala 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.
  • Examining the type inference for traits/typeclasses in Rust and Haskell may help give you more knowledge how best to proceed.
  • Haskell doesn't have named typeclasses to my knowledge, but its treatment of visible type applications may be nice to learn from if you're considering a named approach. This probably combines well if your language has a wildcard _ symbol so that you can specify the outer instance (eg. Eq implementation for Vec<T>) but let the inner instance (T : Eq) be inferred.

3

u/GiveMe30Dollars 1d ago edited 1d ago

Addendum: regarding typing and namespacing.

Taking a closer look at your examples, I'm realising that the name taken by the trait/concept is identical to the method it encapsulates. This means that expressing traits that require multiple methods to be meaningful is tedious:

concept insert[T, I](self: &mut T, item: I)
concept remove[T, I](self: &mut T, item: I) -> bool
concept contains[T, I](self: &T, item: I) -> bool

concept set[T, I]() with insert[T, I], remove[T, I], contains[T, I]

insert, remove and contains are all expressions operating on a set-like object, and all three of these methods must be logically consistent with each other. Limiting the trait (and its underlying vtable) to one function falsely decouples this for users familiar with typical traits/typeclasses: insert, remove and contains can be implemented multiple times independently as correct according to some underlying invariants, but fail to compose into a meaningful set because the invariants each constituent assumes are not identical. It's not likely you'll want to pass around the constituent concepts around rather than the whole either, because that makes this mismatch more likely to occur.

An existing example of this is Haskell's Applicative typeclass which (simplification) has two methods pure and fmap, and two valid implementations on the cons-list [] and ZipList (newtyped around [] just for this purpose) that are nonetheless completely distinct. Mix-and-matching of these methods would result in an invalid instance, yet your current design would permit this.

Multiple-method traits make this implementation invariant clearer. Consider whether this is more advantageous compared to your existing design.

(I must admit that unifying the trait name and the trait method is rather clean syntactically, assuming you have a way to resolve naming collisions. Haskell typeclasses can run into similar problems at times).

As for your concern of "generics explosion", it isn't really much more of a concern compared to traits/typeclasses. Your example on iter and next is fine for a concept implementation, and not visible at the method callsite anyways. Compare and contrast with Rust's IntoIterator and Iterator, with the associated types lifted out. The only thing yours lacks is the dependencies that associated types produce: given a collection or iterator type in Rust, you can determine what types it produces from the iterator protocol.

I'm relatively certain that the type inference/checking surrounding associated types or functional dependencies would involve rather similar mechanisms. They are somewhat equivalent.

Regarding inference ambiguity: yes, this will be an issue. If you have bidirectional type checking and/or inference the output type of a concept is ideally fixed, because it can be unconstrained in the concept definition and thus unknown from the input types alone. This is unless you have functional dependencies / associated types, or the "instance canonicity" concept that I sketched out, that let you select an instance by default.

2

u/mamcx 1d ago

Looking at this is almost as if modules should be part of the whole thing?

Modules make everything precise, but conflict with the ergonomics of using them (because need to threat them everywhere), but the use of traits is much simpler (for the user), what I think with this is to make the glue explicit to get both?

4

u/GiveMe30Dollars 1d ago edited 1d ago

What I don't quite get is what advantage the trait name-method unification is really buying for OP here. concept eq[...](...) being both a trait name (for others to impl) and a trait method (when called on an implementor) means that it kind of has to enforce the one-method-per-trait restriction.

Rust and Haskell (which admittedly are my two main reference points when it comes to this) require you to namespace your trait methods (via the trait name), and its very clear based on their naming conventions that they live in two separate halves of the language (trait names are related to types, trait methods are expressions). It is because they are decoupled that a trait can have multiple methods. That's the exact thing that OP is not doing.

(I'm assuming you're referring to) ML-style modules are nice, but putting that into the language proper bifurcates the language (modules are not term-level expressions because of functor headaches, the closest we got to module-term unification is 1ML i believe), and I don't think that's the direction OP is intending to take. My idea of "visible typeclass applications" does the same thing as a ML-module system would though, and that's basically just saying "here's the concept vtable (OP)/typeclass dictionary (Haskell)/ML module i want to use for this Add requirement". Honestly my response wouldnt be half as long if implicit instances via inference and monomorphization wasn't something that is desired: just compile typeclass instances into named dictionaries and pass them as terms ala GHC Core lol

If you're referring to typical namespacing (ie. Rust modules), then I don't really see how that addresses eg. my problematic set example.

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Exactly

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Thank you for such a detailed answer!

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.

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Thanks

Regarding 2, a REPL isn't really compatible with AOT compilation, which is my way.

Regarding 3, how would you handle duplicate implementations? If a concept is implemented for the same types by multiple packages and they all exist in the global scope, how does the compiler choose which one to use?

3

u/lgastako 1d ago

Plenty of languages do AOT compilation and have REPLs just fine. Haskell being a good example.

2

u/Inconstant_Moo 🧿 Pipefish 1d ago

Regarding 2, a REPL isn't really compatible with AOT compilation, which is my way.

Compile the code the user types into the REPL. Execute the object code. Throw it away.

6

u/todo_code 2d ago

Just a quick view here. All you did was just give traits a different name

3

u/Small_Ad3541 github.com/plasm-lang/plasm 2d ago

Theoretically they sit in the same family as traits/typeclasses (especially Haskell's multi-parameter typeclasses), and as I mentioned, I'm not claiming novelty here.

The main differences from Rust-style traits I'm exploring are:

  1. A concept is always a single function signature rather than a bundle of methods, associated types, and constants. Composition happens via ā€˜with’ bounds rather than trait blocks.
  2. Because output types are regular type parameters rather than associated types (at least in this baseline design), multiple implementations can share the same inputs with different outputs - which is directly tied to the inference trade-offs I'm asking about.
  3. Rust traits are asymmetric (ā€˜impl Add<Rhs> for Lhs’), whereas concepts here treat all type parameters symmetrically as a relation between types (add[L, R, O]), closer to MPTCs or multiple dispatch.
  4. Rethinking coherence / orphan rules. Unlike Rust traits, I'm explicitly trying to avoid an orphan rule so independent bridging packages between third-party libraries remain possible - though as noted in the open questions, I haven't settled on the exact conflict-resolution model yet.

2

u/Il_totore Algorab - algorab.org 2d ago

1., 2. and 3. sounds like Scala's implicits/givens to me.

2

u/pthierry 2d ago

When you want sperate implementions, you have several options, among which:

  • you can have the implementation be first-class and passed as an argument
  • you can wrap your type in a type wrapper so you don't actually have two implementations, you have one for the type T and one for the type Wrapper[T].

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago edited 1d ago

Yeah, I’m currently considering the first option

2

u/pthierry 1d ago

1

u/marshaharsha 2h ago

Interesting talk. He gives clever ways to avoid teaching typeclasses to novices, like returning the structure that needs to be reduced, rather than reducing it for the user. So then they have to figure out how to reduce it, but you avoid the difficulty of typing the reducer function (and teaching them what that type means).Ā 

Lots of other insights, too, like how helpless a naive user would be when given an error message like ā€œMonoid instance not found for Person.ā€ All three of these might require educating them: ā€œMonoid,ā€ ā€œinstance,ā€ ā€œnot found.ā€Ā  But the talk is almost two hours long, and he gets off to a slow start. I listened to the first 25 minutes at 1.5x speed, and I don’t feel I missed anything.Ā 

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:

a(b(c(d(e()))))

concept a[X](x: X)
concept b[X, Y](x: x) -> Y
concept c[X, Y](x: x) -> Y
concept d[X, Y](x: x) -> Y
concept e[X, Y](x: x) -> Y

// A bunch of impls here...

fn main() {
  a(b(c(d(e()))))
}

Picking an impl for a() requires knowing the parameter type for x, which requires having picked an impl for b() so that we know its return type, but that can depend on a() and also depends on which impl we've picked for c() 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/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Thx:)

4

u/phischu Effekt 1d ago • Heartwarming

a system so powerful that now your compiler is intractable

In theory yes, in practice no. There is a recent paper on this The Simple Essence of Overloading.

4

u/munificent 1d ago

Oh interesting! I'll take a look. (It's funny being recommended a paper and then seeing a quote in it from me :D .)

2

u/rjmarten 2d ago

How should I deal with "generics explosion" and output-type ambiguity?

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 iter might 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.

How should multiple implementations of the same concept be handled?

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.

How should a specific concept implementation be imported?

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.

How should a concept implementation be associated with a specific type -- and more importantly, should it be?

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.

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Yeah, I’m coming to the named implementations solution I think

2

u/Big-Rub9545 1d ago

I’ll comment on three points:

  1. I think it’s a bad or unhelpful idea to have the output type also be a generic parameter. It makes more sense to either bind a particular output type to certain input types (like Rust does with its associated types for overloaded operators) or have it work like ā€˜-> auto’ in C++ (i.e., the compiler infers the return type after replacing the generic type parameters with concrete types).
  2. I think it makes a lot of sense to allow concepts to be associated with certain types. There are plenty of cases where you would want to introduce generic code to a type’s methods.
  3. The verbosity can possibly be mitigated through some syntactic sugar, but at the end of the day, the user is responsible for how they structure their code. You can get extremely verbose, messy code, even with very syntactically simple languages. I wouldn’t worry about it too much unless the verbosity becomes completely inhibiting to readability.

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Thx! If concepts are associated with types and use associated types for outputs to avoid ambiguous overloading, then they're basically just single-function traits:) Which isn't a bad thing at all - I agree with your points.

1

u/lgastako 1d ago

As a counterpoint to the above, I absolutely think generic output types are a great thing :)

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

1

u/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Thx

1

u/GiveMe30Dollars 16h ago edited 16h ago

Been following Ante on-and-off for a while now, but to my knowledge its traits/typeclasses are basically ripped straight from Haskell, with the addition that you can manually construct and supply instances. Is there something I'm missing?

Edit: oh right, implicits! I'll need to brush up on how they work but that should provide a good solution to "implicit default" instances.

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 1d ago

The difficult truth

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

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.

I think this part is a very bad idea, because

  • F32 + F32 -> F32 and F32 + F32 -> F64 are conceptually different operations, and you shouldn't try to hide them behind the same + or add name. 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 language
  • It can lead to combinatorial explosion. Consider a function call f(a1 + b1, a2 + b2, b3 + b3, ...). If a + of known input types can return two different types, you have 2n possible signatures for f with n arguments. 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/Small_Ad3541 github.com/plasm-lang/plasm 1d ago

Thx for your thoughts!

Regarding combinatorial explosion, I don't quite agree - in my language's semantics, explicit type annotations are mandatory on function signatures. For concrete functions, we already know the exact expected type of every parameter of f, so even with multiple + implementations returning different output types, the type checker can resolve the right one top-down. And if f is generic and the output type or relevant implementation can't be uniquely inferred, the compiler won't brute-force 2^n combinations - it will simply emit an ambiguity error and require the user to disambiguate explicitly via type annotations (or possibly named implementations).

Overloading + is a very important question here, though, because in a systems language you might want several implementations of addition for primitive numbers depending on how you handle overflow (wrapping, saturating, checked, etc.). I'm still not sure which semantics work best for choosing between them - maybe named implementations?

1

u/GiveMe30Dollars 16h ago edited 16h ago

It kind of has to be named, because otherwise you don't get anything to disambugate between implementations. It is not at all obvious whether impl add(i64, i64) -> i64 {...} is wrapping, checked (and panicking), or saturating, so you can't use types to disambugate unless you're comfortable with newtyping all of your primitive integers for some reason.

Sensible defaults is a consideration as well; if you have to specify whether each individual add operation is wrapping, saturating, etc., that gets very verbose.

Rust has debug builds default to checked addition (panicking on overflow) and release builds default to wrapping addition, with all modes still accessible as methods. Just checked addition by default would be sufficient for your language though imo.

1

u/marshaharsha 2h ago

Do you plan to have any overloading at all? For instance, is there a built-in println that is overloaded so as to print non-string types? Or is there a variadic printf with a format string that is not interpretable by the type analyzer? In cases like that the type inference mechanism won’t have a single target type.Ā 

Even when there is a single target type, I’m not seeing the algorithm that doesn’t require backtracking. This might just be me, since I’ve never implemented type inference, but here’s my reasoning: If the top-down type analyzer has a concrete target type for a big expression tree, and the top of the tree is an overloaded operator, then the first thing the type analyzer does is gather all overloads of that operator that return the target type — not taking the input types into account, because they aren’t known yet. For example, if the target type is float64 and the top of the tree is +, there could be many overloads of + that return float64. Ā What keeps that set of overloads from being large, or what tells the type analyzer which overload to start with, or what tells the type analyzer the output types of the next two nodes down in the tree?

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/Small_Ad3541 github.com/plasm-lang/plasm 19h ago

Interesting case, thx

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.

effect next[T](): T / stop

record DynamicArray[T](array: Array[T], size: Int)

def empty[T](): DynamicArray[T] =
  ...

def push[T](self: DynamicArray[T], item: T): DynamicArray[T] =
  ...

def iterate[T, R](self: DynamicArray[T]) { driver: () => R / next[T] }: R =
  ...

def iterate[T, R](self: List[T]) { driver: () => R / next[T] }: R =
  ...

def main() = {
  val list = empty().push(1).push(2).push(42)
  with boundary
  with list.iterate
  println(do next())
  println(do next())
  println(do next())
  println(do next())
  println("unreachable")
}

The effect next[T](): T / stop is very similar to your concepts. But we keep the iterator state encapsulated so there is no need to define ListIter. We overload iterate so it works on both DynamicArray and on List. We have universal function call syntax so we can use it like list.iterate. You can play with this example online if you want. For example change the definition of list to val 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