From 206f49598e415ba44be1eb60e36ca2a45e5258cd Mon Sep 17 00:00:00 2001 From: Simon Forman Date: Sat, 20 Jul 2019 19:26:11 -0700 Subject: [PATCH] Add mod, gcd, and hypot; term_expansion for math ops. --- thun/defs.txt | 4 +++- thun/thun.pl | 17 +++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/thun/defs.txt b/thun/defs.txt index 741ba8a..ab0ad81 100644 --- a/thun/defs.txt +++ b/thun/defs.txt @@ -9,7 +9,7 @@ average == [sum 1.0 *] [size] cleave / b == [i] dip i binary == unary popd ccons == cons cons -cleave == fork [popd] dip +cleave == fork popdd codireco == cons dip rest cons dinfrirst == dip infrst disenstacken == ? [uncons ?] loop pop @@ -22,7 +22,9 @@ enstacken == stack [clear] dip flatten == [] swap [concat] step fork == [i] app2 fourth == rest third +gcd == true [tuck mod dup 0 >] loop pop grba == [stack popd] dip +hypot == [sqr] ii + sqrt ifte == [nullary] dipd swap branch ii == [dip] dupdip i infra == swons swaack [i] dip swaack diff --git a/thun/thun.pl b/thun/thun.pl index 2a14707..0553a71 100644 --- a/thun/thun.pl +++ b/thun/thun.pl @@ -44,6 +44,14 @@ term_expansion(comparison_operator(X), (func(X, [A, B|S], [C|S]) :- term_expansion(comparison_operator(X, Y), (func(X, [A, B|S], [C|S]) :- F =.. [Y, B, A], catch((F -> C=true ; C=false), _, C=F))). +% Likewise for math operators, try to evaluate, otherwise use the symbolic form. + +term_expansion(math_operator(X), (func(X, [A, B|S], [C|S]) :- + F =.. [X, B, A], catch(C is F, _, C=F))). + +term_expansion(math_operator(X, Y), (func(X, [A, B|S], [C|S]) :- + F =.. [Y, B, A], catch(C is F, _, C=F))). + /* An entry point. @@ -128,10 +136,11 @@ func(dup, [A|S], [A, A|S]). func(pop, [_|S], S ). % Symbolic math. Compute the answer, or derivative, or whatever, later. -func(+, [A, B|S], [B + A|S]). -func(-, [A, B|S], [B - A|S]). -func(*, [A, B|S], [B * A|S]). -func(/, [A, B|S], [B / A|S]). +math_operator(+). +math_operator(-). +math_operator(*). +math_operator(/). +math_operator(mod). % Attempt to calculate the value of a symbolic math expression. func(calc, [A|S], [B|S]) :- B is A.