Skip to content

Instantly share code, notes, and snippets.

@smies
Created April 23, 2013 12:52
Show Gist options
  • Save smies/5443314 to your computer and use it in GitHub Desktop.
Save smies/5443314 to your computer and use it in GitHub Desktop.
Active patterns to hide optimised implementation. From Expert F# 3.0
open System.Collections.Generic
type Prop =
| Prop of int
and PropRepr =
| AndRepr of Prop * Prop
| OrRepr of Prop * Prop
| NotRepr of Prop
| VarRepr of string
| TrueRepr
module PropOps =
let internal uniqStamp = ref 0
type internal PropTable() =
let fwdTable = new Dictionary<PropRepr, Prop>(HashIdentity.Structural)
let bwdTable = new Dictionary<int, PropRepr>(HashIdentity.Structural)
member t.ToUnique repr =
if fwdTable.ContainsKey repr then fwdTable.[repr]
else let stamp = incr uniqStamp; !uniqStamp
let prop = Prop stamp
fwdTable.Add (repr, prop)
bwdTable.Add (stamp, repr)
prop
member t.FromUnique (Prop stamp) =
bwdTable.[stamp]
let internal table = PropTable ()
// Public construction functions
let And (p1, p2) = table.ToUnique (AndRepr (p1, p2))
let Not p = table.ToUnique (NotRepr p)
let Or (p1, p2) = table.ToUnique (OrRepr (p1, p2))
let Var p = table.ToUnique (VarRepr p)
let True = table.ToUnique TrueRepr
let False = Not True
// Deconstruction function
let getRepr p = table.FromUnique p
let (|And|Or|Not|Var|True|) prop =
match table.FromUnique prop with
| AndRepr (x, y) -> And (x, y)
| OrRepr (x, y) -> Or (x, y)
| NotRepr x -> Not x
| VarRepr v -> Var v
| TrueRepr -> True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment