Paste: simple markov chain

Author: bb
Mode: factor
Date: Sat, 27 Dec 2008 06:54:57
Plain Text |
USING: splitting random-weighted grouping random fry hashtables ;

: <chain> ( -- chain ) H{ } ; ! not actually a tuple yet

: union-add ( seq seq -- seq )
    [ '[ swap _ at+ ] assoc-each ] keep ;

: add ( seq seq -- seq )
    [ '[ swap _ [ H{ } clone or union-add ] change-at ] assoc-each ] keep ;

: weighted-choice ( chain key -- elem )
    swap at dup [ >alist [ swap ] assoc-map random-weighted* ] [ ] if ;
    
: add-line ( chain line -- chain )
    " " split 2 clump 
    [ first2 1 swap associate swap associate add ] each ;

: sentence ( chain word -- response )
    tuck 1 -rot 
    [ dupd weighted-choice rot 1+ dup 15 < [ -rot ] dip dupd and ] [ dup ] [ 3drop ] produce
    " " join ;

New Annotation

Summary:
Author:
Mode:
Body: