Node:CREATE..DOES> applications, Next:, Previous:User-defined Defining Words, Up:User-defined Defining Words



Applications of CREATE..DOES>

You may wonder how to use this feature. Here are some usage patterns:

When you see a sequence of code occurring several times, and you can identify a meaning, you will factor it out as a colon definition. When you see similar colon definitions, you can factor them using CREATE..DOES>. E.g., an assembler usually defines several words that look very similar:

: ori, ( reg-target reg-source n -- )
    0 asm-reg-reg-imm ;
: andi, ( reg-target reg-source n -- )
    1 asm-reg-reg-imm ;

This could be factored with:

: reg-reg-imm ( op-code -- )
    CREATE ,
DOES> ( reg-target reg-source n -- )
    @ asm-reg-reg-imm ;

0 reg-reg-imm ori,
1 reg-reg-imm andi,

Another view of CREATE..DOES> is to consider it as a crude way to supply a part of the parameters for a word (known as currying in the functional language community). E.g., + needs two parameters. Creating versions of + with one parameter fixed can be done like this:

: curry+ ( n1 "name" -- )
    CREATE ,
DOES> ( n2 -- n1+n2 )
    @ + ;

 3 curry+ 3+
-2 curry+ 2-