digraphs and hooks

db4
Alex Chapman 2008-03-08 10:05:33 +11:00
parent 1af5a9f92c
commit cdcc101270
3 changed files with 47 additions and 0 deletions

View File

@ -1,3 +1,5 @@
! Copyright (C) 2008 Alex Chapman
! See http://factorcode.org/license.txt for BSD license.
USING: accessors assocs kernel new-slots sequences vectors ;
IN: digraphs
@ -43,3 +45,6 @@ DEFER: (topological-sort)
: topological-sort ( digraph -- seq )
dup clone V{ } clone spin
[ drop (topological-sort) ] assoc-each drop reverse ;
: topological-sorted-values ( digraph -- seq )
dup topological-sort swap [ at value>> ] curry map ;

View File

@ -0,0 +1,14 @@
USING: hooks kernel tools.test ;
IN: hooks.tests
SYMBOL: test-hook
test-hook reset-hook
: add-test-hook test-hook add-hook ;
[ ] [ test-hook call-hook ] unit-test
[ "op called" ] [ "op" [ "op called" ] add-test-hook test-hook call-hook ] unit-test
[ "first called" "second called" ] [
test-hook reset-hook
"second op" [ "second called" ] add-test-hook
"first op" [ "first called" ] add-test-hook
test-hook call-hook
] unit-test

28
extra/hooks/hooks.factor Normal file
View File

@ -0,0 +1,28 @@
! Copyright (C) 2008 Alex Chapman
! See http://factorcode.org/license.txt for BSD license.
USING: assocs digraphs kernel namespaces sequences ;
IN: hooks
: hooks ( -- hooks )
\ hooks global [ drop H{ } clone ] cache ;
: hook-graph ( hook -- graph )
hooks [ drop <digraph> ] cache ;
: reset-hook ( hook -- )
<digraph> swap hooks set-at ;
: add-hook ( key quot hook -- )
#! hook should be a symbol. Note that symbols with the same name but
#! different vocab are not equal
hook-graph add-vertex ;
: before ( key1 key2 hook -- )
hook-graph add-edge ;
: after ( key1 key2 hook -- )
swapd before ;
: call-hook ( hook -- )
hook-graph topological-sorted-values [ call ] each ;