Skip to content

Instantly share code, notes, and snippets.

@Heimdell
Last active May 19, 2016 19:24
Show Gist options
  • Save Heimdell/77da320dd3ff81dd6f1a7096001dbaef to your computer and use it in GitHub Desktop.
Save Heimdell/77da320dd3ff81dd6f1a7096001dbaef to your computer and use it in GitHub Desktop.
class Match
def initialize x
@x = x
self
end
def self.of x
Match.new x
end
def on pred
unless @result
yep = if pred.respond_to? :call then
pred.call @x
else
pred == @x
end
@result = yield @x if yep
end
self
end
def default &block
on ->{true} do
yield
end
end
def result
@result
end
end
def elem? coll
->(x) do
coll.member? x
end
end
puts Match.of(1)
.on(2) { 'two' }
.on(elem? [1,2,3]) { 'odd' }
.default { 'unknown' }
.result
Object subclass: Match [
| value result |
Match class >> of: val [
^ super new value: val
]
value: val [
value := val
]
case: pred then: action [
result ifNil: [
(pred respondsTo: #value:)
ifTrue: [ (pred value: value) ifTrue: [ result := action value ] ]
ifFalse: [ pred == value ifTrue: [ result := action value ] ]
]
]
default: block [
self case: [True] then: block
]
result [ ^ result ]
]
Object subclass: Test [
test [
^ (Match of: 1)
case: 2 then:
['two'];
case: [:x | #(1 3 5) includes: x] then:
['odd'];
default:
['unknown'];
result.
]
]
Test new test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment