Prolog substitution

前端 未结 5 1320
囚心锁ツ
囚心锁ツ 2021-01-22 21:32

How can I replace a list with another list that contain the variable to be replaced. for example

rep([x, d, e, z, x, z, p], [x=z, z=x, d=c], R).
R = [z, c, e, x,         


        
5条回答
  •  自闭症患者
    2021-01-22 21:35

    Here's how you could proceed using if_/3 and (=)/3.

    First, we try to find a single Key in a list of pairs K-V. An extra argument reifies search success.

    pairs_key_firstvalue_t([]       ,_  ,_    ,false).
    pairs_key_firstvalue_t([K-V|KVs],Key,Value,Truth) :-
       if_(K=Key,
           (V=Value, Truth=true),
           pairs_key_firstvalue_t(KVs,Key,Value,Truth)).
    

    Next, we need to handle "not found" cases:

    assoc_key_mapped(Assoc,Key,Value) :-
       if_(pairs_key_firstvalue_t(Assoc,Key,Value),
           true,
           Key=Value).
    

    Last, we put it all together using the meta-predicate maplist/3:

    ?- maplist(assoc_key_mapped([x-z,z-x,d-c]), [x,d,e,z,a,z,p], Rs).
    Rs = [z,c,e,x,a,x,p].                       % OK, succeeds deterministically
    

提交回复
热议问题