Automatic method implementations

The Question

While Roto code gets more generic (see e.g. lists), we have to consider which methods will be available for all types. Currently, that’s just clone and drop. We are also considering adding a debug-type printing mechanism to this. However, there are other methods that might need to be added to this list:

  • an equality method (like Rust’s Eq::eq or its partial variant)

  • an ordering operation (like Rust’s Ord::ord or its partial variant)

  • a hashing method (really important for hashmaps)

If these methods are available on all types, we can add List.sort, List.contains, HashMap/Dict and many other methods that people generally expect. On the other hand, there might be good reasons to either override the default implementation or disable it altogether.

What does Gleam do?

Roto currently does not have anything resembling a trait or class system that allows functions to specify which methods must be available for a type. Gleam doesn’t either, so let’s investigate what they do.

Gleam has a contains function for lists: gleam/list · gleam_stdlib · v0.68.1 . That tells me that equality is at least available for all types.

They also have a sort function, but that takes a comparison function as an argument. That’s not too bad! If we implement first-class functions, we could totally do this. At least it’s better than JavaScript where sort will just silently do the wrong thing if you don’t give it an explicit comparison function.

Additionally, they have a dict type which seems to allow any key type, which means that hashing is definitely implemented for everything.

The echo mechanism in Gleam also does a debug-like print for any type that you give it. And I like that!

Small correction: Gleam implements some things in its target languages, so the methods I’m describing here are not necessarily available for users of the language. For example, there’s no way that I can find to hash a value, but you can use any value as a key in a dict.

However, we do have to consider that all values in Gleam are immutable! That ensures that all values can safely be a key in a dict.

What that means for Roto

If we follow the same design, which I’m inclined to do, we’d have the following:

  • eq, debug and hash will be implemented automatically
  • there won’t be an ord implementation, but sorting will be possible with an explicit function parameter, once we have first-class functions (which are high on the priority list).

There is still an open question around (im)mutability though. Roto’s dictionaries should not be allowed to have mutable key types. This is related to: A design of shared mutability.

Please leave comments and feedback, regardless of whether you agree or not. I’d love to hear opinions.