Skip to content

Unit112358/AlgebraicDataTypes

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AlgebraicDataTypes

This package literally provides algebraic data types(ADT) and performs pattern matching for them. It's inspried by some packages: ast-pattern-mathing and gara, and enum and pattern matching in the Rust language.

It provids two macros:

  • `?=` macro
    It can be used like Rust's if let syntax.
    let a = Option.Some(3)
    if Some(val) ?= a:
        echo val #> 3
    if None ?= a:
        echo "none"
  • match macro
    It's used for pattern matching. It's internally a compostion of if-else statement and `?=` macros.
    let a = Option.Some(3)
    match a
    of Some(val):
        echo val #> 3
    of None:
        echo "none"
    If you are using CaseStatementMacros, an experimental feature via {.experimental: "caseStmtMacros".}, you can use the case syntax instead of the match macro.
    let a = Option.Some(3)
    case a # not `match`
    of Some(val):
        echo val #> 3
    of None:
        echo "none"
    You can use case syntax and match macro as an expression.
    let
        a = Option.Some(3)
        b = case a # The same goes for `match` macro
        of Some(val):
            val
        of _:
            0
    echo b #> 3

Features

ADT

Defining an ADT

You can define an ADT by using a macro called Algebraic. It looks like this:

Algebraic Option[T]:
    Some(T)
    None

Pattern mathing

value

existing variable

If a variable name is included in the pattern and the variable already exists then a comparison is made with that variable, if not, the pattern match succeeds and binds its value to the variable name.

let a = (3, 4)
case a
of (b, _):
    echo a #> 3
let b = 1
case a
of (b, _):
    echo "a[0] == b"
of _: # pass this pattern
    echo "not match"

discarding

case a
of _:
    echo "hello"

expands to:

if true:
    echo "hello"

TODO

  • smarter error infomation: tuple length check, wheter ofBranch is, wheter discard pattern is, and so on

  • detect whether == is declared and emit error

  • support for slice(range) pattern

  • support for seq

  • support for Table

  • support for set

  • support for NimNode

  • check whether exhaustive or not

  • else branch

  • refactoring

  • strict func

  • view types

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Nim 100.0%