Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Add #try and talk about monads.

  • Loading branch information...
commit 9c4a528bfb14c7ba3f58bb6f4f8d576f8bbbde99 1 parent 10554fb
@mike-burns mike-burns authored
Showing with 31 additions and 0 deletions.
  1. +9 −0 README.md
  2. +8 −0 lib/wrapped/types.rb
  3. +14 −0 spec/wrapped_spec.rb
View
9 README.md
@@ -104,6 +104,15 @@ For example:
irb(main):055:0> nil.wrapped.inject(0) {|_, n| n+1}
=> 0
+And then we have `try`, which you can use to produce another wrapped object:
+
+ irb> 1.wrapped.try {|n| (n + 1).wrapped}.try {|n| (n*2).wrapped}.unwrap
+ => 4
+
+Those same people who will exclaim things about functors will, at this point,
+get giddy about monads. I mean, they're right, but they can relax. It's just a
+monad.
+
Other Methods
-------------
View
8 lib/wrapped/types.rb
@@ -38,6 +38,10 @@ def present?
def blank?
false
end
+
+ def try
+ yield unwrap
+ end
end
class Blank
@@ -71,4 +75,8 @@ def present?
def blank?
true
end
+
+ def try
+ self
+ end
end
View
14 spec/wrapped_spec.rb
@@ -144,3 +144,17 @@
nothing.unwrap_or(-1) {2}.should == -1
end
end
+
+describe Wrapped, 'monadic' do
+ let(:value) { 1 }
+ let(:just) { 1.wrapped }
+ let(:nothing) { nil.wrapped }
+
+ it 'produces the value from #try for a wrapped value' do
+ just.try {|n| (n+1).wrapped }.unwrap.should == value+1
+ end
+
+ it 'produces blank from #try for a wrapped nil' do
+ nothing.try {|n| (n+1).wrapped}.should be_blank
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.