├── .gitignore ├── Gemfile ├── Gemfile.lock ├── LICENSE ├── README.md ├── lib ├── monadt.rb └── monadt │ ├── adt.rb │ ├── async.rb │ ├── async_either.rb │ ├── do_m.rb │ ├── do_m │ ├── enumerator.rb │ └── fiber.rb │ ├── either.rb │ ├── list.rb │ ├── maybe.rb │ ├── reader.rb │ ├── reader_state_either.rb │ └── state.rb ├── monadt.gemspec └── spec ├── monadt ├── adt_spec.rb ├── monad_async_either_example.rb ├── monad_async_either_spec.rb ├── monad_async_example.rb ├── monad_async_spec.rb ├── monad_either_example.rb ├── monad_either_spec.rb ├── monad_list_example.rb ├── monad_list_spec.rb ├── monad_maybe_example.rb ├── monad_maybe_spec.rb ├── monad_reader_state_either_example.rb ├── monad_reader_state_either_spec.rb ├── monad_state_example.rb └── monad_state_spec.rb ├── spec_helper.rb └── util.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | *.rbc 3 | /.config 4 | /coverage/ 5 | /InstalledFiles 6 | /pkg/ 7 | /spec/reports/ 8 | /spec/examples.txt 9 | /test/tmp/ 10 | /test/version_tmp/ 11 | /tmp/ 12 | 13 | .*.sw* 14 | tags 15 | 16 | ## Specific to RubyMotion: 17 | .dat* 18 | .repl_history 19 | build/ 20 | 21 | ## Documentation cache and generated files: 22 | /.yardoc/ 23 | /_yardoc/ 24 | /doc/ 25 | /rdoc/ 26 | 27 | ## Environment normalization: 28 | /.bundle/ 29 | /vendor/bundle 30 | /lib/bundler/man/ 31 | 32 | # for a library or gem, you might want to ignore these files since the code is 33 | # intended to run in multiple environments; otherwise, check them in: 34 | # Gemfile.lock 35 | # .ruby-version 36 | # .ruby-gemset 37 | 38 | # unless supporting rvm < 1.11.0 or doing something fancy, ignore this: 39 | .rvmrc 40 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem "i18n", "0.7.0" 4 | gem "activesupport-inflector", "0.1.0" 5 | 6 | group :development, :test do 7 | gem 'pry', '0.10.1' 8 | gem 'funkify', '0.0.4' 9 | gem 'rspec', '3.4.0' 10 | end 11 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | activesupport-inflector (0.1.0) 5 | coderay (1.1.0) 6 | diff-lcs (1.2.5) 7 | funkify (0.0.4) 8 | i18n (0.7.0) 9 | method_source (0.8.2) 10 | pry (0.10.1) 11 | coderay (~> 1.1.0) 12 | method_source (~> 0.8.1) 13 | slop (~> 3.4) 14 | rspec (3.4.0) 15 | rspec-core (~> 3.4.0) 16 | rspec-expectations (~> 3.4.0) 17 | rspec-mocks (~> 3.4.0) 18 | rspec-core (3.4.4) 19 | rspec-support (~> 3.4.0) 20 | rspec-expectations (3.4.0) 21 | diff-lcs (>= 1.2.0, < 2.0) 22 | rspec-support (~> 3.4.0) 23 | rspec-mocks (3.4.1) 24 | diff-lcs (>= 1.2.0, < 2.0) 25 | rspec-support (~> 3.4.0) 26 | rspec-support (3.4.1) 27 | slop (3.6.0) 28 | 29 | PLATFORMS 30 | ruby 31 | 32 | DEPENDENCIES 33 | activesupport-inflector (= 0.1.0) 34 | funkify (= 0.0.4) 35 | i18n (= 0.7.0) 36 | pry (= 0.10.1) 37 | rspec (= 3.4.0) 38 | 39 | BUNDLED WITH 40 | 1.11.2 41 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # monadt 2 | Monads & ADTs in Ruby 3 | 4 | ## Overview 5 | Monadt supplies basic ADT and Monad support to Ruby. 6 | 7 | ADTs are defined as Ruby classes and support pattern matching with block callbacks per case. 8 | 9 | Monads are defined using Ruby Enumerators to allow for imperative-like structures similar to the syntactic sugar available in Haskell and F#. The Maybe and Choice monads are defined using the ADT methods in Monadt. 10 | 11 | ## ADTs 12 | 13 | Declare a new ADT with the following syntax: 14 | ```ruby 15 | require 'monadt' 16 | 17 | class MyAdt 18 | FooBar = data :a_number 19 | Baz = data # no assocated values 20 | Else = data :first_data_point, :second_data_point 21 | end 22 | ``` 23 | 24 | Now you can pattern match using Monadt's match() method. 25 | ```ruby 26 | def some_func(my_adt) 27 | match my_adt, 28 | with(MyAdt::FooBar) {|a_number| (a_number * 2).to_s }, 29 | with(MyAdt::Baz) { 'bar bar bar' }, 30 | with(MyAdt::Else) {|first, second| ((first + second) * 3).to_s } 31 | end 32 | ``` 33 | 34 | You can also match against special class Default for matching all values: 35 | ```ruby 36 | def another_func(my_adt) 37 | match my_adt, 38 | with(MyAdt::Else) {|first, second| first ** second }, 39 | with(Default) { 1024 } 40 | end 41 | ``` 42 | 43 | To declare a new value use the class constructor: 44 | ```ruby 45 | MyAdt::FooBar.new 15 46 | ``` 47 | 48 | If you need to access the fields directly rather than with pattern matching, you can use the name associated with the data. For example, 49 | ```ruby 50 | adt_value.a_number 51 | adt_value.second_data_point 52 | ``` 53 | You will trigger a NoMethodError if you call a data field for the wrong case. 54 | 55 | You can optionally add several useful helper functions to your ADT by calling 56 | ```ruby 57 | decorate_adt MyAdt 58 | ``` 59 | 60 | You now have the following methods: 61 | ```ruby 62 | MyAdt.foo_bar 23 # create a new FooBar (equivalent to MyAdt::FooBar.new 23) 63 | MyAdt.baz # makes a new Baz 64 | MyAdt.else 3, 11 65 | 66 | adt_value.is_foo_bar? # boolean check for FooBar case 67 | adt_value.is_baz? 68 | adt_value.is_else? 69 | 70 | adt_value.to_s # sensible defaults like "FooBar(11)", "Baz", "Else(34, 99)" 71 | ``` 72 | 73 | Decorating your ADTs is optional because you may not want all those helpers, and because I'm sure there is some class name transform case I didn't think of that will break everything in certain edge cases. 74 | 75 | ### TODO 76 | 77 | Make it easy to enforce immutability. 78 | 79 | ## Monads 80 | 81 | Monadt uses Ruby Enumerators to support procedural like syntax for monad control flows. Generally you call 82 | ```ruby 83 | Monad. do |m| 84 | # object m has two members, 85 | # * bind, which performs monadic bind for the specified monad 86 | # * return, which performs monadic return for the specified monad 87 | end 88 | ``` 89 | 90 | ### Built-in monads 91 | 92 | * Maybe/Present 93 | * Either 94 | * State 95 | * Reader 96 | * ReaderStateEither 97 | 98 | #### Maybe 99 | 100 | ```ruby 101 | # values 102 | Maybe.just 5 103 | Maybe.nothing 104 | 105 | # example 106 | def maybeFunc(x) 107 | if x > 10 108 | Maybe.nothing 109 | else 110 | Maybe.just (x - 10) 111 | end 112 | end 113 | 114 | def use_maybe(v) 115 | Monad.maybe do |m| 116 | x = m.bind (maybeFunc v) 117 | y = m.bind (maybeFunc (x*2)) 118 | m.return (x + y) 119 | end 120 | end 121 | ``` 122 | 123 | Monadt also includes what I call the "Present" monad. It's just like Maybe except nil is interpreted as Nothing and non-nil values are interpreted as Just value. 124 | 125 | #### Either 126 | 127 | ```ruby 128 | # values 129 | Either.left "something went wrong" 130 | Either.right 15.0 131 | 132 | # ... 133 | def use_either(v) 134 | Monad.either do |m| 135 | x = m.bind (eitherFunc v) 136 | y = m.bind (eitherFunc2 x) 137 | eitherFunc3 (x + y) 138 | end 139 | end 140 | ``` 141 | 142 | #### State 143 | 144 | ```ruby 145 | # state values are two-element arrays 146 | # [value, state] 147 | proc = Monad.state do |m| 148 | x = m.bind (returns_a_proc v) 149 | y = m.bind (returns_a_proc_2 3 x) 150 | m.return (x + y) 151 | end 152 | 153 | value, final_state = proc.call(initial_state) 154 | 155 | # If you want to run the state function and only care about the final output value, use: 156 | Monad.run_state(initial_value) do |m| 157 | # ... 158 | end 159 | ``` 160 | 161 | Note that for the State monad (or any monad whose monadic type is a function), you may find the funkify gem helpful, as it can make Ruby methods partially applicable such that they return a Proc. 162 | 163 | #### Reader 164 | 165 | ```ruby 166 | proc = Monad.reader do |m| 167 | x = m.bind (returns_a_proc_expecting_env 3) 168 | y = m.bind (returns_a_proc_expecting_env (x * 2)) 169 | m.return (y + 10) 170 | end 171 | value = proc.call(env) 172 | 173 | # OR 174 | 175 | value = Monad.run_reader(env) do |m| 176 | # ... 177 | end 178 | ``` 179 | 180 | #### ReaderStateEither 181 | 182 | This monad combines Reader, State, and Either, having monadic form (env -> state -> Either). 183 | 184 | ### Creating new monads 185 | 186 | Create a new monad by defining a class with two static methods, bind and return. They are implemented in standard monad fashion, slightly tweaked for ruby 187 | 188 | ```ruby 189 | bind(m_a, &blk) # blk is a block of "signature" a -> m_b; this method must return m_b 190 | return(val) # returns m_a 191 | ``` 192 | 193 | ### A note about List Monad 194 | 195 | Because the list monad requires executing the same (a -> m_b) multiple times with different values, it is not currently supported by the Enumerator syntax, as we cannot re-run the same segment of the enumerated block. We're working on coming up with a way around this problem. 196 | -------------------------------------------------------------------------------- /lib/monadt.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/maybe' 2 | require 'monadt/either' 3 | require 'monadt/async' 4 | require 'monadt/state' 5 | require 'monadt/async_either' 6 | require 'monadt/reader_state_either' 7 | require 'monadt/do_m' 8 | 9 | module Monadt 10 | class Monad 11 | class << self 12 | def maybe(&blk) 13 | do_m(Maybe, &blk) 14 | end 15 | 16 | def present(&blk) 17 | do_m(Present, &blk) 18 | end 19 | 20 | def either(&blk) 21 | do_m(Either, &blk) 22 | end 23 | 24 | def async(&blk) 25 | do_m(Async, &blk) 26 | end 27 | 28 | def async_either(&blk) 29 | do_m(AsyncEither, &blk) 30 | end 31 | 32 | def state(&blk) 33 | do_m(State, &blk) 34 | end 35 | 36 | def run_state(initial_state, &blk) 37 | prc = state(&blk) 38 | prc.(initial_state).first 39 | end 40 | 41 | def reader(&blk) 42 | do_m(Reader, &blk) 43 | end 44 | 45 | def run_reader(env, &blk) 46 | reader(&blk).(env) 47 | end 48 | 49 | def reader_state_choice(&blk) 50 | do_m(ReaderStateEither, &blk) 51 | end 52 | 53 | def run_reader_state_choice(env, initial_state, &blk) 54 | reader_state_choice(&blk).(env, initial_state).first 55 | end 56 | end 57 | end 58 | end 59 | 60 | -------------------------------------------------------------------------------- /lib/monadt/adt.rb: -------------------------------------------------------------------------------- 1 | require 'active_support/inflector' 2 | 3 | AdtPattern = Struct.new :klass, :lambda 4 | 5 | def data(*fields) 6 | base = if fields.size > 0 7 | Struct.new(*fields) 8 | else 9 | Object 10 | end 11 | Class.new(base) 12 | end 13 | 14 | def decorate_adt(klass) 15 | klass.constants.each do |v| 16 | name = v.to_s.underscore 17 | const = klass.const_get v 18 | klass.constants.each do |is_v| 19 | is_name = is_v.to_s.underscore 20 | ret = is_v == v 21 | const.class_eval do 22 | define_method "is_#{is_name}?" do ret end 23 | end 24 | end 25 | const.class_eval do 26 | define_method "to_s" do 27 | if respond_to? :values 28 | "#{v.to_s}(#{values.join(", ")})" 29 | else 30 | v.to_s 31 | end 32 | end 33 | end 34 | klass.class_eval do 35 | define_singleton_method name do |*values| const.new(*values) end 36 | end 37 | end 38 | end 39 | 40 | Default = data 41 | 42 | module Adt 43 | def match(o, *cases) 44 | m = cases.find do |tpl| 45 | tpl.klass == o.class || tpl.klass == Default 46 | end 47 | params = 48 | if m.lambda.arity > 0 49 | o.values.take(m.lambda.arity) 50 | else 51 | [] 52 | end 53 | m.lambda.call(*params) 54 | end 55 | 56 | def with(klass, prc=nil, &blk) 57 | AdtPattern.new klass, prc || blk 58 | end 59 | end 60 | 61 | 62 | -------------------------------------------------------------------------------- /lib/monadt/async.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/adt' 2 | 3 | module Monadt 4 | class Async 5 | class << self 6 | 7 | def bind(m, &blk) 8 | a = m.resume 9 | m2 = blk.call(a) 10 | if m2.alive? 11 | m2 12 | else 13 | self.return a 14 | end 15 | end 16 | 17 | def return(a) 18 | Fiber.new { a } 19 | end 20 | end 21 | 22 | end 23 | end 24 | 25 | -------------------------------------------------------------------------------- /lib/monadt/async_either.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/adt' 2 | require 'monadt/either' 3 | 4 | module Monadt 5 | class AsyncEither 6 | class << self 7 | include Adt 8 | 9 | def bind(m, &blk) 10 | a = m.resume 11 | match(a, 12 | with(Either::Left) { |v| Async.return a }, 13 | with(Either::Right) { |v| 14 | m2 = blk.call(v) 15 | if m2.alive? 16 | m2 17 | else 18 | Async.return a 19 | end 20 | }) 21 | end 22 | 23 | def return(a) 24 | Async.return(Either.return(a)) 25 | end 26 | end 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /lib/monadt/do_m.rb: -------------------------------------------------------------------------------- 1 | require_relative 'do_m/fiber' 2 | require_relative 'do_m/enumerator' 3 | 4 | module Monadt 5 | class Monad 6 | 7 | class << self 8 | def engine 9 | if ENV['DO_M_ENGINE'].nil? 10 | DoMFiber 11 | else 12 | Object.const_get(ENV['DO_M_ENGINE']) 13 | end 14 | end 15 | 16 | def do_m(klass, &blk) 17 | engine.do_m(klass, &blk) 18 | end 19 | end 20 | end 21 | end 22 | 23 | -------------------------------------------------------------------------------- /lib/monadt/do_m/enumerator.rb: -------------------------------------------------------------------------------- 1 | require 'fiber' 2 | 3 | module Monadt 4 | module Enum 5 | class MonadObj 6 | def initialize(klass, yielder) 7 | @klass = klass 8 | @yielder = yielder 9 | end 10 | 11 | def return(val) 12 | @klass.return val 13 | end 14 | 15 | def bind(val) 16 | @yielder.yield val 17 | end 18 | end 19 | end 20 | 21 | class DoMEnumerator 22 | class << self 23 | def do_m(klass, &blk) 24 | e = Enumerator.new do |y| 25 | m_obj = Enum::MonadObj.new klass, y 26 | blk.call(m_obj) 27 | end 28 | do_m_recur(klass, e) 29 | end 30 | 31 | def do_m_recur(klass, e) 32 | begin 33 | ma = e.next 34 | rescue StopIteration => ex 35 | return ex.result 36 | end 37 | klass.bind(ma) do |a| 38 | e.feed a 39 | do_m_recur(klass, e) 40 | end 41 | end 42 | end 43 | end 44 | end 45 | -------------------------------------------------------------------------------- /lib/monadt/do_m/fiber.rb: -------------------------------------------------------------------------------- 1 | require 'fiber' 2 | 3 | module Monadt 4 | module Fibr 5 | class MonadObj 6 | def initialize(klass) 7 | @klass = klass 8 | end 9 | 10 | def return(val) 11 | @klass.return val 12 | end 13 | 14 | def bind(val) 15 | Fiber.yield val 16 | end 17 | end 18 | end 19 | 20 | class DoMFiber 21 | class << self 22 | def do_m(klass, &blk) 23 | f = Fiber.new do |y| 24 | m_obj = Fibr::MonadObj.new klass 25 | blk.call(m_obj) 26 | end 27 | do_m_recur(klass, f, nil) 28 | end 29 | 30 | def do_m_recur(klass, f, ma, *args) 31 | if f.alive? 32 | ma = f.resume(*args) 33 | klass.bind(ma) do |a| 34 | do_m_recur(klass, f, ma, a) 35 | end 36 | else 37 | ma 38 | end 39 | end 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /lib/monadt/either.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/adt' 2 | 3 | module Monadt 4 | class Either 5 | Left = data :left 6 | Right = data :right 7 | 8 | class << self 9 | include Adt 10 | 11 | def bind(m, &blk) 12 | match(m, 13 | with(Left) { |v| m }, 14 | with(Right) { |v| blk.call(v) }) 15 | end 16 | 17 | def return(a) 18 | right a 19 | end 20 | end 21 | 22 | end 23 | 24 | decorate_adt Either 25 | end 26 | 27 | -------------------------------------------------------------------------------- /lib/monadt/list.rb: -------------------------------------------------------------------------------- 1 | require_relative 'maybe' 2 | require_relative 'either' 3 | require_relative 'state' 4 | require_relative 'reader_state_either' 5 | 6 | class ListM 7 | class << self 8 | def bind(m, &blk) 9 | m.flat_map(&blk) 10 | end 11 | 12 | def return(a) 13 | [a] 14 | end 15 | end 16 | end 17 | 18 | -------------------------------------------------------------------------------- /lib/monadt/maybe.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/adt' 2 | 3 | module Monadt 4 | class Maybe 5 | Just = data :value 6 | Nothing = data 7 | 8 | class << self 9 | include Adt 10 | 11 | def bind(m, &blk) 12 | match(m, 13 | with(Just) { |v| blk.call(v) }, 14 | with(Nothing) { m }) 15 | end 16 | 17 | def return(a) 18 | Maybe.just a 19 | end 20 | end 21 | end 22 | decorate_adt Maybe 23 | 24 | # like Maybe but nil / not-nill 25 | class Present 26 | class << self 27 | def bind(m, &blk) 28 | if m.nil? 29 | nil 30 | else 31 | blk.call(m) 32 | end 33 | end 34 | 35 | def return(a) 36 | a 37 | end 38 | end 39 | end 40 | end 41 | 42 | -------------------------------------------------------------------------------- /lib/monadt/reader.rb: -------------------------------------------------------------------------------- 1 | module Monadt 2 | class Reader 3 | class << self 4 | def bind(m, &blk) 5 | ->(e) { 6 | v = m.(e) 7 | blk.call(e, v) 8 | } 9 | end 10 | 11 | def return(val) 12 | ->(e) { val } 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /lib/monadt/reader_state_either.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/adt' 2 | 3 | module Monadt 4 | class ReaderStateEither 5 | class << self 6 | include Adt 7 | 8 | def bind(m, &blk) 9 | ->(e, s) { 10 | c, s2 = m.(e, s) 11 | match(c, 12 | with(Either::Left) {|v| [c, s2]}, 13 | with(Either::Right) {|v| 14 | blk.call(v).(e, s2) 15 | }) 16 | } 17 | end 18 | 19 | def return(val) 20 | ->(e, s) { [Either.return(val), s] } 21 | end 22 | end 23 | end 24 | end 25 | -------------------------------------------------------------------------------- /lib/monadt/state.rb: -------------------------------------------------------------------------------- 1 | module Monadt 2 | class State 3 | class << self 4 | def bind(m, &blk) 5 | ->(st) { 6 | v, s = m.(st) 7 | blk.call(v).(s) 8 | } 9 | end 10 | 11 | def return(val) 12 | ->(st) { [val, st] } 13 | end 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /monadt.gemspec: -------------------------------------------------------------------------------- 1 | Gem::Specification.new do |s| 2 | s.name = 'monadt' 3 | s.version = '0.1.2' 4 | s.date = '2016-03-25' 5 | s.summary = "ADTs and Monads in Ruby" 6 | s.description = "Functions to create ADTs and do pattern matching, as well as Enumerator based Monad computation" 7 | s.authors = ["Will Pleasant-Ryan"] 8 | s.email = 'will.ryan@atomicobject.com' 9 | s.files = ["lib/monadt.rb"] + Dir[ "lib/monadt/**/*.rb"] 10 | s.homepage = 'https://github.com/atomicobject/monadt' 11 | s.license = 'Apache' 12 | end 13 | -------------------------------------------------------------------------------- /spec/monadt/adt_spec.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/adt' 2 | 3 | class TestAdt 4 | One = data :foo, :bar 5 | Two = data :foo 6 | AndThree = data 7 | end 8 | 9 | decorate_adt TestAdt 10 | 11 | class UseAdts 12 | include Adt 13 | 14 | def adt_func(o) 15 | match o, 16 | with(TestAdt::One, ->(foo, bar) { foo.to_s + bar.to_s }), 17 | with(TestAdt::AndThree, ->() { 10 }), 18 | with(Default, ->() { "default" }) 19 | end 20 | 21 | def adt_func2(o) 22 | match o, 23 | with(TestAdt::One) { |foo, bar| foo.to_s + bar.to_s }, 24 | with(TestAdt::AndThree) { 10 }, 25 | with(Default) { "default" } 26 | end 27 | end 28 | 29 | describe 'Algebraic Data Types' do 30 | let(:v1) { TestAdt.one 1, :five } 31 | let(:v2) { TestAdt.two "hoi" } 32 | let(:v3) { TestAdt.and_three } 33 | let(:subject) { UseAdts.new } 34 | 35 | describe 'proc/block based ADTs' do 36 | 37 | it 'supports procs' do 38 | expect(subject.adt_func(v1)).to eq("1five") 39 | expect(subject.adt_func(v2)).to eq("default") 40 | expect(subject.adt_func(v3)).to eq(10) 41 | end 42 | 43 | it 'supports blocks' do 44 | expect(subject.adt_func2(v1)).to eq("1five") 45 | expect(subject.adt_func2(v2)).to eq("default") 46 | expect(subject.adt_func2(v3)).to eq(10) 47 | end 48 | end 49 | 50 | describe "decorate ADTs" do 51 | it 'supports blocks' do 52 | expect(v1.is_one?).to be true 53 | expect(v1.is_two?).to be false 54 | expect(v1.is_and_three?).to be false 55 | expect(v1.to_s).to eq("One(1, five)") 56 | 57 | expect(v2.is_one?).to be false 58 | expect(v2.is_two?).to be true 59 | expect(v2.is_and_three?).to be false 60 | expect(v2.to_s).to eq("Two(hoi)") 61 | 62 | expect(v3.is_one?).to be false 63 | expect(v3.is_two?).to be false 64 | expect(v3.is_and_three?).to be true 65 | expect(v3.to_s).to eq("AndThree") 66 | end 67 | end 68 | end 69 | -------------------------------------------------------------------------------- /spec/monadt/monad_async_either_example.rb: -------------------------------------------------------------------------------- 1 | require 'monadt' 2 | 3 | module Monadt 4 | class AsyncEitherExample 5 | @@urls = { 6 | "www.test.com" => {hello: 'world'}, 7 | "www.another.com/world" => {get: 'data'}, 8 | "www.test.com/data" => {bar: 'baz'} 9 | } 10 | class << self 11 | 12 | def get_url(x) 13 | Fiber.new { 14 | sleep 0.01 15 | if @@urls.has_key? x 16 | Either.right @@urls[x] 17 | else 18 | Either.left "URL #{x} could not be retrieved" 19 | end 20 | } 21 | end 22 | 23 | def async_func_works() 24 | Monad.async_either do |m| 25 | test = m.bind (get_url "www.test.com") 26 | another = m.bind (get_url "www.another.com/#{test[:hello]}") 27 | data = m.bind (get_url "www.test.com/#{another[:get]}") 28 | m.return data 29 | end 30 | end 31 | 32 | def async_func_short_circuit() 33 | Monad.async_either do |m| 34 | test = m.bind (get_url "www.test.com") 35 | another = m.bind (get_url "www.fail.com/#{test[:hello]}") 36 | raise "NO" 37 | data = m.bind (get_url "www.test.com/#{another[:get]}") 38 | m.return data 39 | end 40 | end 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /spec/monadt/monad_async_either_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_async_either_example' 2 | require 'monadt/async_either' 3 | 4 | describe 'async either monad' do 5 | it 'handles correct cases' do 6 | result = Monadt::AsyncEitherExample.async_func_works().resume 7 | expect(result.is_right?).to be true 8 | expect(result.right).to eq({bar: 'baz'}) 9 | end 10 | 11 | it 'stops early' do 12 | result = Monadt::AsyncEitherExample.async_func_short_circuit().resume 13 | expect(result.is_right?).to be false 14 | expect(result.left).to eq("URL www.fail.com/world could not be retrieved") 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /spec/monadt/monad_async_example.rb: -------------------------------------------------------------------------------- 1 | require 'monadt' 2 | 3 | module Monadt 4 | class AsyncExample 5 | class << self 6 | def async1(x) 7 | Fiber.new { 8 | x + 1 9 | } 10 | end 11 | 12 | def async2(y, z) 13 | if (y > 0) 14 | Fiber.new { z ** y } 15 | else 16 | Fiber.new { z - y } 17 | end 18 | end 19 | 20 | def async_func(v) 21 | Monad.async do |m| 22 | x = m.bind (async1 v) 23 | y = m.bind (async2 x, v) 24 | ret = m.return (x + y) 25 | ret 26 | end 27 | end 28 | end 29 | end 30 | end 31 | -------------------------------------------------------------------------------- /spec/monadt/monad_async_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_async_example' 2 | require 'monadt/async' 3 | 4 | describe 'async monad' do 5 | it 'handles correct cases' do 6 | result = Monadt::AsyncExample.async_func(9) 7 | expect(result.resume).to eq(9 ** 10 + 10) 8 | 9 | result = Monadt::AsyncExample.async_func(-3) 10 | expect(result.resume).to eq(-3) 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /spec/monadt/monad_either_example.rb: -------------------------------------------------------------------------------- 1 | require 'monadt' 2 | 3 | module Monadt 4 | class EitherExample 5 | class << self 6 | 7 | def choose1(x) 8 | if x > 5 9 | Either.right (x - 5) 10 | else 11 | Either.left "less than 5" 12 | end 13 | end 14 | 15 | def choose2(z) 16 | if z % 2 == 0 17 | Either.right (z * 2) 18 | else 19 | Either.left "i need even numbers" 20 | end 21 | end 22 | 23 | def either_func(v) 24 | Monad.either do |m| 25 | x = m.bind (choose1 v) 26 | y = m.bind (choose2 x) 27 | m.return (x + y) 28 | end 29 | end 30 | 31 | def either_func_stop_early(v) 32 | Monad.either do |m| 33 | x = m.bind (choose1 v) 34 | raise 'uh oh' 35 | y = m.bind (choose2 x) 36 | m.return (x + y) 37 | end 38 | end 39 | end 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /spec/monadt/monad_either_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_either_example' 2 | require 'monadt/either' 3 | 4 | describe 'either monad' do 5 | it 'handles correct cases' do 6 | result = Monadt::EitherExample.either_func(9) 7 | expect(result.is_right?).to be true 8 | expect(result.right).to eq(12) 9 | 10 | result = Monadt::EitherExample.either_func(3) 11 | expect(result.is_right?).to be false 12 | expect(result.left).to eq("less than 5") 13 | 14 | result = Monadt::EitherExample.either_func(10) 15 | expect(result.is_right?).to be false 16 | expect(result.left).to eq("i need even numbers") 17 | end 18 | 19 | it 'stops early' do 20 | result = Monadt::EitherExample.either_func_stop_early(3) 21 | expect(result.is_right?).to be false 22 | expect(result.left).to eq("less than 5") 23 | 24 | expect { Monadt::EitherExample.either_func_stop_early(9) }.to raise_exception("uh oh") 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /spec/monadt/monad_list_example.rb: -------------------------------------------------------------------------------- 1 | require 'monadt/do_m' 2 | 3 | module Monadt 4 | class ListExample 5 | class << self 6 | 7 | def list1(x) 8 | #Choice.failure "no" 9 | if x > 5 10 | [x - 5, x] 11 | else 12 | [x, x + 2] 13 | end 14 | end 15 | 16 | def list2(z) 17 | if z % 2 == 0 18 | [z, z / 2] 19 | else 20 | [z, z * 2] 21 | end 22 | end 23 | 24 | def list_func(v) 25 | Monad.do_m(List) do |m| 26 | x = m.bind (list1 v) 27 | y = m.bind (list2 x) 28 | List.return (x + y) 29 | end 30 | end 31 | end 32 | end 33 | end 34 | -------------------------------------------------------------------------------- /spec/monadt/monad_list_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_list_example' 2 | 3 | describe 'list monad' do 4 | xit 'tries all the possibilities' do 5 | result = ListExample.list_func(9) 6 | expect(result.is_a? Either::Left).to be true 7 | expect(result.value).to eq(12) 8 | 9 | result = ListExample.list_func(3) 10 | expect(result.to eq([1,2,3,4])) 11 | 12 | result = ListExample.list_func(10) 13 | expect(result.to eq([1,2,3,4])) 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /spec/monadt/monad_maybe_example.rb: -------------------------------------------------------------------------------- 1 | require 'monadt' 2 | 3 | module Monadt 4 | class MaybeExample 5 | class << self 6 | 7 | def may1(x) 8 | Maybe.just x 9 | end 10 | 11 | def may2(z) 12 | if z > 0 13 | Maybe.just (z * 2) 14 | else 15 | Maybe.nothing 16 | end 17 | end 18 | 19 | def maybe_func(v) 20 | Monad.maybe do |m| 21 | x = m.bind may1 v 22 | y = m.bind may2 x 23 | m.return (x + y) 24 | end 25 | end 26 | 27 | def maybe_func_stop_early(v) 28 | Monad.maybe do |m| 29 | x = m.bind may1 v 30 | y = m.bind may2 x 31 | raise 'uh oh' 32 | m.return x + y 33 | end 34 | end 35 | end 36 | end 37 | 38 | class PresentExample 39 | class << self 40 | def may1(x) 41 | x 42 | end 43 | 44 | def may2(z) 45 | if z > 0 46 | z * 2 47 | else 48 | nil 49 | end 50 | end 51 | 52 | def maybe_func(v) 53 | Monad.present do |m| 54 | x = m.bind may1 v 55 | y = m.bind may2 x 56 | m.return (x + y) 57 | end 58 | end 59 | 60 | def maybe_func_stop_early(v) 61 | Monad.present do |m| 62 | x = m.bind may1 v 63 | y = m.bind may2 x 64 | raise 'uh oh' 65 | m.return x + y 66 | end 67 | end 68 | end 69 | end 70 | end 71 | -------------------------------------------------------------------------------- /spec/monadt/monad_maybe_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_maybe_example' 2 | 3 | describe 'maybe monad' do 4 | it 'handles correct cases' do 5 | result = Monadt::MaybeExample.maybe_func(5) 6 | expect(result.value).to eq(15) 7 | 8 | result = Monadt::MaybeExample.maybe_func(-4) 9 | expect(result.is_nothing?).to be true 10 | end 11 | 12 | it 'stops early' do 13 | result = Monadt::MaybeExample.maybe_func_stop_early(-4) 14 | expect(result.is_nothing?).to be true 15 | 16 | expect { Monadt::MaybeExample.maybe_func_stop_early(5) }.to raise_exception("uh oh") 17 | end 18 | end 19 | 20 | describe 'present monad' do 21 | it 'handles correct cases' do 22 | result = Monadt::PresentExample.maybe_func(5) 23 | expect(result).to eq(15) 24 | 25 | result = Monadt::PresentExample.maybe_func(-4) 26 | expect(result).to be nil 27 | end 28 | 29 | it 'stops early' do 30 | result = Monadt::PresentExample.maybe_func_stop_early(-4) 31 | expect(result).to be nil 32 | 33 | expect { Monadt::PresentExample.maybe_func_stop_early(5) }.to raise_exception("uh oh") 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /spec/monadt/monad_reader_state_either_example.rb: -------------------------------------------------------------------------------- 1 | require 'funkify' 2 | require 'monadt' 3 | require 'util' 4 | 5 | module Monadt 6 | class ReaderStateEitherFuncs 7 | include Funkify 8 | 9 | auto_curry 10 | def unpack(base, language, state) 11 | modded = state.first % base 12 | if (modded > 5) 13 | [Either.left('too big'), state.rest] 14 | else 15 | v = Lang.send(language)[modded] 16 | [Either.right(v), state.rest] 17 | end 18 | end 19 | 20 | end 21 | 22 | class ReaderStateEitherExample 23 | class << self 24 | def state_func(language, bytes) 25 | sf = ReaderStateEitherFuncs.new 26 | Monad.run_reader_state_choice(language, bytes) do |m| 27 | x = m.bind (sf.unpack 4) 28 | y = m.bind (sf.unpack 9) 29 | z = m.bind (sf.unpack 3) 30 | m.return "#{x}, #{y}, #{z}" 31 | end 32 | end 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /spec/monadt/monad_reader_state_either_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_reader_state_either_example' 2 | 3 | describe 'reader state either monad' do 4 | it 'handles correct cases' do 5 | val = Monadt::ReaderStateEitherExample.state_func(:english, [5,14,8]) 6 | expect(val.is_right?).to be true 7 | expect(val.right).to eq("one, five, two") 8 | 9 | expect(val.is_right?).to be true 10 | val = Monadt::ReaderStateEitherExample.state_func(:spanish, [5,14,8]) 11 | expect(val.right).to eq("uno, cinco, dos") 12 | end 13 | 14 | it 'stops early' do 15 | val = Monadt::ReaderStateEitherExample.state_func(:english, [5,8,8]) 16 | expect(val.is_right?).to be false 17 | expect(val.left).to eq("too big") 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /spec/monadt/monad_state_example.rb: -------------------------------------------------------------------------------- 1 | require 'funkify' 2 | require 'monadt' 3 | require 'util' 4 | 5 | module Monadt 6 | class StateFuncs 7 | include Funkify 8 | 9 | auto_curry 10 | def unpack_english(base, state) 11 | v = Lang.english[state.first % base] 12 | [v, state.rest] 13 | end 14 | 15 | def unpack_spanish(base, state) 16 | v = Lang.spanish[state.first % base] 17 | [v, state.rest] 18 | end 19 | end 20 | 21 | class StateExample 22 | class << self 23 | def state_func(bytes) 24 | sf = StateFuncs.new 25 | Monad.run_state(bytes) do |m| 26 | a = m.bind (sf.unpack_english 4) 27 | b = m.bind (sf.unpack_english 6) 28 | c = m.bind (sf.unpack_spanish 5) 29 | d = m.bind (sf.unpack_spanish 2) 30 | m.return "#{a} and #{b} + #{c} y #{d}" 31 | end 32 | end 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /spec/monadt/monad_state_spec.rb: -------------------------------------------------------------------------------- 1 | require_relative 'monad_state_example' 2 | 3 | describe 'state monad' do 4 | it 'can do deserialization' do 5 | expect(Monadt::StateExample.state_func([6,11,8,10])).to eq("two and five + tres y cero") 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | PROJECT_ROOT = File.expand_path(File.dirname(__FILE__) + "/..") 2 | 3 | $LOAD_PATH << "#{PROJECT_ROOT}/lib" 4 | $LOAD_PATH << "#{PROJECT_ROOT}/spec" 5 | 6 | require 'factory_girl' 7 | require 'mocha/api' 8 | 9 | RSpec.configure do |config| 10 | config.mock_with :mocha 11 | config.include FactoryGirl::Syntax::Methods 12 | config.include Mocha::API 13 | end 14 | 15 | -------------------------------------------------------------------------------- /spec/util.rb: -------------------------------------------------------------------------------- 1 | class Array 2 | def rest 3 | self[1..-1] 4 | end 5 | end 6 | 7 | class Lang 8 | def self.english 9 | ['zero', 'one', 'two', 'three', 'four', 'five'] 10 | end 11 | def self.spanish 12 | ['cero', 'uno', 'dos', 'tres', 'quatro', 'cinco'] 13 | end 14 | end 15 | --------------------------------------------------------------------------------