ML-Style Qualified Unions for Ruby
Logan Capaldo brings us ML-style qualified unions in Ruby:
require 'mltypes'
deftype :List do
:Cons.of( :first => :Object,
:rest => :List ) |
:End
end
deftype :Tree do
:Leaf.of( :data => :Object ) |
:Branch.of( :data => :Object,
:left => :Tree,
:right => :Tree )
end
def print_list( list )
case list.tag
when :Cons
puts list.first
print_list( list.rest )
when :End
end
end
def print_tree_inorder( tree )
case tree.tag
when :Leaf
puts tree.data
when :Branch
print_tree_inorder( tree.left )
puts tree.data
print_tree_inorder( tree.right )
end
end
ls = List.Cons( :first => 1,
:rest => List.End )
ls = List.Cons( :first => "Hello",
:rest => ls )
print_list ls
tree = Tree.Branch(
:data => 2,
:left => Tree.Leaf( :data => 1 ),
:right => Tree.Leaf( :data => 3 ) )
print_tree_inorder( tree )
The source for his mltypes library is available in his original post.