prolog - Swapping a specific number in list 1 with a specific number in list 2 -
i have been brushing on prolog recently. kind of enjoy coming random problems try , solve , working them out. 1 quite tough though, , i'm not 1 give on problem have set out solve.
the problem: want make predicate have 2 predetermined lists, 2 numbers swap, , output lists after swapping done.
further explanation: made little harder on myself wanting find specific unique number list 1, , swapping specific unique number list 2 if have 2 lists... [7,2,7,8,5], , [1,2,3,8,7,9,8], , give predicate 2 numbers(lets 8 , 7), number 8 , number 7 swapped between lists if , if number 8 in first list , number 7 in second list. (it disregard 8 in second list , 7 in first list).
sample query expected answer:
?- bothswap([7,2,7,8,5],[1,2,3,8,7,9,8],8,7,x,y). x = [7,2,7,7,5], y = [1,2,3,8,8,9,8].
i kind of got stuck @ point:
bothswap([],l2,n1,n2,[],l2). bothswap(l1,[],n1,n2,l1,[]). bothswap([h1|t1],[h2|t2],n1,n2,x,y) :- h1 == n1, h2 == n2, bothswap(t1,t2,n1,n2,d1,d2), append(d1,[h2],x), append(d2,[h1],y). bothswap([h1|t1],[h2|t2],n1,n2,x,y) :- h1 == n1, h2 =\= n2, bothswap([h1|t1],t2,n1,n2,d1,d2). bothswap([h1|t1],[h2|t2],n1,n2,x,y) :- h1 =\= n1, h2 == n2, bothswap(t1,[h2|t2],n1,n2,d1,d2).
any bright minds out there willing tackle problem me? :)
let's start, mean swapping.
swap(x0,x, s0,s) :- if_(x0 = s0, s = x, s = s0). bothswap0(xs0, ys0, x0,x, xs,ys) :- maplist(swap(x0,x), xs0,xs), maplist(swap(x,x0), ys0,ys). if_( c_1, then_0, else_0) :- call(c_1, truth), functor(truth,_,0), % safety check ( truth == true -> then_0 ; truth == false, else_0 ). =(x, y, r) :- x == y, !, r = true. =(x, y, r) :- ?=(x, y), !, r = false. % syntactically different =(x, y, r) :- x \= y, !, r = false. % semantically different =(x, y, r) :- r == true, !, x = y. =(x, x, true). =(x, y, false) :- dif(x, y).
now wanted particular condition - not clear how apply it. see 2 interpretations:
bothswap(xs0, ys0, x0,x, xs,ys) :- memberd(x0, xs0), memberd(x, ys0), maplist(swap(x0,x), xs0,xs), maplist(swap(x,x0), ys0,ys).
which means bothswap/6
fail should 2 elements not occur in respective list.
another interpretation might want otherwise lists remain same. express (in pure monotonic fashion):
bothswap(xs0, ys0, x0,x, xs,ys) :- if_( ( memberd_t(x0, xs0), memberd_t(x, ys0) ), ( maplist(swap(x0,x), xs0,xs), maplist(swap(x,x0), ys0,ys) ), ( xs0 = xs, ys0 = ys) ). memberd_t(e, xs, t) :- list_memberd(xs, e, t). list_memberd([], _, false). list_memberd([x|xs], e, t) :- if_(e = x, t = true, list_memberd(xs, e, t) ). ','( a_1, b_1, t) :- if_( a_1, call(b_1, t), t = false ).
Comments
Post a Comment