jamiebuilds / ghost-lang

:ghost: A friendly little language for you and me.
302 stars 10 forks source link

Structs/Traits/Implementations #38

Open jamiebuilds opened 5 years ago

jamiebuilds commented 5 years ago

Structs

struct Employee {
  name: String,
  title: String,
}

let employee = Employee {
  name = "Jamie Kyle",
  title = "Principal Engineer",
}
employee.name
employee.title

Traits

trait Display {
  display: fn (self): String
}

trait Debug {
  debug: fn (self): String
}

Display.display(valueThatImplementsDisplay) # => String
Debug.debug(valueThatImplementsDebug) # => String

StructThatImplementsDisplay.display(structValue) # => String
StructThatImplementsDebug.debug(structValue) # => String

valueThatImplementsDisplay.display() # => String
valueThatImplementsDebug.debug() # => String

Implementations of Structs

implement Employee {
  new = fn (name: String, title: String) {
    return Employee { name, title }
  }

  changeTitle = fn (self, newTitle: String) {
    return Employee {
      name: self.name,
      title: newTitle,
    }
  }
}

let employee = Employee.new(
  name = "Jamie Kyle",
  title = "Principal Engineer",
)
let newEmployee = employee.changeTitle("Shitposter Extraordinaire")

Implementations of Traits

implement Employee as Display {
  display = fn (self) {
    return "{self.name} ({self.title})"
  }
}

let employee = Employee {
  name = "Jamie Kyle",
  title = "Principal Engineer",
}
employee.display() # "Jamie Kyle (Principal Engineer)"

Implementations of Structs and Traits

implement Employee as Display {
  new = fn (name: String, title: String) {
    return Employee { name, title }
  }

  changeTitle = fn (self, newTitle: String) {
    return Employee {
      name: self.name,
      title: newTitle,
    }
  }

  display = fn (self) {
    return "{self.name} ({self.title})"
  }
}

let employee = Employee.new(
  name = "Jamie Kyle",
  title = "Principal Engineer",
)
let newEmployee = employee.changeTitle("Shitposter Extraordinaire")
newEmployee.display() # "Jamie Kyle (Shitposter Extraordinaire)"

Implementations of multiple Traits

implement Employee as Display, Debug {
  display = fn (self) {
    return "{self.name} ({self.title})"
  }

  debug = fn (self) {
    return "Employee \{ name = \"{self.name}\", title = \"{self.title}\" \}"
  }
}

let employee = Employee {
  name = "Jamie Kyle",
  title = "Principal Engineer",
}
employee.display() # "Jamie Kyle (Principal Engineer)"
employee.debug() # "Employee \{ name = \"Jamie Kyle\", title = \"Principal Engineer\" \}"
jamiebuilds commented 5 years ago

Note: This is a complete rip-off of Rust because out of similar patterns, I like theirs best.