Created
January 23, 2018 23:41
-
-
Save endgame/99140595cc07fd03afb6e29bf0e8da5d to your computer and use it in GitHub Desktop.
Monoids in Ruby
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
class Monoid | |
attr_reader :mempty | |
def initialize(mempty, mappend) | |
@mempty = mempty | |
@mappend = mappend | |
end | |
def mappend(x, y) | |
@mappend.call(x, y) | |
end | |
def mconcat(enumerable) | |
enumerable.reduce(mempty &@mconcat) | |
end | |
end | |
sum = Monoid.new(0) { |x, y| x + y } | |
def hashmerge(monoid) | |
Monoid.new({}) do |h1, h2| | |
h2.merge(h2) do |key, old, new| | |
monoid.mappend(old, new) | |
end | |
end | |
end | |
def function(monoid) | |
Monoid.new(lambda { |x| monoid.mempty }) do |f, g| | |
lambda do |x| | |
monoid.mappend(f.call(x), g.call(x)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment