KeliLanguage / compiler

The compiler for Keli
https://keli-language.gitbook.io/doc/specification/
Apache License 2.0
171 stars 1 forks source link

Pattern matching #40

Open wongjiahau opened 5 years ago

wongjiahau commented 5 years ago

Purpose

Refer https://stackoverflow.com/questions/2502354/what-is-pattern-matching-in-functional-languages

Example

Shape = tags.case(circle.radius(Float)) case(square.side(Float))

(this Shape).area = 
  this.
    case(circle.radius(0.0)):
      (0.0)
    case(square.side(0.0)):
      (0.0)
    case(circle.radius(r)):
      (pi.*(r.square))
    case(square.side(10.0)):
      (100.0)
    case(square):
      (99999)

Warning

There are many kinds of pattern matching:

How to match function arguments?

Use record type matching as:

(this Boolean).or(that Boolean) =
  record.left(this) right(that).
    case(record.left(False) right(False)):
      (False)

    case(_):
      (True)

Pattern matching with predicates

This can be achieve using lambdas. For example,

(this Shape).isBig = 
  case(circle.radius(.>(5.0)):
    (Boolean.true)
  case(square.side(.>(10.0)):
    (Boolean.true)
  case(rectangle.width(.>(5.0)) height(.>(5.0))):
    (Boolean.true)
  case(other):
    (Boolean.false)
wongjiahau commented 5 years ago

This is actually not necessary at the moment, as it is more like an enhancement

wongjiahau commented 5 years ago

For implementation refer: https://www.microsoft.com/en-us/research/wp-content/uploads/1987/01/slpj-book-1987-small.pdf