Module: RubyNext::Language::Rewriters::Predicates
- Defined in:
- lib/ruby-next/language/rewriters/2.7/pattern_matching.rb
Overview
We can memoize structural predicates to avoid double calculation.
For example, consider the following case and the corresponding predicate chains:
case val
in [:ok, 200] #=> [:respond_to_deconstruct, :deconstruct_type, :arr_size_is_2]
in [:created, 201] #=> [:respond_to_deconstruct, :deconstruct_type, :arr_size_is_2]
in [401 | 403] #=> [:respond_to_deconstruct, :deconstruct_type, :arr_size_is_1]
end
We can minimize the number of predicate calls by storing the intermediate values (prefixed with ‘p_`) and using them in the subsequent calls:
case val
in [:ok, 200] #=> [:respond_to_deconstruct, :deconstruct_type, :arr_size_is_2]
in [:created, 201] #=> [:p_deconstructed, :p_arr_size_2]
in [401 | 403] #=> [:p_deconstructed, :arr_size_is_1]
end
This way we mimic a naive decision tree algorithim.