8000 GitHub - iNecas/algebrick: Algebraic types and pattern matching
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

iNecas/algebrick

 
 

Repository files navigation

Algebrick

Build Status

It's a small gem providing algebraic types and pattern matching on them for Ruby.

What is it good for?

  • Defining data structures.
  • Algebraic types play nice with JSON serialization and deserialization. It is ideal for defining message-based cross-process communication.
  • and more...

Quick example

Let's define a Tree

Tree = Algebrick.type do |tree|
  variants Empty = atom,
           Leaf  = type { fields Integer },
           Node  = type { fields tree, tree }
end

Now types Tree(Empty | Leaf | Node), Empty, Leaf(Integer) and Node(Tree, Tree) are defined. 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

About

Algebraic types and pattern matching

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Ruby 100.0%
0