Last active
June 1, 2016 10:52
-
-
Save katafrakt/f32c7f0e5add474a13ff7a791e7a7791 to your computer and use it in GitHub Desktop.
Which pattern-matching syntax is better?
This file contains 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
# Which pattern-matching syntax you think is better in Ruby? | |
# | |
# Some background: | |
# - https://github.com/katafrakt/noaidi | |
# - http://katafrakt.me/2016/02/13/quest-for-pattern-matching-in-ruby/ | |
# - http://katafrakt.me/2016/05/24/refactoring-rails-with-noaidi/ | |
# Syntax 1: | |
Noaidi.match open_file(path), { | |
[:ok, File] => ->(file) { process_file(file) }, | |
[:error, Exception] => ->(ex) { handle_file_opening_exception(path, ex) } | |
} | |
# or | |
Noaidi.match open_file(path), { | |
[:ok, File] => lambda {|file| process_file(file) }, | |
[:error, Exception] => lambda {|ex| handle_file_opening_exception(path, ex) } | |
} | |
# Pros: | |
# - close to syntax from other languages, eg. Elixir | |
# Cons: | |
# - Hackish Hash syntax | |
# - Some editors don't like it (emacs) | |
# Syntax 2: | |
Noaidi.match open_file(path) do |m| | |
m(:ok, File) { |file| process_file(file) }, | |
m(:error, Exception) { |ex| handle_file_opening_exception(path, ex) } | |
} | |
# Pros: | |
# - Using natural Ruby idiom (block) | |
# - No duplicate rockets/arrows or unnecessary lambda keyword | |
# - dry-transaction uses similar syntax (http://dry-rb.org/gems/dry-transaction/basic-usage/) | |
# Cons: | |
# - I'm not entirely sure it's possible to implement | |
# - adds some clutter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Syntax 2 as well