3 ms·
I've looked at Gleam before but it didn't seem to have any mechanism for dynamic dispatch like interfaces or type classes. Did it change in the meantime?
by mono442 10mo ago
I've looked at Gleam before but it didn't seem to have any mechanism for dynamic dispatch like interfaces or type classes. Did it change in the meantime?
- stuartaxelowen 10mo agoThe answer I’ve seen is “just pass structs of functions around”, which is just one step more explicit than the implicit version we’re all use to, but honestly I kinda like it to free ourselves of all the ceremony around generics.
- lpil 10mo agoIt’s discouraged to pass around structs of functions to replicate type classes in Gleam. Instead the preference is to not type class style patterns in your projects, favouring a concrete style instead.
- stuartaxelowen 10mo agoDoes that mean pass every needed function as a parameter? Or just don’t write generic functionality?
- lpil 10mo agoYes, one would use higher order functions, as is common in Erlang, Elixir, OCaml, Elm, etc.
- shirogane86x 10mo agoAt least half of those languages (Elixir and OCaml) have some sort of mechanism for ad hoc polymorphism (elixir has behaviors and protocols, OCaml has higher order modules) so I feel like the comparison doesn't work that well personally
- lpil 10mo agoOCaml's modules are not implicitly instantiated, so they provide the same DX and APIs as you would get in Gleam. Elixir does have protocols, but they are extremely limited compared to type classes, traits, etc, and they're uncommonly used compared to writing concrete code.
- lpil 10mo agoGleam has first class functions, so it has dynamic dispatch. Both of type classes and interfaces desugar to high order functions, so anything you write with them can be written with first class functions, though with a less concise API.
- the_duke 10mo agoWhat you are saying is: no, it doesn't. Of course dynamic dispatch can be implemented in almost every language. The Linux kernel uses dynamic dispatch with C! But that's a hack, not a language feature.
- lpil 10mo agoI think you might mean “ad hoc polymorphism” rather than “dynamic dispatch”. Gleam, C, Erlang, etc have the latter, not so much the former.
- array_key_first 10mo agoIt's not a "hack" because many language DO NOT let you store functions with state. Gleam does, I write PHP, and that does as well. PHP has interfaces and whatnot, but a lot of the time I do polymorphism by just having a class that has Closure members. When you can arbitrarily pass around functions like that, it's basically equivalent to an interface or abstract class, with a bit more flexibility.