Skip to content

Pattern matching #40

@wongjiahau

Description

@wongjiahau

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:

  • For tagged union
  • For Integer
  • For String
  • For Record types
  • On function arguments!

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions