mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[Feature Request] "Extensions", a way to separate struct's implementations from their data

Open jordiae opened this issue 1 year ago • 2 comments

Request

Disentangle struct's implementations from their data.

Motivation

Improving extensibility (see example below).

Description and Requirements

In the struct definition, define only the attributes:

struct MyPair:
    var first: Int
    var second: Int

Add an additional statement, "impl", to define the implementation:

impl MyPair:
    def __lt__(self, rhs: MyPair) -> Bool:
            return self.first < rhs.first or
                 (self.first == rhs.first and
                  self.second < rhs.second)

The language doesn't have traits yet, but it's in the roadmap. Since structs don't have inheritance, disentangling struct's implementations from their data would allow for user extensions. Say that the user decides to define a new trait, ToString:

interface ToString:
    def __str__(self) -> Str:
        raise NotImplemented

impl MyPair(ToString):
    def __str__(self) -> Str:
        return '(' + str(self.first) + ',  ' + str(self.second) + ')'

jordiae avatar May 11 '23 17:05 jordiae

Good idea!

ksandvik avatar May 11 '23 17:05 ksandvik

This would allow the community to implement methods like map, filter, and reduce to some of the builtin list/vector types like so (until they are added into the language)

let arr = [1, 2, 3, 4, 5]

arr
  .map(lambda x: x*2)
  .filter(lambda x: x%2==0)

sa- avatar May 12 '23 07:05 sa-

It might be good to restrict so that you can only implement methods/traits for locally defined types (like the orphan rule in Rust), or else you can end up with multiple implementations and incoherence. This talk gives a good explanation: https://youtu.be/AI7SLCubTnk?si=D1B-i5G28t5nTBfB&t=2600

segeljakt avatar Jan 01 '24 10:01 segeljakt