Local Words
It would be helpful to let local variables create local words. So, instead of being put on the stack like a local variable, local words will run. There are two ways to do this in Smojo:
{ and }, then use
EXECUTEto run it as needed.
~to convert the XT to a local word instead so that it is run when called. This is the preferred method.
Example 1
: make-greeting ( "greeting" -- xt ) { g } [: g . ;] ;
"Hello Sam!" make-greeting dup
: how-are { xt } "I would like to say " . xt execute ;
how-are
I would like to say Hello Sam! ok
: how-are ~ { fn } "I say: " . fn ;
how-are
I say: Hello Sam! ok
Example 2
: xx
[: "hello" . ;] ~ { f }
f f f
;
xx
hello hello hello ok
Quiz
Question 1
Write a version ofHOW-AREthat does not use either local variables or local words.
: make-greeting ( "greeting" -- xt ) { g } [: g . ;] ;
: how-are
"I say:" .
execute
;
"Hello Sam!" make-greeting
how-are \ I say: Hello Sam!
Question 2
Write a wordFIND-MAX ( xt a b -- v )that takes a XT and two values as arguments. The XT is a single-value function of the form f(x). The word should return the maximum value between f(a) and f(b).
: find-max ( xt a b -- v )
>R >R ~ { f }
R> f R> f
max
;
: 1/ 1 swap /. ;
' 1/ 4 5 find-max . \ 0.25
