From 96d4bbd5c3226bb746e8f813818320f4f6a4b9c2 Mon Sep 17 00:00:00 2001 From: Stephen Paul Weber Date: Sun, 31 Mar 2019 19:10:59 -0500 Subject: [PATCH] Refactor UnionType#fetch --- lib/dhall/ast.rb | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/lib/dhall/ast.rb b/lib/dhall/ast.rb index 5b98d20..a506e17 100644 --- a/lib/dhall/ast.rb +++ b/lib/dhall/ast.rb @@ -650,20 +650,13 @@ module Dhall end def fetch(k, default=nil) - if (default || block_given?) && !alternatives.key?(k) - return (default || yield) - end - - remains = with(alternatives: alternatives.dup.tap { |r| r.delete(k) }) Function.new( var: k, type: alternatives.fetch(k), - body: Union.new( - tag: k, - value: Variable.new(name: k), - alternatives: remains - ) + body: Union.from(self, tag, Variable[k]) ).normalize + rescue KeyError + block_given? ? yield : (default || raise) end def constructor_types @@ -684,6 +677,16 @@ module Dhall alternatives UnionType end) + def self.from(alts, tag, value) + new( + tag: tag, + value: value, + alternatives: alts.with( + alternatives: alts.alternatives.reject { |alt, _| alt == tag } + ) + ) + end + def as_json [12, tag, value.as_json, alternatives.as_json.last] end -- 2.34.5