: max over over < if swap else then drop ;
Not using any type of if/branching/skip instruction it becomes more interesting. Using abs is one possibility http://www.retroprogramming.com/2009/06/implement-min-in-forth-without.html but abs is implemented often by branching (?) and isn't a very primitive first forth word. Instead one can use the fact that conditional less than "<" return 0 if false and -1 otherwise...
Using only simple operators I came up with this, it's kind of overly long but...
: max over over < dup 1 + rot rot * negate rot rot * + ;
3 4 max .
-> 4
4 3 max .
-> 4
I guess one could use < to implement abs similarly and use the simplier definition in the link above, but abs becomes:
: abs dup 0 < 2 * 1 + * ;
77 3 - abs .
-> 74
3 77 - abs .
-> 74
--
.sigh
ok, so then using this abs which isn't too fanicful define min instead (max require an swap somewhere)
: min over over - abs - + 2 / ;
3 4 min .
-> 3
4 3 min .
-> 3
.sigh
No comments:
Post a Comment