charly-lang / charly

🐈 The Charly Programming Language | Written by @KCreate
https://charly-lang.github.io/charly/
MIT License
199 stars 10 forks source link

Enums #120

Open KCreate opened 7 years ago

KCreate commented 7 years ago
enum MyEnum {
  Foo
  Bar
  Baz
}

MyEnum.Foo # => 0
MyEnum.Bar # => 1
MyEnum.Baz # => 2

Enums can also have static methods

enum MyEnum {
  Foo
  Bar
  Baz

  func is_foo(value) {
    value == @Foo
  }
}

The values of an enum are Numeric values starting at 0, incrementing with each value added to the enum. The enum is represented as an object.

The above code is equivalent to the following object literal:

let MyEnum = {
  const Foo = 0
  const Bar = 1
  const Baz = 2

  func is_foo(value) {
    value == @Foo
  }
}
ghost commented 7 years ago

@KCreate Good idea, that gives us more opportunities to seperate the functions from other objects

ghost commented 6 years ago

@KCreate But are the functions actually necessary? Any examples for a good use?

KCreate commented 6 years ago

Writing code with enums usually requires comparing them every so often. Sometimes that code becomes long and complicated. Allowing functions directly inside enums makes it possible to encapsulate logic and abstract implementation details away.

En example that comes to mind is checking whether a type of token is a keyword or not.

enum Token {
  Let
  Const
  If
  Integer

  func is_keyword() {
    return self == Token.Let || self == Token.Const
  }
}