Skip to content

Instantly share code, notes, and snippets.

@themichaelyang
Created December 22, 2025 10:11
Show Gist options
  • Select an option

  • Save themichaelyang/dfdb267793fb690e662dd2d404320748 to your computer and use it in GitHub Desktop.

Select an option

Save themichaelyang/dfdb267793fb690e662dd2d404320748 to your computer and use it in GitHub Desktop.
monkeypatched maybe monad
class Object
def maybe(&blk)
yield self
end
end
class NilClass
def maybe(&blk)
nil
end
end
hash = {
a: {
b: {
c: 1
}
}
}
hash.maybe { _1[:a] }
.maybe { _1[:b] }
.maybe { _1[:c] }
hash.maybe { _1[:a] }
.maybe { _1[:d] }
.maybe { _1[:c] }
def unit(a)
a
end
def bind(m, &blk)
m.maybe(&blk)
end
# monad law 1
raise unless bind(unit(1)) { _1 + 2 } == 3
# monad law 2
raise unless bind(unit(1)) { unit(_1) } == unit(1)
# monad law 3
raise unless bind(1.0) { |a| bind(a + 1) { |b| b / 2 }} \
== bind(bind(1.0) { |a| a + 1}) { |b| b / 2 }
raise unless bind(1.0) { |a|
bind(a == 1 ? nil : 1) { |b| b / 2 }
} == bind(bind(1.0) { |a|
a == 1 ? nil : 1
}) { |b| b / 2 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment