Last active
October 18, 2017 00:58
-
-
Save dnagir/9134d1b498f8ed3d8b1cb75dc6d9411f to your computer and use it in GitHub Desktop.
Minimal Ruby Maybe monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'singleton' | |
module Maybe | |
class Just < BasicObject | |
attr_reader :value | |
def initialize(value) | |
@value = value | |
end | |
def present? | |
true | |
end | |
end | |
class Nothing < BasicObject | |
include ::Singleton | |
def present? | |
false | |
end | |
end | |
def self.just(value) | |
Just.new(value) | |
end | |
def self.nothing | |
Nothing.instance | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts Maybe.just('foo').value # "foo" | |
puts Maybe.nothing.value rescue puts "No value on nothing" | |
puts Maybe.just('foo').to_s rescue puts "Can't call random stuff on Maybe - unwrap using #value" | |
def use_maybe(maybe) | |
if maybe.present? | |
puts maybe.value | |
else | |
puts "no, no, cannot use it" | |
end | |
end | |
use_maybe Maybe.just('foo') | |
use_maybe Maybe.nothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment