Skip to content

Supports for ADT enum? #6

@petamoriken

Description

@petamoriken

The enums in Swift, Rust and Scala (case class) can have values and it can be unwrapped by pattern matching.

// swift
enum Command {
    jump
    run(velocity: Int)
    punch(target: Enemy, power: Int)
}

let command = Command.run(20)
switch command {
case .jump:
  print("jump")
case .run(let velocity):
  print("run(velocity: \(velocity))")
case .punch(let target, let power):
  print("run(target: \(target), power: \(power))")
}

It would be more useful to support Algebraic Data Types (ADT), so I would like to include it in this proposal.

enum Command {
  jump
  run(velocity)
  punch(target, power)
}

// Stage 1 Pattern Matching
const command = Command.run(20);
case (command) {
  when Command.jump -> {
      console.log(`jump`);
  }
  when Command.run(velocity) -> {
      console.log(`run(velocity: ${velocity})`);
  }
  when Command.punch(target, power) -> {
      console.log(`punch(target: ${target}, power: ${power})`);
  }
}

// types
typeof Command.run === "function";
typeof Command.run(20) === "object";

// not necessary if implementation becomes difficult
Command.run(20) === Command.run(20);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions