noaidi 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 616599ed29b3b649e96e11e287fe697930b16cd6
4
+ data.tar.gz: ca3cd45631602312e0928079f75098b734c1b91c
5
+ SHA512:
6
+ metadata.gz: d4974660037e467062b5200c645ff7a8365b28c4828611afe15628a8805db70bfc13d46a8bc7f78f637229fbb08c8d5b8b12cf0dc9abee6ec57fd748932f9f50
7
+ data.tar.gz: 5c8ef7539e37911f5d85c8177eb28c50a51bf94f2ed27d75e4a8da0f88ca7912aafa472de2131e1e3d3f8fc7dea09d30f29c15201e2b30b72e3f77bdb6008dc2
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.2
4
+ before_install: gem install bundler -v 1.10.6
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in noaidi.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Paweł Świątkowski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,147 @@
1
+ # Noaidi
2
+
3
+ This is a proof-of-concept gem for creating focused modules with pattern matching support. At its root it was inspired by how Erlang does it, but later was refined using concepts from Elixir language.
4
+
5
+ Noaidi is a Saami name for a shaman. According to Wikipedia:
6
+
7
+ > A noaidi was a mediator between the human world and _saivo_, the underworld, for the least of community problems.
8
+
9
+ So, this Noaidi is a mediator between the functional world and Ruby world (which of those is _saivo_, I leave it to you).
10
+
11
+ There are some blog posts about it:
12
+ * [A quest for pattern-matching in Ruby](http://katafrakt.me/2016/02/13/quest-for-pattern-matching-in-ruby/) (now obsolete, but still tells some things about motivation)
13
+ * [Refactoring Rails with pattern-matching (Noaidi)](http://katafrakt.me/2016/05/24/refactoring-rails-with-noaidi/)
14
+
15
+ ## Usage
16
+
17
+ A basic unit of this library is a module. Module should define some functions (called `fun`s) and be responsible for some part of the domain. A classic example is a naive recursive Fibonacci implementation. Here's how it looks with `Noaidi`:
18
+
19
+ ```ruby
20
+ require 'noaidi'
21
+
22
+ naive = Noaidi.module do
23
+ fun :fib, [0] { 0 }
24
+ fun :fib, [1] { 1 }
25
+ fun :fib, [Integer] do |n|
26
+ fib(n - 1) + fib(n - 2)
27
+ end
28
+ end
29
+
30
+ puts naive.fib(5)
31
+ puts naive.fib(15)
32
+ ```
33
+
34
+ As you see, the core concept is a `fun`. You create is using DSL inside a block passed to `Noaidi.module`. First parameter is a fun name, second is array of arguments pattern. It is followed by a block. Of course, you can reference `fun`s from the same module in other funs. If you call for example `fib(1)`, the first fun where arguments pattern matches the actual arguments is called (and in this case will return `1`).
35
+
36
+ ### Pattern matching
37
+
38
+ You can leverage pattern matching in Noaidi with some choices. That basic match will use `===` operator (like `case`). This way, except for exact values, you can match on:
39
+
40
+ * Classes – to indicate that the argument has to be an instance of this class or its subclass
41
+ * Values – so that the argument has to be exactly the same
42
+ * Ranges – to have the argument included in the boundaries of a range
43
+
44
+ There are also some special patterns, that are handled differently:
45
+
46
+ **Hashes**: You can pass `{ status: :ok }` as a pattern at it will match all hashes that include value `100` under `:status` key. It does not matter what the rest of the keys are. As a values you can also use other pattern, i.e. `{ response: 500..599, headers: { language: 'fi' } }` will match all hashes with response between 500 and 599 and also having a `:headers` key, containing a hash having `'fi'` under `:language` key.
47
+
48
+ **Lambdas** provide basic guard possibilities. If the lambda evaluates to `true`, it is a match. For example:
49
+
50
+ ```ruby
51
+ Stat = Noaidi.module do
52
+ # Assuming array is already sorted
53
+
54
+ fun :median, [->(array) { array.is_a?(Array) && array.length.even? }] do
55
+ half = array.length/2
56
+ (array[half] + array[half - 1]) / 2.0
57
+ end
58
+
59
+ fun :median, [Array] { array[array.length/2] }
60
+ end
61
+ ```
62
+
63
+ You can use `any` keyword if you don't want to specify constraint on the argument:
64
+
65
+ ```ruby
66
+ fun :whatever, [any, Integer] { |a, i| a.to_s * i }
67
+ ```
68
+
69
+ ### Argument relevance
70
+
71
+ ```ruby
72
+ Noaidi.match open_file(path) do |m|
73
+ m.(:ok, File) {|file| process_file(file) },
74
+ m.(:error, Exception) {|ex| handle_file_opening_exception(path, ex) }
75
+ end
76
+ ```
77
+
78
+ If you look at the example above, you'll notice that even though the pattern consists of two elements, only one is passed to execution block. This is because of relevance checker. If you match against `:ok, File` you will always have `:ok` as the first argument, and therefore there's no point in passing it to the block.
79
+
80
+ The rule here is that if you match by value (usually symbols, strings, numbers), the pattern is irrelevant. In every other case, it is relevant and passed to the block.
81
+
82
+ ### Immutability
83
+
84
+ It's not easy to enforce immutability in language like Ruby and I won't try too hard to do it. However, `fun`s are frozen, which means that you can change it after it has been moduled. It also means that **you can't use instance variables** in `fun`s (that's intentional, as using them could possibly yield unexpected results). Of course, I bet there are some trick with which you can overcome this, but having to use them should discourage you enough.
85
+
86
+ ### Default arguments
87
+
88
+ Default arguments for `fun`s are not supported and won't be supported. This is by design. If you want to have default arguments, use constructs known in other languages, i.e.
89
+
90
+ ```ruby
91
+ fun :mult, [Integer, Integer] {|x,y| x*y }
92
+ fun :mult, [Integer] {|x| mult(x, 1) }
93
+ ```
94
+
95
+ ### Using pattern matching outside modules
96
+
97
+ Sometimes you don want to write a module to use pattern matching. In those cases, use `Noaidi.match`.
98
+
99
+ ```ruby
100
+ Noaidi.match save_post(@post) do |m|
101
+ m.(:ok, Post) {|post| redirect_to post, notice: 'Post successfully created' },
102
+ m.(:invalid, any) {|_validation_errors| render :new },
103
+ m.(:error, StandardError) {|error| render :error_500, error: error }
104
+ end
105
+ ```
106
+
107
+ If you care for performance, treat this pattern matching as RegEx, where initialization is a most expensive part. With that in mind, you can "compile" the match beforehand and only call subsequent values on compiled version. Use `Noaidi.compile_match` just like with an example above. The returned value will be a compiled matcher.
108
+
109
+ ```ruby
110
+ matcher = Noaidi.compile_match do |m|
111
+ ...
112
+ end
113
+
114
+ matcher.(value)
115
+ ```
116
+
117
+ The benchmark comparing those two approaches on my laptop gives following results:
118
+
119
+ ```
120
+ Rehearsal ----------------------------------------------------------------
121
+ 100000 times without compile 1.190000 0.000000 1.190000 ( 1.191833)
122
+ 100000 times with compile 0.380000 0.000000 0.380000 ( 0.388147)
123
+ ------------------------------------------------------- total: 1.570000sec
124
+
125
+ user system total real
126
+ 100000 times without compile 1.190000 0.000000 1.190000 ( 1.184098)
127
+ 100000 times with compile 0.390000 0.000000 0.390000 ( 0.386056)
128
+ ```
129
+
130
+ ## Roadmap
131
+
132
+ Things I want to implement in the future:
133
+
134
+ * Private funs in module
135
+ * `_` operator that matches argument as irrelevant and does not pass it to execution block
136
+
137
+ ## Testing
138
+
139
+ Run `rake spec`.
140
+
141
+ ## Contributing
142
+
143
+ Bug reports and pull requests are welcome on GitHub at https://github.com/katafrakt/noaidi.
144
+
145
+ ## License
146
+
147
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
@@ -0,0 +1,11 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
7
+
8
+ task :benchmark do
9
+ require_relative 'benchmark/benchmark'
10
+ NoaidiBenchmark.run
11
+ end
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "noaidi"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,15 @@
1
+ require "noaidi/version"
2
+ require "noaidi/dsl"
3
+ require "noaidi/module"
4
+ require "noaidi/fun"
5
+ require "noaidi/matcher"
6
+ require "noaidi/matchmaker"
7
+ require "noaidi/idioms/match"
8
+
9
+ module Noaidi
10
+ def self.module(&block)
11
+ Noaidi::Module.new.tap do |mod|
12
+ mod.instance_eval(&block)
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,7 @@
1
+ module Noaidi
2
+ module DSL
3
+ def any
4
+ BasicObject
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,38 @@
1
+ module Noaidi
2
+ ReturnContractViolation = Class.new(StandardError)
3
+
4
+ class Fun
5
+ def initialize(noaidi, name, args, block)
6
+ @module = noaidi
7
+ @name = name
8
+ @args = args.map{|a| Matcher.new(a)}
9
+ @block = block
10
+ end
11
+
12
+ def call(*args)
13
+ freeze unless frozen?
14
+ instance_exec(*args, &@block)
15
+ end
16
+
17
+ def matches?(args)
18
+ return false unless arity == args.length
19
+ args.each_with_index do |arg, i|
20
+ return false unless @args[i].match?(arg)
21
+ end
22
+ true
23
+ end
24
+
25
+ def method_missing(name, *args)
26
+ @module.public_send(name, *args)
27
+ end
28
+
29
+ private
30
+ def arity
31
+ @args.length
32
+ end
33
+
34
+ def arguments
35
+ @args
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,9 @@
1
+ module Noaidi
2
+ module Idioms
3
+ module Match
4
+ def match(*args, &block)
5
+ Noaidi.match(*args, &block)
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,37 @@
1
+ module Noaidi
2
+ class Matcher
3
+ def initialize(pattern)
4
+ @pattern = pattern
5
+ end
6
+
7
+ def match?(value)
8
+ case @pattern
9
+ when Proc
10
+ match_with_lambda(value)
11
+ when Hash
12
+ match_with_hash(value)
13
+ else
14
+ @pattern === value
15
+ end
16
+ end
17
+
18
+ def pattern_class
19
+ @pattern.class
20
+ end
21
+
22
+ private
23
+
24
+ # TODO: compile it at construction time
25
+ def match_with_hash(value)
26
+ return false unless value.is_a?(Hash)
27
+
28
+ @pattern.map do |key, val|
29
+ Matcher.new(val).match?(value[key])
30
+ end.all?{ |x| x == true }
31
+ end
32
+
33
+ def match_with_lambda(value)
34
+ @pattern.call(value)
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,56 @@
1
+ module Noaidi
2
+ def self.match(value, &block)
3
+ compile_match(&block).call(value)
4
+ end
5
+
6
+ def self.compile_match(&block)
7
+ Matchmaker.new(block)
8
+ end
9
+
10
+ class Matchmaker
11
+ NoMatchError = Class.new(StandardError)
12
+
13
+ def initialize(block)
14
+ @branches = process_block(block)
15
+ end
16
+
17
+ def call(value)
18
+ values = Array(value)
19
+ @branches.each do |matchers, block|
20
+ return block.call(*meaningful_values(matchers, values)) if matches?(matchers, values)
21
+ end
22
+ raise NoMatchError, "No match for #{@values.inspect}"
23
+ end
24
+
25
+ private
26
+ def process_block(block)
27
+ block.call(Parser.new)
28
+ end
29
+
30
+ def meaningful_values(matchers, values)
31
+ values.zip(matchers).select do |i|
32
+ value = i[0]
33
+ matcher = i[1]
34
+ !matcher.nil? && (matcher.pattern_class == Class || value.class != matcher.pattern_class)
35
+ end.map{|i| i[0]}
36
+ end
37
+
38
+ def matches?(matchers, values)
39
+ return false unless values.length == matchers.length
40
+ values.each_with_index do |value, i|
41
+ return false unless matchers[i].match?(value)
42
+ end
43
+ true
44
+ end
45
+
46
+ class Parser
47
+ def call(*args, &block)
48
+ @branches ||= {}
49
+ key = args.map{ |i| Noaidi::Matcher.new(i) }
50
+ @branches[key] = block
51
+ @branches
52
+ end
53
+ end
54
+ private_constant :Parser
55
+ end
56
+ end
@@ -0,0 +1,33 @@
1
+ module Noaidi
2
+ NoBlockGiven = Class.new(StandardError)
3
+
4
+ class Module
5
+ include Noaidi::DSL
6
+
7
+ def initialize
8
+ @funs = {}
9
+ end
10
+
11
+ def fun(name, args=[], &block)
12
+ raise NoBlockGiven unless block_given?
13
+ name = name.to_sym
14
+ f = Fun.new(self, name, args, block)
15
+ @funs[name] ||= []
16
+ @funs[name] << f
17
+ f
18
+ end
19
+
20
+ def inspect_funs
21
+ @funs.inspect
22
+ end
23
+
24
+ def method_missing(name, *args)
25
+ find_best_method(name, args).call(*args)
26
+ end
27
+
28
+ private
29
+ def find_best_method(name, args)
30
+ @funs[name].detect { |f| f.matches?(args) }
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,3 @@
1
+ module Noaidi
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'noaidi/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "noaidi"
8
+ spec.version = Noaidi::VERSION
9
+ spec.authors = ["Paweł Świątkowski"]
10
+ spec.email = ["inquebrantable@gmail.com"]
11
+
12
+ spec.summary = %q{Functional shamanism for Ruby}
13
+ spec.description = %q{Functional shamanism for Ruby}
14
+ spec.homepage = "https://github.com/katafrakt/noaidi"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|benchmark)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_development_dependency "bundler", "~> 1.10"
23
+ spec.add_development_dependency "rake", "~> 10.0"
24
+ spec.add_development_dependency "rspec"
25
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: noaidi
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Paweł Świątkowski
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-11-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Functional shamanism for Ruby
56
+ email:
57
+ - inquebrantable@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - Gemfile
66
+ - LICENSE.txt
67
+ - README.md
68
+ - Rakefile
69
+ - bin/console
70
+ - bin/setup
71
+ - lib/noaidi.rb
72
+ - lib/noaidi/dsl.rb
73
+ - lib/noaidi/fun.rb
74
+ - lib/noaidi/idioms/match.rb
75
+ - lib/noaidi/matcher.rb
76
+ - lib/noaidi/matchmaker.rb
77
+ - lib/noaidi/module.rb
78
+ - lib/noaidi/version.rb
79
+ - noaidi.gemspec
80
+ homepage: https://github.com/katafrakt/noaidi
81
+ licenses:
82
+ - MIT
83
+ metadata: {}
84
+ post_install_message:
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '0'
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubyforge_project:
100
+ rubygems_version: 2.5.1
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: Functional shamanism for Ruby
104
+ test_files: []