Skip to content

Instantly share code, notes, and snippets.

@steshaw
Created October 27, 2010 01:10
Show Gist options
  • Save steshaw/648192 to your computer and use it in GitHub Desktop.
Save steshaw/648192 to your computer and use it in GitHub Desktop.
(* A simple pattern matching example from http://www.c2.com/cgi/wiki?PatternMatching *)
(*
* Define type `expr' to have two constructors:
* Constant(anInteger) represents a constant
* Sum(anExpr, anotherExpr) represents the sum of two expressions.
*)
datatype expr =
Constant of int
| Sum of expr*expr
fun eval(Constant c) = c (* A constant evaluates to itself. *)
| eval(Sum(x, y)) = eval(x) + eval(y) (* eval(x+y)=eval(x)+eval(y). *)
(*
* The compiler infers that eval takes an expr as its argument, and it
* makes sure that both Constant and Sum are handled. If someone comes
* back later and adds, say, a Product constructor to expr, any
* pattern-match that dissects an expr without somehow handling the case
* of Product will raise a warning.
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment