-USING: kernel accessors multi-methods locals combinators math arrays
+USING: kernel accessors locals combinators math arrays
 assocs namespaces sequences ;
 IN: persistent-heaps
 ! These are minheaps


GENERIC: sift-down ( value prio left right -- heap )

METHOD: sift-down { empty-heap empty-heap } <branch> ;

METHOD: sift-down { singleton-heap empty-heap }
    3dup drop prio>> <= [ <branch> ] [
        drop -rot [ [ value>> ] [ prio>> ] bi ] 2dip
        <singleton-heap> <persistent-heap> <branch>
    ] if ;

:: reroot-left ( value prio left right -- heap )
    left value>> left prio>>

    value prio right left>> right right>> sift-down
    <branch> ;

M: branch sift-down
    3dup [ prio>> <= ] both-with? [ <branch> ] [
        2dup [ prio>> ] bi@ <= [ reroot-left ] [ reroot-right ] if
    ] if ;
