Deferred Words
Often, you know how to use a word X within word Y, but want to defer defining X for later or maybe want to use a variety of versions of X such as X1, X2.
DEFER. For example, to create a blank word
XX, we do the following:
defer xxYou can use the word
XXanywhere subsequently. To put in some functionality, use
AS. The behaviour can also be changed subsequently at any time using
AS.
: x2 "pug!" . ; ' x2 as xx xx pug! ok
Quiz
Question 1
Before putting in some functionality intoXX. What does
DEFER XXdo? Check your answer using
SEE.
see defer [0] Literal XT(2c9c9c76) [1] CREATE [2] , [3] DOES> [3.0] @ [3.1] EXECUTE
DEFERputs an XT into the deferred word's data section. If the deferred word is called before given any functionality, that XT will be executed instead. The XT, when executed, will print
Error: DEFER not setand then halt the program.
Question 2
What happens if we runXXbefore it is given any functionality?
Error: DEFER not setwill be printed. Then, the program ends.
Question 3
: compose ( xt xt -- xt ) { f g } [: f execute g execute ;] ;Rewrite
COMPOSEwithout using local variables or local functions. Use
DEFERinstead.
defer f defer g : compose ( -- xt ) [: f g ;] ; ' sin as f ' cos as g 0 compose execute . \ 0 sin cos . => 1.0 ' dup as f ' * as g 2 compose execute . \ 2 dup * => 4