JSAbrahams / mamba

🐍 The Mamba programming language, because we care about safety
MIT License
85 stars 3 forks source link

Should we have a keyword to specify self is mutable in function signatures #378

Closed JSAbrahams closed 1 year ago

JSAbrahams commented 1 year ago

Current Issue

Ideally we want in functions to be able to define whether self is mutable or not. Currently, the default is that it is mutable, and if we want self to be final then we have to add fin. E.g:

def f(fin self, a, b ....)

However, by default users will most likely always have self be mutable (by not appending fin). This is fine, until we have a final variable and try to access its methods. Then, the compiler will constantly throw errors because self will most likely be mutable (even when it needn't be). Instead, we want that self is final by default and only mutable if the user explicitly defines this. This falls along the line of the philosophy of "strict, but as familiar as possible to those coming from Python. So then we would have the following:

class MyClass
    def c: Int := 10

    def f(self, a) -> Int =>
        a + b

    def g(mut self, a) -> Int =>
        self.c += a
        a + b

def my_class := MyClass()

my_class.f(10)
my_class.g(10)

def fin my_class := MyClass()
my_class.g(10) # gives error!

A few issues here is that:

High-level description of the feature

Description of potential implementation

JSAbrahams commented 1 year ago

I'm leaning towards not doing this, but I'll leave this hear until we reach this milestone. The main reason for not doing this would be that we should in functions stick to the same philosophy as top-level scripts. My main gripe is that for many applications you don't need everything to be mutable, so having to put fin constantly in signatures is a bit cumbersome and may lead to it not being used.

In top-level scripts, I'm just leaving the behaviour as-is anyway because I'm assuming most variables need to be mutable there. We could also use the var val system from Kotlin and Scala (?). Would be a bit sad since I did like that we use def for everything, which feels more math-like.