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.
Quick example
Load DSL for type definition and define some algebraic types
extend Algebrick::DSL
type_def do
tree === empty | leaf(Integer) | node(tree, tree)
end
Now types Tree(Empty | Leaf | Node)
, Empty
, Leaf(Integer)
and 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[10].depth # => 1
Node[Leaf[4], Empty].depth # => 2
Node[Empty, Node[Leaf[1], Empty]].depth # => 3
Do you wish to know more?
- Documentation: http://blog.pitr.ch/algebrick
- Source: https://github.com/pitr-ch/algebrick
- Blog: http://blog.pitr.ch/blog/categories/algebrick/