From: Tim Vaughan Date: Tue, 26 Apr 2016 09:58:42 +0000 (+1200) Subject: Added MAX and MIN X-Git-Url: https://thelambdalab.xyz/gitweb/index.cgi?a=commitdiff_plain;h=aa56183a78faf9a661146353446af24fae716d92;p=forth.jl.git Added MAX and MIN --- diff --git a/src/forth.jl b/src/forth.jl index 11d0044..9c3f62e 100644 --- a/src/forth.jl +++ b/src/forth.jl @@ -844,6 +844,11 @@ EXECUTE = defPrimWord("EXECUTE", () -> begin return mem[reg.W] end) +type ParseError <: Exception + wordName::ASCIIString +end +Base.showerror(io::IO, ex::ParseError) = print(io, "Parse error at word: '$(ex.wordName)'.") + INTERPRET = defPrimWord("INTERPRET", () -> begin callPrim(mem[WORD]) @@ -881,8 +886,7 @@ INTERPRET = defPrimWord("INTERPRET", () -> begin callPrim(mem[NUMBER]) if popPS() != 0 - println("Parse error at word: '$wordName'") - return NEXT + throw(ParseError(wordName)) end if mem[STATE] == 0 @@ -979,7 +983,7 @@ function run(;initialize=true) global initialized, initFileName if !initialized && initialize if initFileName != nothing - print("Including definitions from $initFileName.") + print("Including definitions from $initFileName...") push!(sources, open(initFileName, "r")) initialized = true else @@ -1002,6 +1006,11 @@ function run(;initialize=true) showerror(STDOUT, ex) println() + while !isempty(sources) && currentSource() != STDIN + close(pop!(sources)) + end + + mem[STATE] = 0 mem[NUMTIB] = 0 reg.IP = QUIT + 1 jmp = NEXT diff --git a/src/lib.4th b/src/lib.4th index f4e9908..ae4e60e 100644 --- a/src/lib.4th +++ b/src/lib.4th @@ -2,13 +2,7 @@ : MOD /MOD DROP ; : */ * / ; -: '\n' 10 ; -: BL 32 ; - -: CR '\n' emit ; -: SPACE BL emit ; - -: NEGATE 0 swap - ; +: NEGATE 0 SWAP - ; : TRUE -1 ; : FALSE 0 ; @@ -18,6 +12,9 @@ : DEPTH PSP@ PSP0 @ - ; +: '\n' 10 ; +: BL 32 ; + : LITERAL IMMEDIATE ' LIT , , ; : ':' [ CHAR : ] LITERAL ; @@ -32,6 +29,9 @@ : '-' [ CHAR - ] LITERAL ; : '.' [ CHAR . ] LITERAL ; +: CR '\n' emit ; +: SPACE BL emit ; + : [COMPILE] IMMEDIATE WORD \ get the next word FIND \ find it in the dictionary @@ -170,12 +170,28 @@ : HEX ( -- ) 16 BASE ! ; ( Compute absolute value. ) -: ABS ( n -- m) +: ABS ( n -- |n| ) dup 0< if negate then ; +: MAX ( n m -- max ) + 2dup - 0< if + swap drop + else + drop + then +; + +: MIN ( n m -- max ) + 2dup - 0> if + swap drop + else + drop + then +; + ( PRINTING NUMBERS ---------------------------------------------------------------------- ) ( This is the underlying recursive definition of U. )