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:

  • Bind the XT to a local variable as usual using
    , then use
    to run it as needed.
  • Use the word
    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 ;
    	I would like to say Hello Sam! ok
    	: how-are ~ { fn } "I say: " . fn ;
    	I say: Hello Sam! ok
    Example 2
    	: xx 	
    		[: "hello" . ;] ~ { f }
    		f f f 
    	hello hello hello ok


    Question 1

    Write a version of 
    that does not use either local variables or local words.

    Question 2

    Write a word 
    FIND-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).

    Next: Higher Order Functions