# Paste: Contuation passing style in Factor

Author: Capital factor Tue, 12 Sep 2023 08:03:01
Plain Text |
```! Copyright (C) 2023 Your name.
USING: kernel math ;
IN: capital.cps

: dip& ( x y quot quot -- )
[ dip ] dip call ; inline

: drop& ( x quot -- )
[ drop ] dip call ; inline

: *& ( x y quot -- )
[ * ] dip call ; inline

: -& ( x y  quot -- )
[ - ] dip call ; inline

: swap& ( x y quot -- )
[ swap ] dip call ; inline

: over& ( x y quot -- )
[ over ] dip call ; inline

: +& ( x y quot -- )
[ + ] dip call ; inline

: nip& ( x y quot -- )
[ nip ] dip call ; inline

: =& ( x y quot -- )
[ = ] dip call ; inline

: dup& ( x quot -- )
[ dup ] dip call ; inline

: times& ( x quot quot -- )
[ times ] dip call ; inline

! Factor can apparently inline and optimize
! Continuation passing style into the same performance
! as the direct style.
: factorial ( x -- x! )
dup 0 = [ drop 1 ]
[ dup 1 - factorial * ] if ;

: factorial& ( x quot: ( x -- ) -- )
[
[
0 [
[ [ 1 ] drop& ]
[ [ 1 [ [ [ ] *& ] factorial& ] -& ] dup& ] if
] =&
] dup&
] dip call ; inline recursive

: fib ( x -- x )
[ 1 0 ] dip [ over + swap ] times nip ;

: fib& ( x quot -- )
[
[ 1 0 ]
[
[ [ [ [ ] swap& ] &+ ] over& ]
[ [ ] nip& ] times&
] dip&
] dip call ; inline
```