How to reify Prolog's backtracking state to perform the same task as “lazy seq” from Clojure?

前端 未结 2 660
南方客
南方客 2021-01-12 10:10

Here is a quicksort algorithm for numbers written in Clojure. It is basically the quicksort algorithm found in \"The Joy of Clojure\", 2nd edition, page 133. I modi

2条回答
  •  Happy的楠姐
    2021-01-12 10:49

    This isn't standardized, but a number of Prologs nowadays provide facilities to maintain and manipulate multiple independent backtrackable states, often known as engines.

    For example, using the corresponding primitives in ECLiPSe, you might write

    init(Vars, Goal, Engine) :-
        engine_create(Engine, []),
        engine_resume(Engine, (true;Goal,yield(Vars,Cont),Cont), true).
    
    more(Engine, Vars) :-
        engine_resume(Engine, fail, yielded(Vars)).
    

    and use that as follows (with qsort/2 as defined by you)

    ?- init(X, qsort(X,[3,2,1]), Eng),
       more(Eng, X1),
       more(Eng, X2),
       more(Eng, X3).
    
    X = X
    Eng = $&(engine,"9wwqv3")
    X1 = 1
    X2 = 2
    X3 = 3
    Yes (0.00s cpu)
    

    Here, the variable Eng is bound to an opaque engine-handle. This engine executes a nondeterministic goal that yields a new solution to the caller every time it is resumed and instructed to backtrack.

提交回复
热议问题