From 655a14e36ef468fd16bd8ebac065f21608e49ace Mon Sep 17 00:00:00 2001 From: Gwenhael Le Moine Date: Thu, 18 Nov 2021 15:58:59 +0100 Subject: [PATCH] implement SIGN --- lib/dictionary.rb | 6 +++--- lib/language/operations.rb | 31 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/lib/dictionary.rb b/lib/dictionary.rb index 01aa618..dec2a2e 100644 --- a/lib/dictionary.rb +++ b/lib/dictionary.rb @@ -39,13 +39,13 @@ module Rpn add( 'inv', proc { |stack| Rpn::Core::Operations.inverse( stack ) } ) add( '^', proc { |stack| Rpn::Core::Operations.power( stack ) } ) add( 'sqrt', proc { |stack| Rpn::Core::Operations.sqrt( stack ) } ) - add( 'sq', proc { |stack| Rpn::Core.__todo( stack ) } ) # rpn_square - add( 'abs', proc { |stack| Rpn::Core.__todo( stack ) } ) # absolute value + add( 'sq', proc { |stack| Rpn::Core::Operations.sq( stack ) } ) + add( 'abs', proc { |stack| Rpn::Core::Operations.abs( stack ) } ) add( 'dec', proc { |stack| Rpn::Core.__todo( stack ) } ) # decimal representation add( 'hex', proc { |stack| Rpn::Core.__todo( stack ) } ) # hexadecimal representation add( 'bin', proc { |stack| Rpn::Core.__todo( stack ) } ) # binary representation add( 'base', proc { |stack| Rpn::Core.__todo( stack ) } ) # arbitrary base representation - add( 'sign', proc { |stack| Rpn::Core.__todo( stack ) } ) # 1 if number at stack level 1 is > 0, 0 if == 0, -1 if <= 0 + add( 'sign', proc { |stack| Rpn::Core::Operations.sign( stack ) } ) # OPERATIONS ON REALS add( '%', proc { |stack| Rpn::Core.__todo( stack ) } ) # percent diff --git a/lib/language/operations.rb b/lib/language/operations.rb index 1ed5de1..32bf0e1 100644 --- a/lib/language/operations.rb +++ b/lib/language/operations.rb @@ -96,6 +96,37 @@ module Rpn stack << { type: :numeric, value: BigMath.sqrt( BigDecimal( args[0][:value] ), Rpn::Core.precision ) } end + + # rpn_square + def sq( stack ) + stack, args = Rpn::Core.stack_extract( stack, [%i[numeric]] ) + + stack << { type: :numeric, + value: args[0][:value] * args[0][:value] } + end + + # absolute value + def abs( stack ) + stack, args = Rpn::Core.stack_extract( stack, [%i[numeric]] ) + + stack << { type: :numeric, + value: args[0][:value].abs } + end + + # 1 if number at stack level 1 is > 0, 0 if == 0, -1 if <= 0 + def sign( stack ) + stack, args = Rpn::Core.stack_extract( stack, [%i[numeric]] ) + value = if args[0][:value].positive? + 1 + elsif args[0][:value].negative? + -1 + else + 0 + end + + stack << { type: :numeric, + value: value } + end end end end