Hi! First off, I am a Gleam noob. This is my second day of learning. :)
Goal: I want to build an Entity Component System based game engine. In ECS, "components" are arbitrary pieces of data that can be attached to game entities, stored in the game world, and queried. It is the architecture used by Rust's Bevy engine.
Abstract goal: I want to have a central storage location for data that I don't know the type of, but I don't want devs using the library to lose out on any type safety when operating on that storage. Basically I want a heterogeneous/generic dict.
But Gleam doesn't have that. But I made something that comes pretty close by using constructors as keys to a closure-captured dynamic dict.
pub type Position {
Position
PositionData(x: Int, y: Int)
}
pub fn main() -> Nil {
new_world()
|> add_entity()
// meh, why do we need two types
|> component(Position).set(PositionData(1, 2))
// problem: ideally this would error because we want a `Position` value, not the constructor
|> component(Position).set(Position)
// best case scenario (doesn't work because of type mismatch):
|> component(Position).set(Position(1, 2))
Nil
}
I guess my question is: is there a way to get the return type of a constructor fn? Like TypeScript's ReturnType. I don't think so? That feels like the last thing blocking me. If it doesn't exist, would it be reasonable to add to the language?
code here, it is short/skimmable: https://github.com/willmartian/glecs/blob/main/src/example.gleam#L16-L22
Thank y'all in advance! (Also, Gleam is really fun!)