Paste: amb

Author: Jon Harper
Mode: factor
Date: Mon, 7 Dec 2009 08:41:08
Plain Text |
! See http://rosettacode.org/wiki/Amb

! Largely inspired by (in french)
! http://www.rfc1149.net/inf355/2009/05/29/corrige-du-tp-scheme-2/

! Copyright (C) 2009 Jon Harper
! See http://factorcode.org/license.txt for BSD license.
USING: continuations fry kernel locals namespaces prettyprint
sequences ;
IN: amb

: words ( -- seq ) {
    { "the" "that" "a" } 
    { "frog" "elephant" "thing" } 
    { "walked" "treaded" "grows" }
    { "slowly" "quickly"  }
} ;
: letters-match? ( str1 str2 -- ? )
    [ last ] [ first ] bi* = ;
: sentence-match? ( seq -- ? )
    dup rest t [ letters-match? and ] 2reduce ;

SYMBOL: amb-next

: amb-init ( -- ) [ amb-next set f ] callcc1
[ "Alternatives exhausted" throw ] when ;
: next-amb ( -- next ) amb-next get continue ;

:: amb ( alternatives -- next )
    [
       :> escape
       amb-next get :> old-amb-next
       alternatives 
       [ 
         '[
            amb-next set
            _ escape continue-with
          ]  callcc0
       ] each
       t old-amb-next continue-with
    ] callcc1 ;

: search ( -- ) 
    amb-init
    words [ amb ] map
    dup sentence-match?
    [ " " join ] [ drop next-amb ] if . ;

MAIN: search

Annotation: Use factor's library amb

Author: jon
Mode: factor
Date: Wed, 9 Dec 2009 02:45:14
Plain Text |
! Copyright (C) 2009 Jon Harper
! See http://factorcode.org/license.txt for BSD license.
USING: backtrack continuations fry generalizations kernel
locals prettyprint sequences ;
IN: amb
: words ( -- seq ) {
    { "the" "that" "a" } 
    { "frog" "elephant" "thing" } 
    { "walked" "treaded" "grows" }
    { "slowly" "quickly"  }
} ; inline
: letters-match? ( str1 str2 -- ? )
    [ last ] [ first ] bi* = ;
: sentence-match? ( seq -- ? )
    dup rest t [ letters-match? and ] 2reduce ;
 
MACRO:: macro-map ( seq macro -- )
    seq length :> tmp
    seq [ ] each
    [ macro tmp napply tmp narray ] tmp ncurry ;
 
: search ( -- ) 
    words [ amb ] macro-map
    dup sentence-match?
    [ " " join ] [ fail ] if . ;
 
MAIN: search

Annotation: Simpler version

Author: Sam
Mode: factor
Date: Wed, 9 Dec 2009 12:52:12
Plain Text |
! Copyright (C) 2009 Jon Harper
! See http://factorcode.org/license.txt for BSD license.
USING: backtrack continuations kernel prettyprint sequences ;
IN: amb

CONSTANT: words {
    { "the" "that" "a" }
    { "frog" "elephant" "thing" }
    { "walked" "treaded" "grows" }
    { "slowly" "quickly"  }
}

: letters-match? ( str1 str2 -- ? ) [ last ] [ first ] bi* = ;

: sentence-match? ( seq -- ? ) dup rest [ letters-match? ] 2all? ;

: select ( seq -- seq' )
    dup empty? [ unclip [ select ] [ amb-lazy ] bi* prefix ] unless ;

: search ( -- )
    words select dup sentence-match? [ " " join ] [ fail ] if . ;

MAIN: search

New Annotation

Summary:
Author:
Mode:
Body: