mojo icon indicating copy to clipboard operation
mojo copied to clipboard

Conditional Trait Conformance

Open Moosems opened this issue 10 months ago • 1 comments

Review Mojo's priorities

What is your request?

I believe it would be nice for there to be conditional trait conformance in structs. This could be achieved through a a decorator that is passed static tuples that contain a type, the trait, and the struct value that needs to conform to this.

Example use case:

@value
struct SpecialStruct[T]:
    var x: T
    var y: T
    @conditional((T, Stringable, Self.x))
    fn __str__(self) -> String raises:
        # raises in case T does not conform
        return self.x

    @conditional((T, Intable, Self.x), (T, Intable, Self.y))
    fn mult_vals(self) -> Int raises:
        # tuple ao you can use multiple struct variables
        return self.x * self.y

What is your motivation for this change?

It would allow for more flexibility and be nice when a programmer knows if something will work.

Any other details?

Could be implemented in other ways but the idea/concept is still pretty important

Moosems avatar Apr 15 '24 19:04 Moosems

Some alternate ideas for syntax include:

trait Purchaseable:
    fn buy(): …

struct Array[T]:
    fn buy() if conforms[T, Purchaseable] raises: …

Or

trait Purchaseable:
    fn buy(): …

struct Array[T: AnyType](Purchaseable if T): …

Or (by far my least favorite as it requires another set of indentation)

struct Optional[T]:
    # …
    if conforms[T, CollectionElement]:
        fn blah():
            pass

With the last one there should, in my opinion, also be a way to not make another layer of indentation. In my experience you almost never need more than three layers of indentation and excessive layers are ugly. This is why many opt for guard clauses instead of layered ifs. You could say that it's because of the function definition, and thats true, but there's ways to not need the if statement or put in it a way that doesn't need more indentation

Moosems avatar Apr 15 '24 20:04 Moosems

I believe this is related to https://github.com/modularml/mojo/issues/1876

gabrieldemarmiesse avatar Apr 16 '24 10:04 gabrieldemarmiesse

Yes, thank you, closing in favor of #1876

Moosems avatar Apr 16 '24 11:04 Moosems

What do you think of the proposed syntax, if I may @gabrieldemarmiesse?

Moosems avatar Apr 16 '24 11:04 Moosems

I have no opinion on the syntax, everything is fine by me

gabrieldemarmiesse avatar Apr 16 '24 12:04 gabrieldemarmiesse