1 ! Copyright (C) 2008, 2010 Slava Pestov.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel math ranges math.order math.parser
5 IN: benchmark.binary-trees
7 TUPLE: tree-node item left right ;
9 C: <tree-node> tree-node
11 : bottom-up-tree ( item depth -- tree )
15 [ [ 2 * 1 - ] dip bottom-up-tree ]
16 [ [ 2 * ] dip bottom-up-tree ] 2tri
19 ] if <tree-node> ; inline recursive
21 GENERIC: item-check ( node -- n )
23 M: tree-node item-check
24 [ item>> ] [ left>> ] [ right>> ] tri [ item-check ] bi@ - + ;
26 M: f item-check drop 0 ;
30 : stretch-tree ( max-depth -- )
31 1 + 0 over bottom-up-tree item-check
32 [ "stretch tree of depth " write number>string write ]
33 [ "\t check: " write number>string print ] bi* ; inline
35 :: long-lived-tree ( max-depth -- )
36 0 max-depth bottom-up-tree
38 min-depth max-depth 2 <range> [| depth |
39 max-depth depth - min-depth + 2^ [
42 [ depth bottom-up-tree item-check + ] bi@
45 [ 2 * number>string write ] bi
46 "\t trees of depth " write depth number>string write
47 "\t check: " write number>string print
50 "long lived tree of depth " write max-depth number>string write
51 "\t check: " write item-check number>string print ; inline
53 : binary-trees ( n -- )
54 min-depth 2 + max [ stretch-tree ] [ long-lived-tree ] bi ; inline
56 : binary-trees-benchmark ( -- )
59 MAIN: binary-trees-benchmark