Skip to content

Commit

Permalink
Either handles Just and Nothing as Success and Failure
Browse files Browse the repository at this point in the history
  • Loading branch information
Piotr Zolnierek committed Jun 24, 2012
1 parent 850b724 commit 8bf26b4
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
7 changes: 4 additions & 3 deletions README.md
Expand Up @@ -90,9 +90,10 @@ Maybe(1).to_s == '1'
```

`#or`
Maybe(nil).or(1) == 1
Maybe(1).or(2) == 1
Maybe(nil).or(nil) == Just(nil)
Maybe(nil).or(1) == Just(1)
Maybe(1).or(2) == Just(1)
Maybe(nil).or(1) == Just(1)
Maybe(nil).or(nil) == Nothing

Falsey values (kind-of) examples:

Expand Down
4 changes: 3 additions & 1 deletion lib/monadic/either.rb
Expand Up @@ -8,7 +8,9 @@ def self.chain(initial=nil, &block)

def self.unit(value)
return value if value.is_a? Either
return Failure.new(value) if value.nil? || (value.respond_to?(:empty?) && value.empty?) || !value
return Nothing if value.is_a? Nothing
return Success.new(value.fetch) if value.is_a? Just
return Failure.new(value) if value.nil? || (value.respond_to?(:empty?) && value.empty?) || !value
return Success.new(value)
end

Expand Down
12 changes: 12 additions & 0 deletions spec/either_spec.rb
Expand Up @@ -39,6 +39,10 @@
Failure(1).should_not == Failure(2)
end

it 'Either(Nothing) is a Failure' do
Either(Nothing).should == Failure(Nothing)
end

it 'wraps a nil result to Failure' do
Success(nil).bind { nil }.should == Failure(nil)
end
Expand Down Expand Up @@ -241,6 +245,14 @@ def process_content(content); content.start_with?('b') ? Success(content.upcase)
either.fetch.should be_a KeyError
end

it 'Either(Nothing) returns a Failure' do
Either(Nothing).should == Failure(Nothing)
end

it 'Either(Just) returns a Success' do
Either(Just.new(1)).should == Success(1)
end

it 'instance variables' do
result = Either.chain do
bind { @map = { one: 1, two: 2 } }
Expand Down

0 comments on commit 8bf26b4

Please sign in to comment.