rpl.rb/lib/core/branch.rb

53 lines
1.7 KiB
Ruby
Raw Normal View History

2021-12-07 16:09:17 +01:00
# frozen_string_literal: true
2021-11-24 16:34:13 +01:00
module Rpl
2021-12-07 15:50:58 +01:00
module Lang
module Core
module_function
2021-11-24 16:34:13 +01:00
2021-12-09 16:31:29 +01:00
# ( x prg -- … ) run PRG X times putting i(counter) on the stack before each run
def times( stack, dictionary )
2022-02-08 15:45:36 +01:00
stack, args = Rpl::Lang.stack_extract( stack, [:any, %i[numeric]] )
2021-12-09 16:31:29 +01:00
args[1][:value].to_i.times do |i|
2022-02-09 16:29:01 +01:00
counter = { value: BigDecimal( i, Rpl::Lang.precision ), type: :numeric, base: 10 }
2021-12-09 16:31:29 +01:00
stack << counter << args[0]
stack, dictionary = Rpl::Lang::Core.eval( stack, dictionary )
end
[stack, dictionary]
end
# ( x y prg -- … ) run PRG (Y - X) times putting i(counter) on the stack before each run
def loop( stack, dictionary )
2022-02-08 15:45:36 +01:00
stack, args = Rpl::Lang.stack_extract( stack, [:any, %i[numeric], %i[numeric]] )
2021-12-09 16:31:29 +01:00
((args[2][:value].to_i)..(args[1][:value].to_i)).each do |i|
2022-02-09 16:29:01 +01:00
counter = { value: BigDecimal( i, Rpl::Lang.precision ), type: :numeric, base: 10 }
2021-12-09 16:31:29 +01:00
stack << counter << args[0]
stack, dictionary = Rpl::Lang::Core.eval( stack, dictionary )
end
[stack, dictionary]
end
2021-12-07 15:50:58 +01:00
# similar to if-then-else-end, <test-instruction> <true-instruction> <false-instruction> ifte
def ifte( stack, dictionary )
2022-02-08 15:45:36 +01:00
stack, args = Rpl::Lang.stack_extract( stack, [:any, :any, %i[boolean]] )
2021-11-24 16:34:13 +01:00
2021-12-07 15:50:58 +01:00
stack << args[ args[2][:value] ? 1 : 0 ]
2021-11-24 16:34:13 +01:00
2021-12-07 15:50:58 +01:00
Rpl::Lang::Core.eval( stack, dictionary )
end
2021-12-08 13:15:33 +01:00
2021-12-08 13:46:06 +01:00
# Implemented in Rpl
2021-12-08 13:15:33 +01:00
# similar to if-then-end, <test-instruction> <true-instruction> ift
def ift( stack, dictionary )
2022-02-08 15:45:36 +01:00
Rpl::Lang.eval( stack, dictionary, '« nop » ifte' )
2021-12-08 13:15:33 +01:00
end
2021-11-24 16:34:13 +01:00
end
end
end