Last active
May 3, 2017 18:59
-
-
Save fmnoise/166215eaddf93f6fca5022439a25b7e5 to your computer and use it in GitHub Desktop.
Maybe monad in Ruby
This file contains 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
module Monads | |
class Maybe | |
def self.[](value) | |
self.new(value) | |
end | |
def initialize(value) | |
@value = value | |
end | |
def fmap | |
self.class.new(@value.nil? ? nil : block_given? ? yield(@value) : @value) | |
end | |
def fold | |
@value.nil? ? nil : block_given? ? yield(@value) : @value | |
end | |
end | |
end | |
########################################## | |
def email_service_imperative user_id | |
if user = User.find_by_id(user_id) | |
if email = user.email | |
if service = email.split('@').last | |
service.upcase | |
end | |
end | |
end | |
end | |
def email_service_declarative user_id | |
Monads::Maybe[user_id] | |
.fmap{|v| User.find_by_id(v)} | |
.fmap(&:email) | |
.fmap{|v| v.split '@'} | |
.fmap(&:last) | |
.fold(&:upcase) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment