Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement case_of #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Implement case_of #5

wants to merge 2 commits into from

Conversation

rap1ds
Copy link
Owner

@rap1ds rap1ds commented Aug 4, 2014

Maybe implements the threequals method in a way which allows it to be used in case expressions pretty neatly: You can match both the type (None or Some) and the value of Some. It almost feels like pattern matching in functional language. However, there's one big shortcoming. Ruby doesn't allow binding the value of Some to a variable, so you must use the get method to do that. The following does not work in Ruby:

case apples
when Some(1)
  puts "one apple"
when Some(x)
  puts "#{x} apples"
when None
  puts "Unknown number of apples"
end

Instead, you have to use get, which is cubersome:

case apples
when Some(1)
  puts "one apple"
when Some
  x = apples.get
  puts "#{x} apples"
when None
  puts "Unknown number of apples"
end

To workaround this limitation, Maybe implements a method case_of, which internally uses case expression:

apples.case_of(Some(1)) { |_| puts "1 apple" }
apples.case_of(Some(Integer)) { |x| puts "#{x} apples" }
apples.case_of(None) { |_| puts "Unknown number of apples" }
- apples.case_of(Some(1)) do
  = "1 apple"

- apples.case_of(Some(Integer)) do |x|
  = puts "#{x} apples"

- apples.case_of(None) do
  = "Unknown number of apples"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant