Algebrick - Algebraic types and pattern matching for Ruby
I've just released a new gem
algebrick which brings algebraic types and pattern matching to Ruby.
It's not as powerfull as Haskell's but it can still be quite useful. Let me give you a quick taste of the syntax.
Load DSL for type definition and define some algebraic types
extend Algebrick::DSL type_def do tree === empty | leaf(Integer) | node(tree, tree) end
Tree(Empty | Leaf | Node),
Node(Tree, Tree) are defined.
Lets add some methods, don't miss the pattern matching example.
module Tree # compute depth of a tree def depth match self, Empty >> 0, Leaf >> 1, # ~ will store and pass matched parts to variables left and right Node.(~any, ~any) --> left, right do 1 + [left.depth, right.depth].max end end end
Methods are defined on all values of type Tree
Empty.depth # => 0 Leaf.depth # => 1 Node[Leaf, Empty].depth # => 2 Node[Empty, Node[Leaf, Empty]].depth # => 3