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
    {
    and
    }
    , then use
    EXECUTE
    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 ;
    	
    	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 of 
    HOW-ARE
    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: The Data Section