algebrick-0.7.4/0000755000004100000410000000000013040707711013475 5ustar www-datawww-dataalgebrick-0.7.4/algebrick.gemspec0000644000004100000410000000637013040707711016773 0ustar www-datawww-data######################################################### # This file has been automatically generated by gem2tgz # ######################################################### # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = "algebrick" s.version = "0.7.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Petr Chalupa"] s.date = "2017-01-12" s.description = "Provides algebraic type definitions and pattern matching" s.email = "git+algebrick@pitr.ch" s.extra_rdoc_files = ["LICENSE.txt", "README.md", "README_FULL.md", "VERSION", "doc/data.out.rb", "doc/extending_behavior.out.rb", "doc/json.out.rb", "doc/null.out.rb", "doc/parametrized.out.rb", "doc/pattern_matching.out.rb", "doc/quick_example.out.rb", "doc/tree1.out.rb", "doc/type_def.out.rb", "doc/values.out.rb"] s.files = ["LICENSE.txt", "README.md", "README_FULL.md", "VERSION", "doc/data.out.rb", "doc/extending_behavior.out.rb", "doc/json.out.rb", "doc/null.out.rb", "doc/parametrized.out.rb", "doc/pattern_matching.out.rb", "doc/quick_example.out.rb", "doc/tree1.out.rb", "doc/type_def.out.rb", "doc/values.out.rb", "lib/algebrick.rb", "lib/algebrick/atom.rb", "lib/algebrick/dsl.rb", "lib/algebrick/field_method_readers.rb", "lib/algebrick/matcher_delegations.rb", "lib/algebrick/matchers.rb", "lib/algebrick/matchers/abstract.rb", "lib/algebrick/matchers/abstract_logic.rb", "lib/algebrick/matchers/and.rb", "lib/algebrick/matchers/any.rb", "lib/algebrick/matchers/array.rb", "lib/algebrick/matchers/atom.rb", "lib/algebrick/matchers/many.rb", "lib/algebrick/matchers/not.rb", "lib/algebrick/matchers/or.rb", "lib/algebrick/matchers/product.rb", "lib/algebrick/matchers/variant.rb", "lib/algebrick/matchers/wrapper.rb", "lib/algebrick/matching.rb", "lib/algebrick/parametrized_type.rb", "lib/algebrick/product_constructors.rb", "lib/algebrick/product_constructors/abstract.rb", "lib/algebrick/product_constructors/basic.rb", "lib/algebrick/product_constructors/named.rb", "lib/algebrick/product_variant.rb", "lib/algebrick/reclude.rb", "lib/algebrick/serializer.rb", "lib/algebrick/serializers.rb", "lib/algebrick/type.rb", "lib/algebrick/type_check.rb", "lib/algebrick/types.rb", "lib/algebrick/value.rb"] s.homepage = "https://github.com/pitr-ch/algebrick" s.licenses = ["Apache-2.0"] s.require_paths = ["lib"] s.rubygems_version = "1.8.23" s.summary = "Algebraic types and pattern matching for Ruby" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q, ["~> 1.13"]) s.add_development_dependency(%q, ["~> 5.10"]) s.add_development_dependency(%q, ["~> 1.1"]) s.add_development_dependency(%q, ["~> 0.9"]) else s.add_dependency(%q, ["~> 1.13"]) s.add_dependency(%q, ["~> 5.10"]) s.add_dependency(%q, ["~> 1.1"]) s.add_dependency(%q, ["~> 0.9"]) end else s.add_dependency(%q, ["~> 1.13"]) s.add_dependency(%q, ["~> 5.10"]) s.add_dependency(%q, ["~> 1.1"]) s.add_dependency(%q, ["~> 0.9"]) end end algebrick-0.7.4/doc/0000755000004100000410000000000013040707711014242 5ustar www-datawww-dataalgebrick-0.7.4/doc/parametrized.out.rb0000644000004100000410000000331513040707711020066 0ustar www-datawww-data# Let's define Tree but this time parameterized by :value_type, Tree = Algebrick.type(:value_type) do |tree| variants Empty = atom, Leaf = type(:value_type) { fields value: :value_type }, Node = type(:value_type) { fields left: tree, right: tree } end # with method depth defined as before. module Tree def depth match self, Empty >> 0, Leaf >> 1, Node.(~any, ~any) >-> left, right do 1 + [left.depth, right.depth].max end end end # Then Tree, Leaf, Node are Tree.class # => Algebrick::ParametrizedType [Tree, Leaf, Node] # => [Tree[value_type], Leaf[value_type], Node[value_type]] # which servers as factories to actual types. Tree[Float] # => Tree[Float](Empty | Leaf[Float] | Node[Float]) Tree[String] # => Tree[String](Empty | Leaf[String] | Node[String]) # Types cannot be mixed. Leaf[Integer]['1'] rescue $! # => # Node[Integer][Leaf[String]['a'], Empty] rescue $! # => # Leaf[String]['1'] # => Leaf[String][value: 1] # Depth method works as before. integer_tree = Node[Integer][Leaf[Integer][2], Empty] # => Node[Integer][left: Leaf[Integer][value: 2], right: Empty] integer_tree.depth # => 2 string_tree = Node[String][Empty, Empty] # => Node[String][left: Empty, right: Empty] string_tree.depth # => 1 algebrick-0.7.4/doc/quick_example.out.rb0000644000004100000410000000203213040707711020221 0ustar www-datawww-data# Let's define a Tree Tree = Algebrick.type do |tree| variants Empty = atom, Leaf = type { fields Integer }, Node = type { fields tree, tree } end # => Tree(Empty | Leaf | Node) # Now types `Tree(Empty | Leaf | Node)`, `Empty`, `Leaf(Integer)` and `Node(Tree, Tree)` are defined. # Let's add a method, don't miss the **pattern matching** example. module Tree # compute depth of a tree def depth match self, (on Empty, 0), (on Leaf, 1), # ~ will store and pass matched parts to variables left and right (on Node.(~any, ~any) do |left, right| 1 + [left.depth, right.depth].max end) end end # Method defined in module `Tree` are passed down to **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 algebrick-0.7.4/doc/pattern_matching.out.rb0000644000004100000410000001441113040707711020725 0ustar www-datawww-data# Let's define a tree and binary tree to demonstrate the pattern matching abilities. Tree = Algebrick.type do |tree| variants Empty = type, Leaf = type { fields Integer }, Node = type { fields tree, tree } end # => Tree(Empty | Leaf | Node) BinaryTree = BTree = Algebrick.type do |btree| fields! value: Comparable, left: btree, right: btree variants Empty, btree end # => BTree(Empty | BTree(value: Comparable, left: BTree, right: BTree)) extend Algebrick::Matching # => main # Product matchers are constructed with #.() syntax. Leaf.(any) === Leaf[1] # => true Leaf.(1) === Leaf[1] # => true Leaf.(2) === Leaf[1] # => false # There are also some shortcuts to use when product has more fields. BTree.() # => BTree.(any, any, any) BTree.(value: any, left: Empty) # => BTree.(any, Empty, any) BTree.(value: any, left: Empty) === BTree[1, Empty, Empty] # => true # Any object responding to #=== can be converted to matcher. (1..2).to_m # => Wrapper.(1..2) (1..2).to_m === 2 # => true Empty.to_m # => Empty.to_m # As matchers are using standard #=== method it does not have to be always converted. Empty === Empty # => true Leaf === Leaf[1] # => true # Tree matches all its values. [Empty, Leaf[1], Node[Empty, Empty]].all? { |v| Tree === v } # => true # There is also a #match method in Matching module to make pattern matching easier. match Leaf[1], # supply the value for matching # if Leaf.(0) matches :zero is returned (on Leaf.(0), :zero), # when computation of the result needs to be avoided use block # if Leaf.(1) matches block is called and its result is returned (on Leaf.(1) do (1..10000).inject(:*) # expensive computation :one # which is :one in this case end) # => :one # Alternatively case can be used. case Leaf[1] when Leaf.(0) :zero when Leaf.(1) (1..10000).inject(:*) # expensive computation :one end # => :one # But that won't work nicely with value deconstruction. # Each matcher can be marked with #~ method to store value against which is being matched, # each matched value is passed to the block, ... match Leaf[0], (on ~Leaf.(~any) do |leaf, value| [leaf, value] end) # => [Leaf[0], 0] btree = BTree[1, BTree[0, Empty, Empty], Empty] # => BTree[value: 1, left: BTree[value: 0, left: Empty, right: Empty], right: Empty] match btree, (on BTree.(any, ~any, ~any) do |left, right| [left, right] end) # => [BTree[value: 0, left: Empty, right: Empty], Empty] # or alternatively you can use Ruby's multi-assignment feature. match btree, (on ~BTree do |(_, left, right)| [left, right] end) # => [BTree[value: 0, left: Empty, right: Empty], Empty] # Matchers also support logical operations #& for and, #| for or, and #! for negation. Color = Algebrick.type do variants Black = atom, White = atom, Pink = atom, Grey = type { fields scale: Float } end # => Color(Black | White | Pink | Grey) def color?(color) match color, on(Black | Grey.(-> v { v < 0.2 }), 'black-ish'), on(White | Grey.(-> v { v > 0.8 }), 'white-ish'), on(Grey.(-> v { v >= 0.2 }) & Grey.(-> v { v <= 0.8 }), 'grey-ish'), on(Pink, "that's not a color ;)") end # => :color? color? Black # => "black-ish" color? Grey[0.1] # => "black-ish" color? Grey[0.3] # => "grey-ish" color? Grey[0.9] # => "white-ish" color? White # => "white-ish" color? Pink # => "that's not a color ;)" # A more complicated example of extracting node's value and values of its left and right side # using also logical operators to allow Empty sides. match BTree[0, Empty, BTree[1, Empty, Empty]], (on BTree.({ value: ~any, left: Empty | BTree.(value: ~any), right: Empty | BTree.(value: ~any) }) do |value, left, right| { left: left, value: value, right: right } end) # => {:left=>nil, :value=>0, :right=>1} # It also supports matching against Ruby Arrays Array.() === [] # => true Array.() === [1] # => false Array.(*any) === [] # => true Array.(*any) === [1] # => true Array.(*any) === [1, 2] # => true Array.(1, *any) === [] # => false Array.(1, *any) === [1] # => true Array.(1, *any) === [1, 2] # => true match [], on(~Array.to_m) { |v| v } # => [] match [], on(~Array.()) { |v| v } # => [] match [1, 2], on(~Array.(*any)) { |v| v } # => [1, 2] match [1, 2], on(~Array.(*any)) { |(v, _)| v } # => 1 match [1, 2, 3], on(Array.(any, *~any)) { |v| v } # => [2, 3] match [:first, 1, 2, 3], on(Array.(:first, ~any, *any)) { |v| v } # => 1 match [:+, 1, 2, :foo, :bar], (on Array.(:+, ~Integer.to_m, ~Integer.to_m, *~any) do |int1, int2, rest| { sum: int1 + int2, rest: rest } end) # => {:sum=>3, :rest=>[:foo, :bar]} # There is also a more funky syntax for matching # using #>, #>> and Ruby 1.9 syntax for lambdas `-> {}`. match Leaf[1], Leaf.(0) >> :zero, Leaf.(~any) >-> value do (1..value).inject(:*) # an expensive computation end # => 1 algebrick-0.7.4/doc/null.out.rb0000644000004100000410000000214013040707711016344 0ustar www-datawww-dataextend Algebrick::Matching # => main def deliver_email(email) true end Contact = Algebrick.type do |contact| variants Null = atom, contact fields username: String, email: String end # => Contact(Null | Contact(username: String, email: String)) module Contact def username match self, Null >> 'no name', Contact >-> { self[:username] } end def email match self, Null >> 'no email', Contact >-> { self[:email] } end def deliver_personalized_email match self, Null >> true, Contact >-> { deliver_email(self.email) } end end peter = Contact['peter', 'example@dot.com'] # => Contact[username: peter, email: example@dot.com] john = Contact[username: 'peter', email: 'example@dot.com'] # => Contact[username: peter, email: example@dot.com] nobody = Null # => Null [peter, john, nobody].map &:email # => ["example@dot.com", "example@dot.com", "no email"] [peter, john, nobody].map &:deliver_personalized_email # => [true, true, true] algebrick-0.7.4/doc/type_def.out.rb0000644000004100000410000000201713040707711017174 0ustar www-datawww-data# Let's define some types Maybe = Algebrick.type do variants None = atom, Some = type { fields Numeric } end # => Maybe(None | Some) # where the Maybe actually is: Maybe.class # => Algebrick::ProductVariant Maybe.class.superclass # => Algebrick::Type Maybe.class.superclass.superclass # => Module Maybe.class.superclass.superclass.superclass # => Object # if there is a circular dependency you can define the dependent types inside the block like this: Tree = Algebrick.type do |tree| variants Empty = type, Leaf = type { fields Integer }, Node = type { fields tree, tree } end # => Tree(Empty | Leaf | Node) Empty # => Empty Leaf # => Leaf(Integer) Node # => Node(Tree, Tree) algebrick-0.7.4/doc/extending_behavior.out.rb0000644000004100000410000000363713040707711021252 0ustar www-datawww-dataMaybe = Algebrick.type do variants None = atom, Some = type { fields Object } end # => Maybe(None | Some) # Types can be extended with usual syntax for modules and using Ruby supports module reopening. module Maybe def maybe(&block) case self when None when Some block.call value end end end # #maybe method is defined on both values (None, Some) of Maybe. None.maybe { |_| raise 'never ever happens' } # => nil # Block is called with the value. Some[1].maybe { |v| v*2 } # => 2 # It also works as expected when modules like Comparable are included. Season = Algebrick.type do variants Spring = atom, Summer = atom, Autumn = atom, Winter = atom end # => Season(Spring | Summer | Autumn | Winter) module Season include Comparable ORDER = Season.variants.each_with_index.each_with_object({}) { |(season, i), h| h[season] = i } def <=>(other) Type! other, Season ORDER[self] <=> ORDER[other] end end Quarter = Algebrick.type do fields! year: Integer, season: Season end # => Quarter(year: Integer, season: Season) module Quarter include Comparable def <=>(other) Type! other, Quarter [year, season] <=> [other.year, other.season] end end # Now Quarters and Seasons can be compared as expected. [Winter, Summer, Spring, Autumn].sort # => [Spring, Summer, Autumn, Winter] Quarter[2013, Spring] < Quarter[2013, Summer] # => true Quarter[2014, Spring] > Quarter[2013, Summer] # => true Quarter[2014, Spring] == Quarter[2014, Spring] # => true [Quarter[2013, Spring], Quarter[2013, Summer], Quarter[2014, Spring]].sort # => [Quarter[year: 2013, season: Spring], Quarter[year: 2013, season: Summer], Quarter[year: 2014, season: Spring]] algebrick-0.7.4/doc/values.out.rb0000644000004100000410000000475113040707711016703 0ustar www-datawww-data# Let's define a Tree Tree = Algebrick.type do |tree| variants Empty = type, Leaf = type { fields Integer }, Node = type { fields tree, tree } end # => Tree(Empty | Leaf | Node) # Values of atomic types are represented by itself, # they are theirs own value. Empty.kind_of? Algebrick::Value # => true Empty.kind_of? Algebrick::Type # => true Empty.kind_of? Empty # => true # Values of product types are constructed with #[] and they are immutable. Leaf[1].kind_of? Algebrick::Value # => true Leaf[1].kind_of? Leaf # => true Node[Empty, Empty].kind_of? Node # => true # Variant does not have its own values, it uses atoms and products. Leaf[1].kind_of? Tree # => true Empty.kind_of? Tree # => true # Product can have its fields named. BinaryTree = BTree = Algebrick.type do |btree| fields! value: Integer, left: btree, right: btree variants Tip = atom, btree end # => BTree(Tip | BTree(value: Integer, left: BTree, right: BTree)) # Then values can be created with names tree1 = BTree[value: 1, left: Tip, right: Tip] # => BTree[value: 1, left: Tip, right: Tip] # or without them as before. BTree[0, Tip, tree1] # => BTree[value: 0, left: Tip, right: BTree[value: 1, left: Tip, right: Tip]] # Fields of products can be read as follows: # 1. When type has only one field method #value is defined Leaf[1].value # => 1 # 2. By multi-assign v, left, right = BTree[value: 1, left: Tip, right: Tip] # => BTree[value: 1, left: Tip, right: Tip] [v, left, right] # => [1, Tip, Tip] # 3. With #[] method when fields are named BTree[value: 1, left: Tip, right: Tip][:value] # => 1 BTree[value: 1, left: Tip, right: Tip][:left] # => Tip # 4. With methods named by fields when fields are named # (it can be disabled if fields are defined with #fields instead of #fields!) BTree[1, Tip, Tip].value # => 1 BTree[1, Tip, Tip].left # => Tip # Product instantiation raises TypeError when being constructed with wrong type. Leaf['a'] rescue $! # => # Node[nil, Empty] rescue $! # => # algebrick-0.7.4/doc/json.out.rb0000644000004100000410000000362613040707711016355 0ustar www-datawww-dataextend Algebrick::Matching # => main # Lets define message-protocol for a cross-process communication. Request = Algebrick.type do User = type { fields login: String, password: String } variants CreateUser = type { fields User }, GetUser = type { fields login: String } end # => Request(CreateUser | GetUser) Response = Algebrick.type do variants Success = type { fields Object }, Failure = type { fields error: String } end # => Response(Success | Failure) Message = Algebrick.type { variants Request, Response } # => Message(Request | Response) require 'algebrick/serializer' # => true require 'multi_json' # => true # Prepare a message for sending. serializer = Algebrick::Serializer.new # => # request = CreateUser[User['root', 'lajDh4']] # => CreateUser[User[login: root, password: lajDh4]] raw_request = MultiJson.dump serializer.dump(request) # => "{\"algebrick_type\":\"CreateUser\",\"algebrick_fields\":[{\"algebrick_type\":\"User\",\"login\":\"root\",\"password\":\"lajDh4\"}]}" # Receive the message. response = match serializer.load(MultiJson.load(raw_request)), (on CreateUser.(~any) do |user| # create the user and send success Success[user] end) # => Success[User[login: root, password: lajDh4]] # Send response. response_raw = MultiJson.dump serializer.dump(response) # => "{\"algebrick_type\":\"Success\",\"algebrick_fields\":[{\"algebrick_type\":\"User\",\"login\":\"root\",\"password\":\"lajDh4\"}]}" # Receive response. serializer.load(MultiJson.load(response_raw)) # => Success[User[login: root, password: lajDh4]] algebrick-0.7.4/doc/data.out.rb0000644000004100000410000000647513040707711016322 0ustar www-datawww-dataextend Algebrick::Matching # => main # Simple data structures like trees Tree = Algebrick.type do |tree| variants Tip = type, Node = type { fields value: Object, left: tree, right: tree } end # => Tree(Tip | Node) module Tree def depth match self, Tip.to_m >> 0, Node.(any, ~any, ~any) >-> left, right do 1 + [left.depth, right.depth].max end end end tree = Node[2, Tip, Node[5, Node[4, Tip, Tip], Node[6, Tip, Tip]]] # => Node[value: 2, left: Tip, right: Node[value: 5, left: Node[value: 4, left: Tip, right: Tip], right: Node[value: 6, left: Tip, right: Tip]]] tree.depth # => 3 # Whenever you find yourself to pass around too many fragile Hash-Array structures # e.g. for menus. Menu = Algebrick.type do |menu| Item = Algebrick.type do variants Delimiter = atom, Link = type { fields! label: String, url: String }, Group = type { fields! label: String, submenu: menu } end fields! item: Item, next: menu variants None = atom, menu end # => Menu(None | Menu(item: Item, next: Menu)) None # => None Item # => Item(Delimiter | Link | Group) module Link def self.new(*fields) super(*fields).tap { |menu| valid! menu.url } end def self.valid!(url) # stub end end module Item def draw_menu(indent = 0) match self, Delimiter >-> { [' '*indent + '-'*10] }, Link.(label: ~any) >-> label { [' '*indent + label] }, (on ~Group do |(label, sub_menu)| [' '*indent + label] + sub_menu.draw_menu(indent + 2) end) end end module Menu def self.build(*items) items.reverse_each.reduce(None) { |menu, item| Menu[item, menu] } end include Enumerable def each(&block) it = self loop do break if None === it block.call it.item it = it.next end end def draw_menu(indent = 0) map { |item| item.draw_menu indent }.reduce(&:+) end end sub_menu = Menu.build Link['Red Hat', '#red-hat'], Delimiter, Link['Ubuntu', '#ubuntu'], Link['Mint', '#mint'] # => Menu[item: Link[label: Red Hat, url: #red-hat], next: Menu[item: Delimiter, next: Menu[item: Link[label: Ubuntu, url: #ubuntu], next: Menu[item: Link[label: Mint, url: #mint], next: None]]]] menu = Menu.build Link['Home', '#home'], Delimiter, Group['Linux', sub_menu], Link['About', '#about'] # => Menu[item: Link[label: Home, url: #home], next: Menu[item: Delimiter, next: Menu[item: Group[label: Linux, submenu: Menu[item: Link[label: Red Hat, url: #red-hat], next: Menu[item: Delimiter, next: Menu[item: Link[label: Ubuntu, url: #ubuntu], next: Menu[item: Link[label: Mint, url: #mint], next: None]]]]], next: Menu[item: Link[label: About, url: #about], next: None]]]] menu.draw_menu.join("\n") # => "Home\n----------\nLinux\n Red Hat\n ----------\n Ubuntu\n Mint\nAbout" # Group['Products', # Menu[]], # Link['About', '#about'] #]] algebrick-0.7.4/doc/tree1.out.rb0000644000004100000410000000111413040707711016412 0ustar www-datawww-dataTree = Algebrick.type do |tree| variants Empty = type, Leaf = type { fields Integer }, Node = type { fields tree, tree } end # => Tree(Empty | Leaf | Node) # Which sets 4 modules representing these types in current module/class Tree # => Tree(Empty | Leaf | Node) Empty # => Empty Leaf # => Leaf(Integer) Node # => Node(Tree, Tree) algebrick-0.7.4/LICENSE.txt0000644000004100000410000002404313040707711015323 0ustar www-datawww-dataApache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. # Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. algebrick-0.7.4/README_FULL.md0000644000004100000410000000663613040707711015611 0ustar www-datawww-data# Algebrick Typed structs on steroids based on algebraic types and pattern matching seamlessly integrating with standard Ruby features. - Documentation: - Source: - Blog: ## Quick example {include:file:doc/quick_example.out.rb} ## Algebraic types Algebraic types are: - products with a given number of fields, - or a kind of composite type, i.e. a type formed by combining other types. In Haskell algebraic type looks like this: data Tree = Empty | Leaf Int | Node Tree Tree depth :: Tree -> Int depth Empty = 0 depth (Leaf n) = 1 depth (Node l r) = 1 + max (depth l) (depth r) depth (Node Empty (Leaf 5)) -- => 2 This snippet defines type `Tree` which has 3 possible values: - `Empty` - `Leaf` with and extra value of type `Int` - `Node` with two values of type `Tree` and function `depth` to calculate depth of a tree which is called on the last line and evaluates to `2`. Same `Tree` type and `depth` method can be also defined with this gem as it was shown in {file:README_FULL.md#quick-example Quick Example}. ### Algebrick implementation Algebrick distinguishes 4 kinds of algebraic types: 1. **Atom** - type that has only one value, e.g. `Empty`. 2. **Product** - type that has a set number of fields with given type, e.g. `Leaf(Integer)` 3. **Variant** - type that is one of the set variants, e.g. `Tree(Empty | Leaf(Integer) | Node(Tree, Tree)`, meaning that values `Empty`, `Leaf[1]`, `Node[Empty, Empry]` have all type `Tree`. 4. **ProductVariant** - will be created when a recursive type like `List(Empty | List(Integer, List))` is defined. `List` has two variants: `Empty` and itself. Simultaneously it has fields as a product type. Atom type is implemented with {Algebrick::Atom} and the rest is implemented with {Algebrick::ProductVariant} which behaves differently based on what is set: fields, variants, or both. More information can be found at . ## Documentation ### Type definition {include:file:doc/type_def.out.rb} ### Value creation {include:file:doc/values.out.rb} ### Behaviour extending {include:file:doc/extending_behavior.out.rb} ### Pattern matching Pattern matching is implemented with helper objects defined in `ALgebrick::Matchers`. They use standard `#===` method to match against values. {include:file:doc/pattern_matching.out.rb} ### Parametrized types {include:file:doc/parametrized.out.rb} ## What is it good for? ### Defining data structures - Simple data structures like trees - Whenever you find yourself to pass around too many fragile Hash-Array structures _Examples are coming shortly._ ### Serialization Algebraic types also play nice with JSON serialization and de-serialization making it ideal for defining message-based cross-process communication. {include:file:doc/json.out.rb} ### Message matching in Actor pattern Just a small snippet how it can be used in Actor model world. {include:file:doc/actor.rb} algebrick-0.7.4/lib/0000755000004100000410000000000013040707711014243 5ustar www-datawww-dataalgebrick-0.7.4/lib/algebrick/0000755000004100000410000000000013040707711016166 5ustar www-datawww-dataalgebrick-0.7.4/lib/algebrick/serializers.rb0000644000004100000410000000161113040707711021046 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Serializers require 'algebrick/serializers/abstract' require 'algebrick/serializers/abstract_to_hash' require 'algebrick/serializers/chain' require 'algebrick/serializers/strict_to_hash' require 'algebrick/serializers/benevolent_to_hash' end end algebrick-0.7.4/lib/algebrick/parametrized_type.rb0000644000004100000410000000624613040707711022253 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick require 'monitor' class ParametrizedType < Type include TypeCheck include MatcherDelegations include FieldMethodReaders attr_reader :variables, :fields, :variants def initialize(variables) @variables = variables.each { |v| Type! v, Symbol } @fields = nil @variants = nil @cache = {} @cache_barrier = Monitor.new end def set_fields(fields) @fields = Type! fields, Hash, Array @field_names = case @fields when Hash @fields.keys when Array, nil nil else raise end end def set_variants(*variants) @variants = Type! variants, Array end def [](*assigned_types) @cache_barrier.synchronize do @cache[assigned_types] || begin raise ArgumentError unless assigned_types.size == variables.size ProductVariant.new(type_name(assigned_types)).tap do |type| type.be_kind_of self @cache[assigned_types] = type type.assigned_types = assigned_types type.set_variants *insert_types(variants, assigned_types) if variants type.set_fields insert_types(fields, assigned_types) if fields end end end end def generic @generic ||= self[*Array(variables.size) { Object }] end def to_s "#{name}[#{variables.join(', ')}]" end def inspect to_s end def to_m if @variants Matchers::Variant.new self else Matchers::Product.new self end end def call(*field_matchers) raise TypeError unless @fields Matchers::Product.new self, *field_matchers end def ==(other) other.kind_of? ParametrizedType and self.generic == other.generic end private def insert_types(types, assigned_types) case types when Hash types.inject({}) { |h, (k, v)| h.update k => insert_type(v, assigned_types) } when Array types.map { |v| insert_type v, assigned_types } else raise ArgumentError end end def insert_type(type, assigned_types) case type when Symbol assigned_types[variables.index type] when ParametrizedType type[*type.variables.map { |v| assigned_types[variables.index v] }] else type end end def type_name(assigned_types) "#{name}[#{assigned_types.join(', ')}]" end end end algebrick-0.7.4/lib/algebrick/product_variant.rb0000644000004100000410000001330613040707711021722 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # Representation of Product and Variant types. The class behaves differently # based on #kind. #noinspection RubyTooManyMethodsInspection class ProductVariant < Type # TODO split up into classes or modules # TODO aliases for fields, (update matchers) include FieldMethodReaders attr_reader :fields, :variants def initialize(name, &definition) super(name, &definition) @to_be_kind_of = [] @final_variants = false end def set_fields(fields_or_hash) raise TypeError, 'can be set only once' if @fields @kind = nil fields, keys = case fields_or_hash when Hash [fields_or_hash.values, fields_or_hash.keys] when Array [fields_or_hash, nil] else raise ArgumentError end add_field_names keys if keys fields.all? { |f| Type! f, Type, Class, Module } raise TypeError, 'there is no product with zero fields' unless fields.size > 0 define_method(:value) { @fields.first } if fields.size == 1 @fields = fields @constructor = Class.new( field_names? ? ProductConstructors::Named : ProductConstructors::Basic). tap { |c| c.type = self } const_set :Constructor, @constructor apply_be_kind_of self end def field_indexes @field_indexes or raise TypeError, "field names not defined on #{self}" end def field(name) fields[field_indexes[name]] end def final! @final_variants = true self end def set_variants(*variants) raise TypeError, 'can be set only once' if @variants && @final_variants @kind = nil variants.all? { |v| Type! v, Type, Class } @variants ||= [] @variants += variants apply_be_kind_of variants.each do |v| if v.respond_to? :be_kind_of v.be_kind_of self else v.send :include, self end end self end def new(*fields) raise TypeError, "#{self} does not have fields" unless @constructor @constructor.new *fields end alias_method :[], :new def ==(other) other.kind_of? ProductVariant and variants == other.variants and fields == other.fields end def be_kind_of(type) @to_be_kind_of << type apply_be_kind_of end def apply_be_kind_of @to_be_kind_of.each do |type| @constructor.send :include, type if @constructor variants.each { |v| v.be_kind_of type if v != self && v.respond_to?(:be_kind_of) } if @variants end end def call(*field_matchers) raise TypeError, "#{self} does not have any fields" unless @fields Matchers::Product.new self, *field_matchers end def to_m case kind when :product Matchers::Product.new self when :product_variant Matchers::Variant.new self when :variant Matchers::Variant.new self else raise end end def to_s case kind when :product product_to_s when :product_variant name + '(' + variants.map do |variant| if variant == self product_to_s else sub_type variant end end.join(' | ') + ')' when :variant "#{name}(#{variants.map { |v| sub_type v }.join ' | '})" else raise end end #noinspection RubyCaseWithoutElseBlockInspection def kind @kind ||= case when @fields && !@variants :product when @fields && @variants :product_variant when !@fields && @variants :variant when !@fields && !@variants raise TypeError, 'fields or variants have to be set' end end def assigned_types @assigned_types or raise TypeError, "#{self} does not have assigned types" end def assigned_types=(assigned_types) raise TypeError, "#{self} assigned types already set" if @assigned_types @assigned_types = assigned_types end private def product_to_s fields_str = if field_names? field_names.zip(fields).map { |name, field| "#{name}: #{field.name}" } else fields.map(&:name) end "#{name}(#{fields_str.join ', '})" end def sub_type(type) return type.name unless type.name.nil? return '(recursive)' if type == self # FIXME: will not catch deeper recursions return type.to_s end def add_field_names(names) @field_names = names names.all? { |k| Type! k, Symbol } dict = @field_indexes = Hash.new { |_, k| raise ArgumentError, "unknown field #{k.inspect} in #{self}" }. update names.each_with_index.inject({}) { |h, (k, i)| h.update k => i } define_method(:[]) { |key| @fields[dict[key]] } # TODO use attr_readers to speed things up end end end algebrick-0.7.4/lib/algebrick/matchers.rb0000644000004100000410000000215313040707711020322 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers require 'algebrick/matchers/abstract' require 'algebrick/matchers/abstract_logic' require 'algebrick/matchers/and' require 'algebrick/matchers/or' require 'algebrick/matchers/not' require 'algebrick/matchers/any' require 'algebrick/matchers/many' require 'algebrick/matchers/wrapper' require 'algebrick/matchers/array' require 'algebrick/matchers/product' require 'algebrick/matchers/variant' require 'algebrick/matchers/atom' end end algebrick-0.7.4/lib/algebrick/type_check.rb0000644000004100000410000000307113040707711020632 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick #noinspection RubyInstanceMethodNamingConvention module TypeCheck # FIND: type checking of collections? def Type?(value, *types) types.any? { |t| value.is_a? t } end def Type!(value, *types) Type?(value, *types) or TypeCheck.error(value, 'is not', types) value end def Match?(value, *types) types.any? { |t| t === value } end def Match!(value, *types) Match?(value, *types) or TypeCheck.error(value, 'is not matching', types) value end def Child?(value, *types) Type?(value, Class) && types.any? { |t| value <= t } end def Child!(value, *types) Child?(value, *types) or TypeCheck.error(value, 'is not child', types) value end private def self.error(value, message, types) raise TypeError, "Value (#{value.class}) '#{value}' #{message} any of: #{types.join('; ')}." end end end algebrick-0.7.4/lib/algebrick/product_constructors/0000755000004100000410000000000013040707711022476 5ustar www-datawww-dataalgebrick-0.7.4/lib/algebrick/product_constructors/named.rb0000644000004100000410000000313613040707711024112 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module ProductConstructors class Named < Abstract def to_s "#{self.class.type.name}[" + type.field_names.map { |name| "#{name}: #{self[name].to_s}" }.join(', ') +']' end def pretty_print(q) q.group(1, "#{self.class.type.name}[", ']') do type.field_names.each_with_index do |name, i| if i == 0 q.breakable '' else q.text ',' q.breakable ' ' end q.text name.to_s q.text ':' q.group(1) do q.breakable ' ' q.pp self[name] end end end end def to_hash type.field_names.inject({}) { |h, name| h.update name => self[name] } end alias_method :to_h, :to_hash def self.type=(type) super(type) raise unless type.field_names? end def update(fields) type[to_hash.merge fields] end end end end algebrick-0.7.4/lib/algebrick/product_constructors/basic.rb0000644000004100000410000000241013040707711024101 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module ProductConstructors class Basic < Abstract def to_s "#{self.class.type.name}[" + fields.map(&:to_s).join(', ') + ']' end def pretty_print(q) q.group(1, "#{self.class.type.name}[", ']') do fields.each_with_index do |value, i| if i == 0 q.breakable '' else q.text ',' q.breakable ' ' end q.pp value end end end def self.type=(type) super(type) raise if type.field_names? end def update(fields) type[*fields] end end end end algebrick-0.7.4/lib/algebrick/product_constructors/abstract.rb0000644000004100000410000000331013040707711024623 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module ProductConstructors class Abstract include Value extend TypeCheck attr_reader :fields def initialize(*fields) if fields.size == 1 && fields.first.is_a?(Hash) fields = type.field_names.map { |k| fields.first[k] } end @fields = fields.zip(self.class.type.fields).map { |field, type| Type! field, type }.freeze end def to_ary @fields end def to_a @fields end def ==(other) return false unless other.kind_of? self.class @fields == other.fields end alias_method :eql?, :== def hash [self.class, @fields].hash end def self.type @type || raise end def type self.class.type end def self.name @type.to_s end def self.to_s name end def self.type=(type) Type! type, ProductVariant raise if @type @type = type include type end def update(*fields) raise NotImplementedError end end end end algebrick-0.7.4/lib/algebrick/value.rb0000644000004100000410000000176313040707711017636 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # Any value of Algebraic type is kind of Value module Value include TypeCheck include Matching def ==(other) raise NotImplementedError end def type raise NotImplementedError end def to_s raise NotImplementedError end def pretty_print(q) raise NotImplementedError end def inspect to_s end end end algebrick-0.7.4/lib/algebrick/types.rb0000644000004100000410000000324013040707711017656 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick #noinspection RubyConstantNamingConvention module Types Maybe = Algebrick.type(:v) do variants None = atom, Some = type(:v) { fields :v } end module Maybe def maybe match self, on(None, nil), on(Some) { yield value } end end Boolean = Algebrick.type do variants TrueClass, FalseClass end List = Algebrick.type(:value_type) do |list| fields! value: :value_type, next: list variants EmptyList = atom, list end module List include Enumerable def each(&block) return to_enum unless block_given? it = self loop do break if EmptyList === it block.call it.value it = it.next end self end def next? self.next != EmptyList end def empty? !next? end def self.build(type, *items) items.reverse_each.reduce(EmptyList) { |list, item| self[type][item, list] } end end end include Types end algebrick-0.7.4/lib/algebrick/matching.rb0000644000004100000410000000357513040707711020317 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # include this module anywhere yoy need to use pattern matching module Matching def any Matchers::Any.new end def match(value, *cases) success, result = match? value, *cases raise "no match for (#{value.class}) '#{value}' by any of #{cases.map(&:first).join ', '}" unless success result end def match?(value, *cases) cases = if cases.size == 1 && cases.first.is_a?(Hash) cases.first else cases end cases.each do |matcher, block| return true, Matching.match_value(matcher, block) if matcher === value end [false, nil] end def on(matcher, value = nil, &block) matcher = if matcher.is_a? Matchers::Abstract matcher else matcher.to_m end raise ArgumentError, 'only one of block or value can be supplied' if block && value [matcher, value || block] end private def self.match_value(matcher, block) if block.kind_of? Proc if matcher.kind_of? Matchers::Abstract matcher.assigns &block else block.call end else block end end end include Matching extend Matching end algebrick-0.7.4/lib/algebrick/field_method_readers.rb0000644000004100000410000000254213040707711022646 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module FieldMethodReaders def field_names @field_names or raise TypeError, "field names not defined on #{self}" end def field_names? !!@field_names end def add_field_method_reader(field) raise TypeError, 'no field names' unless field_names? raise ArgumentError, "no field name #{field}" unless field_names.include? field raise ArgumentError, "method #{field} already defined" if instance_methods.include? field define_method(field) { self[field] } self end def add_field_method_readers(*fields) fields.each { |f| add_field_method_reader f } self end def add_all_field_method_readers add_field_method_readers *field_names self end end end algebrick-0.7.4/lib/algebrick/product_constructors.rb0000644000004100000410000000155713040707711023033 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # A private classes used for Product values creation module ProductConstructors require 'algebrick/product_constructors/abstract' require 'algebrick/product_constructors/basic' require 'algebrick/product_constructors/named' end end algebrick-0.7.4/lib/algebrick/atom.rb0000644000004100000410000000207513040707711017457 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # Representation of Atomic types class Atom < Type include Value def initialize(name, &block) super name, &block extend self end def to_m Matchers::Atom.new self end def be_kind_of(type) extend type end def ==(other) self.equal? other end def type self end def to_s name || 'nameless-atom' end def pretty_print(q) q.text to_s end end end algebrick-0.7.4/lib/algebrick/matchers/0000755000004100000410000000000013040707711017774 5ustar www-datawww-dataalgebrick-0.7.4/lib/algebrick/matchers/variant.rb0000644000004100000410000000164713040707711021775 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Variant < Wrapper def initialize(something) raise ArgumentError unless something.variants Type! something, Algebrick::ProductVariant super something end def to_s assign_to_s + "#{@something.name}.to_m" end end end end algebrick-0.7.4/lib/algebrick/matchers/product.rb0000644000004100000410000000523413040707711022005 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Product < Abstract attr_reader :algebraic_type, :field_matchers def initialize(algebraic_type, *field_matchers) super() @algebraic_type = Type! algebraic_type, Algebrick::ProductVariant, Algebrick::ParametrizedType raise ArgumentError unless algebraic_type.fields @field_matchers = case # AProduct.() when field_matchers.empty? ::Array.new(algebraic_type.fields.size) { Algebrick.any } # AProduct.(field_name: a_matcher) when field_matchers.size == 1 && field_matchers.first.is_a?(Hash) field_matchers = field_matchers.first unless (dif = field_matchers.keys - algebraic_type.field_names).empty? raise ArgumentError, "no #{dif} fields in #{algebraic_type}" end algebraic_type.field_names.map do |field| field_matchers.key?(field) ? field_matchers[field] : Algebrick.any end # normal else field_matchers end unless algebraic_type.fields.size == @field_matchers.size raise ArgumentError end end def children find_children @field_matchers end def to_s assign_to_s + "#{@algebraic_type.name}.(#{@field_matchers.join(', ')})" end def ==(other) other.kind_of? self.class and self.algebraic_type == other.algebraic_type and self.field_matchers == other.field_matchers end protected def matching?(other) other.kind_of?(@algebraic_type) and other.kind_of?(ProductConstructors::Abstract) and @field_matchers.zip(other.fields).all? do |matcher, field| matcher === field end end end end end algebrick-0.7.4/lib/algebrick/matchers/wrapper.rb0000644000004100000410000000262013040707711022001 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers # wraps any object having #=== method into matcher class Wrapper < Abstract def self.call(something) new something end attr_reader :something def initialize(something) super() @something = matchable! something end def children find_children [@something] end def to_s assign_to_s + "Wrapper.(#{@something})" end def ==(other) other.kind_of? self.class and self.something == other.something end protected def matching?(other) @something === other end end # allow to convert any object to matcher if it has #=== method class ::Object def to_m Wrapper.new(self) end end end end algebrick-0.7.4/lib/algebrick/matchers/atom.rb0000644000004100000410000000154413040707711021265 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Atom < Wrapper def initialize(something) Type! something, Algebrick::Atom super something end def to_s assign_to_s + "#{@something.name}.to_m" end end end end algebrick-0.7.4/lib/algebrick/matchers/abstract_logic.rb0000644000004100000410000000204513040707711023302 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class AbstractLogic < Abstract def self.call(*matchers) new *matchers end attr_reader :matchers def initialize(*matchers) @matchers = matchers.each { |m| matchable! m } end def children find_children matchers end def ==(other) other.kind_of? self.class and self.matchers == other.matchers end end end end algebrick-0.7.4/lib/algebrick/matchers/array.rb0000644000004100000410000000336613040707711021447 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Array < Abstract def self.call(*matchers) new *matchers end attr_reader :matchers def initialize(*matchers) super() @matchers = matchers raise ArgumentError, 'many can be only last' if @matchers[0..-2].any? { |v| v.is_a?(Many) } end def children find_children @matchers end def to_s "#{assign_to_s}#{"Array.(#{matchers.join(',')})" if matchers}" end def ==(other) other.kind_of? self.class and self.matchers == other.matchers end def rest? matchers.last.is_a?(Many) end protected def matching?(other) return false unless other.kind_of? ::Array if rest? matchers[0..-2].zip(other).all? { |m, v| m === v } and matchers.last === other[(matchers.size-1)..-1] else matchers.size == other.size and matchers.zip(other).all? { |m, v| m === v } end end end class ::Array def self.call(*matchers) Matchers::Array.new *matchers end end end end algebrick-0.7.4/lib/algebrick/matchers/many.rb0000644000004100000410000000162413040707711021270 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Many < Abstract def children [] end def to_s "*#{assign_to_s}any" end def ==(other) other.kind_of? self.class end protected def matching?(other) true end end end end algebrick-0.7.4/lib/algebrick/matchers/and.rb0000644000004100000410000000151213040707711021062 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class And < AbstractLogic def to_s matchers.join ' & ' end protected def matching?(other) matchers.all? { |m| m === other } end end end end algebrick-0.7.4/lib/algebrick/matchers/any.rb0000644000004100000410000000211213040707711021104 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Any < Abstract def children [] end def to_s assign_to_s + 'any' end def ==(other) other.kind_of? self.class end # transforms *any to many def to_a if assigned? super else [Matchers::Many.new.tap { |m| m.assign! if assign? }] end end protected def matching?(other) true end end end end algebrick-0.7.4/lib/algebrick/matchers/not.rb0000644000004100000410000000206013040707711021117 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Not < Abstract attr_reader :matcher def initialize(matcher) @matcher = matcher end def children [] end def to_s '!' + matcher.to_s end def ==(other) other.kind_of? self.class and self.matcher == other.matcher end protected def matching?(other) not matcher === other end end end end algebrick-0.7.4/lib/algebrick/matchers/abstract.rb0000644000004100000410000000507613040707711022134 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers class Abstract include TypeCheck attr_reader :value def initialize @assign, @value, @matched = nil end def case(&block) return self, block end alias_method :when, :case def >(block) return self, block end alias_method :>>, :> def assign! @assign = true self end alias_method :~, :assign! def &(matcher) And.new self, matcher end def |(matcher) Or.new self, matcher end def ! Not.new self end def assign? @assign end def assigned? !!@value end def matched? @matched end def children_including_self children.unshift self end def assigns assigns = collect_assigns return yield *assigns if block_given? assigns end def to_a assigns end def ===(other) matching?(other).tap { |matched| @value = other if (@matched = matched) } end def assign_to_s assign? ? '~' : '' end def inspect to_s end def children raise NotImplementedError end def to_s raise NotImplementedError end def ==(other) raise NotImplementedError end # TODO pretty_print for all matchers protected def matching?(other) raise NotImplementedError end private def collect_assigns mine = @assign ? [@value] : [] children.inject(mine) { |assigns, child| assigns + child.assigns } end def matchable!(obj) raise ArgumentError, 'object does not respond to :===' unless obj.respond_to? :=== obj end def find_children(collection) collection.map do |matcher| matcher if matcher.kind_of? Abstract end.compact end end end end algebrick-0.7.4/lib/algebrick/matchers/or.rb0000644000004100000410000000247513040707711020751 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module Matchers #noinspection RubyClassModuleNamingConvention class Or < AbstractLogic def to_s matchers.join ' | ' end protected def matching?(other) matchers.any? { |m| m === other } end alias_method :super_children, :children private :super_children def children super.select &:matched? end private def collect_assigns super.tap do |assigns| missing = assigns_size - assigns.size assigns.push(*::Array.new(missing)) end end def assigns_size # TODO is it efficient? super_children.map { |ch| ch.assigns.size }.max end end end end algebrick-0.7.4/lib/algebrick/serializer.rb0000644000004100000410000000711313040707711020666 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick class Serializer include TypeCheck TYPE_KEY = :algebrick_type FIELD_KEY = :algebrick_fields def load(data, options = {}) case data when ::Hash parse_value(data, options) when Numeric, String, ::Array, Symbol, TrueClass, FalseClass, NilClass data else parse_other(data, options) end end def dump(object, options = {}) case object when Value generate_value object, options when Numeric, String, ::Array, ::Hash, Symbol, TrueClass, FalseClass, NilClass object else generate_other(object, options) end end def constantize(camel_cased_word) names = camel_cased_word.split('::') names.shift if names.empty? || names.first.empty? parameter = nil names.last.tap do |last| name, parameter = last.split /\[|\]/ last.replace name end constant = Object names.each do |name| constant = if constant.const_defined?(name) constant.const_get(name) else constant.const_missing(name) end end constant = constant[constantize(parameter)] if parameter constant end protected def parse_other(other, options = {}) other end def generate_other(object, options = {}) case when object.respond_to?(:to_h) object.to_h when object.respond_to?(:to_hash) object.to_hash else raise "do not know how to convert (#{object.class}) #{object}" end end private def parse_value(value, options) type_name = value[TYPE_KEY] || value[TYPE_KEY.to_s] if type_name type = constantize(type_name) fields = value[FIELD_KEY] || value[FIELD_KEY.to_s] || value.dup.tap { |h| h.delete TYPE_KEY; h.delete TYPE_KEY.to_s } Type! fields, Hash, Array if type.is_a? Atom type else case fields when Array type[*fields.map { |value| load value, options }] when Hash type[fields.inject({}) do |h, (name, value)| raise ArgumentError unless type.field_names.map(&:to_s).include? name.to_s h.update name.to_sym => load(value, options) end] end end else parse_other value, options end end def generate_value(value, options) { TYPE_KEY => value.type.name }. update(case value when Atom {} when ProductConstructors::Basic { FIELD_KEY => value.fields.map { |v| dump v, options } } when ProductConstructors::Named value.type.field_names.inject({}) do |h, name| h.update name => dump(value[name], options) end else raise end) end end end algebrick-0.7.4/lib/algebrick/matcher_delegations.rb0000644000004100000410000000170013040707711022512 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module MatcherDelegations def ~ ~to_m end def &(other) to_m & other end def |(other) to_m | other end def ! !to_m end def case(&block) to_m.case &block end def >>(block) to_m >> block end def >(block) to_m > block end end end algebrick-0.7.4/lib/algebrick/reclude.rb0000644000004100000410000000231613040707711020140 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # fix module to re-include itself to where it was already included when a module is included into it #noinspection RubySuperCallWithoutSuperclassInspection module Reclude def included(base) used_by << base super(base) end def extended(base) used_by << base super(base) end def include(*modules) super(*modules) modules.reverse.each do |module_being_included| used_by.each do |mod| mod.send :include, module_being_included end end end private def used_by @used_by ||= [] end end end algebrick-0.7.4/lib/algebrick/type.rb0000644000004100000410000000255513040707711017503 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick # Any Algebraic type defined by Algebrick is kind of Type class Type < Module include TypeCheck include Matching include MatcherDelegations include Reclude def initialize(name, &definition) super &definition @name = name end def name super || @name || nil end def to_m(*args) raise NotImplementedError end def ==(other) raise NotImplementedError end def be_kind_of(type) raise NotImplementedError end def to_s raise NotImplementedError end def inspect to_s end def match(value, *cases) Type! value, self super value, *cases end #def pretty_print(q) TODO # raise NotImplementedError #end end end algebrick-0.7.4/lib/algebrick/dsl.rb0000644000004100000410000000455713040707711017310 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Algebrick module DSL module Shortcuts def type(*variables, &block) Algebrick.type *variables, &block end def atom Algebrick.atom end end class TypeDefinitionScope include Shortcuts include TypeCheck attr_reader :new_type def initialize(new_type, &block) @new_type = Type! new_type, ProductVariant, ParametrizedType instance_exec @new_type, &block @new_type.kind if @new_type.is_a? ProductVariant end def fields(*fields) @new_type.set_fields fields.first.is_a?(Hash) ? fields.first : fields self end def fields!(*fields) fields(*fields) all_readers end def final! @new_type.final! self end def variants(*variants) @new_type.set_variants *variants self end def field_readers(*names) @new_type.add_field_method_readers *names self end alias_method :readers, :field_readers def all_field_readers @new_type.add_all_field_method_readers self end alias_method :all_readers, :all_field_readers end class OuterShell include Shortcuts def initialize(&block) instance_eval &block end end end def self.type(*variables, &block) if block.nil? raise 'Atom cannot be parametrized' unless variables.empty? atom else if variables.empty? DSL::TypeDefinitionScope.new(ProductVariant.new(nil), &block).new_type else DSL::TypeDefinitionScope.new(ParametrizedType.new(variables), &block).new_type end end end def self.atom Atom.new nil end def self.types(&block) DSL::OuterShell.new &block end end algebrick-0.7.4/lib/algebrick.rb0000644000004100000410000000403313040707711016513 0ustar www-datawww-data# Copyright 2013 Petr Chalupa # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # TODO method definition in variant type defines methods on variants based on match, better performance? # TODO add matcher/s for Hash # TODO add method matcher (:size, matcher) # TODO Menu modeling example, add TypedArray # TODO update actor pattern example when gem is done # TODO gemmify reclude # TODO gemmify typecheck # TODO add default field values # Person = Algebrick.type do # fields! age: Integer, # address: [Maybe[String], None]#, # # address: Maybe[String] >> None # # field! :age, Integer # field! :address, Maybe[String], None # end # Person[1] # Person[1, Some['Praha']] # TODO use benevolent deserializer to allow: # Person[address: Address[name: 'asd']] # Person[address: { name: 'asd' }] # Provides Algebraic types and pattern matching # # **Quick example** # {include:file:doc/quick_example.out.rb} module Algebrick def self.version @version ||= Gem::Version.new File.read(File.join(File.dirname(__FILE__), '..', 'VERSION')) end require 'algebrick/reclude' require 'algebrick/type_check' require 'algebrick/matching' require 'algebrick/matcher_delegations' require 'algebrick/type' require 'algebrick/value' require 'algebrick/atom' require 'algebrick/product_constructors' require 'algebrick/field_method_readers' require 'algebrick/product_variant' require 'algebrick/parametrized_type' require 'algebrick/dsl' require 'algebrick/matchers' require 'algebrick/types' end algebrick-0.7.4/VERSION0000644000004100000410000000000613040707711014541 0ustar www-datawww-data0.7.4 algebrick-0.7.4/README.md0000644000004100000410000000341313040707711014755 0ustar www-datawww-data# Algebrick [![Build Status](https://travis-ci.org/pitr-ch/algebrick.png?branch=master)](https://travis-ci.org/pitr-ch/algebrick) Typed structs on steroids based on algebraic types and pattern matching seamlessly integrating with standard Ruby features. - Documentation: - Source: - Blog: ## What is it good for? - Well defined data structures. - Actor messages see [new Actor implementation](http://rubydoc.info/gems/concurrent-ruby/Concurrent/Actress) in [concurrent-ruby](concurrent-ruby.com). - Describing message protocols in message-based cross-process communication. Algebraic types play nice with JSON de/serialization. - and more... ## Quick example Let's define a Tree ```ruby 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. Let's add a method, don't miss the **pattern matching** example. ```ruby module Tree # compute depth of a tree def depth match self, (on Empty, 0), (on Leaf, 1), # ~ will store and pass matched parts to variables left and right (on Node.(~any, ~any) do |left, right| 1 + [left.depth, right.depth].max end) end end ``` Method defined in module `Tree` are passed down to **all** values of type Tree ```ruby Empty.depth # => 0 Leaf[10].depth # => 1 Node[Leaf[4], Empty].depth # => 2 Node[Empty, Node[Leaf[1], Empty]].depth # => 3 ```