3 ms·
I disagree with the post. The goal of traits, or any similar mechanism in other languages, is not to implement a given functionality. It is to describe and enfo
by pierrebai 4y ago
I disagree with the post. The goal of traits, or any similar mechanism in other languages, is not to implement a given functionality. It is to describe and enforce a common way and API to expose the functionality.
To take the example given for gleam, there is nothing enforcing that the conversion to string is called to_string, what are its arguments, how formatting works. So you're left to just-so compatibility for each type. They only happen to be the same by accident, and nothing enforces consistency.
Programming language and code in general is about communication between programmers. When I design a trait, or an interface, I'm telling everyone else what are the requirements.
- Supermancho 4y ago> The goal of traits, or any similar mechanism in other languages, is not to implement a given functionality. Note: Saying "similar mechanism" is a tautology for whatever you defined after that.
- jghn 4y agoConstructs like Lisp's CLOS and dd hoc polymorphism can provide the same benefit. You don't need a class/trait/etc enforcing a contract on data. Instead you can keep data and functionality separate, and then prove you have an implementation of function X for data Y. This also allows for easy extension of the data downstream.
- Joker_vD 4y agoBut Gleam is statically typed, you see, and very restrictively. In such languages, typeclasses/interfaces/extensible records/(void*)-passing and -casting shenanigans are the things that traditionally provide the virtual/dynamic dispatch to the programmers.
- gct 4y agoYeah Traits give you more than just the type of the output, they let you specify how it must be called to get that trait, that's a key capability for writing generic code. Sure I can write a to_string() method but someone else will call it ToString() and I can't use it. If we both impl Display then it's all good.
- aatd86 4y agoSame way when you design a type, you define some requirements over raw data. If one really wanted to argue, that would be that instead of saying that traits/interfaces are types, rather one should say that types are interfaces over raw data. An interface/trait would then supersede the concept of type.