Add static variables
rozaxe opened this issue Β· comments
βοΈ Proposed change
I propose a way to define instance variables which can be called on the type rather on an instance of the type.
π€ Rationale
This would allows to store values on a type, and use them from type methods.
This would also allows the development of the singleton
pattern.
πΊExample
Here an example of an implementation of the singleton
pattern :
ππΎπ
πππ instance π¬πΎ
ππππ
πβοΈπΎ β‘οΈ πΎ π
βͺοΈπ€·ββοΈ π instance π
ππΎπβοΈ β‘οΈ ππinstance
π
β©οΈ πΊinstance
π
π
This defines a static variable πππ instance π¬πΎ
accessibles from the type itself with πinstance
.
We can then call the singleton with πΎππΎβοΈ
and access the unique instance of the type πΎ
Perfect except that I don't think β‘οΈππinstance
is good. β‘οΈπinstance
like with instance methods would be better. After all, type methods really are in the context of the type. (π contains the type.)
You wanna try to implement this? π
At least I will try ! π
I am digging into implementing this, and I found a problem. How a static variable initial value would be set ?
π π π
πππ count π‘
π βοΈ πββοΈ π
count β 1 β‘οΈ π count
π
π βοΈ πββοΈ π
π count βοΈ
π
π
For example, what would be count
initial value ?
Do you think we could add "on step declaration and assignment variable" in type as well ?
Something like that :
π π©βπΌ π
5300 β‘οΈ ππ money
π ππ
π
After calling ππ©βπΌπ
the value of money
would be set to 5300
?
Thus, we could write something like that for static variables :
π π π
0 β‘οΈ πππ count
π
Declaring and Assigning in one step in types would be great.
These expressions would have to be evaluated in a context where π (and thus access to instance variables) is disallowed, I guess.
@rozaxe Can you please give me a heads-up before you implement anything concerning the declaration and assignment in type bodies? I want to some refactoring here first, if possible.
No problem, go again ! (I need some time to understand how the compile works in whole, so do not hesitate to implements features)
So we have a syntax issue here. Consider this code:
π π©βπΌ π
ππ¦πβοΈ β‘οΈ ππ pet
π
While this is a variable assignment, it is hard for the compiler to tell it apart from an initializer definition:
π π©βπΌ π
ππ¦ π
π
π
Emojicode uses a strict LL(1) grammar, which makes this impossible. I think the best solution is:
π π©βπΌ π
ππ pet β¬
οΈ ππ¦π βοΈ
π
So for recap, for instance variable :
ππ pet β¬
οΈ ππ¦π βοΈ
And for "in method variable" :
ππ¦π βοΈβ‘οΈ ππ pet
Yes, although I think it might even be
ππ pet π¦ β¬
οΈ ππ¦π βοΈ
because type inference could be difficult here. Furthermore, a well-reasoned argument against something like this was made in #83 .
β This is implemented on 0.7.
https://0-7.emojicode.org/docs/reference/classes-valuetypes.html#instance-variables
Sorry, I do not feel I will be able to implement this (too many knowledge).
I will keep my motivation for implementing some useful package !