Skip to content

Instantly share code, notes, and snippets.

@endgame
Created January 23, 2018 23:41
Show Gist options
  • Save endgame/99140595cc07fd03afb6e29bf0e8da5d to your computer and use it in GitHub Desktop.
Save endgame/99140595cc07fd03afb6e29bf0e8da5d to your computer and use it in GitHub Desktop.
Monoids in Ruby
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