Skip to content

Instantly share code, notes, and snippets.

@fmnoise
Last active May 3, 2017 18:59
Show Gist options
  • Save fmnoise/166215eaddf93f6fca5022439a25b7e5 to your computer and use it in GitHub Desktop.
Save fmnoise/166215eaddf93f6fca5022439a25b7e5 to your computer and use it in GitHub Desktop.
Maybe monad in Ruby
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