Prolog - 用 K 列出成员
Prolog - List Member with K
listMem(L, K, LK): LK is the list L with element K inserted in it somewhere.
我在编写这个函数时遇到了问题,但我的尝试是这样的:
我的想法是将 K 添加到 L,然后对其进行排序并检查排序是否与 LK 相同,不幸的是它效果不佳。我对附加谓词的使用有疑问。
listMem(L, K, LK) :- append(L, K, Y), sort(Y, LK).
因为您似乎忽略了函数和 Prolog 谓词之间的区别:
?- select(E, [a,b,c], L).
E = a,
L = [b, c] ;
E = b,
L = [a, c] ;
E = c,
L = [a, b] ;
false.
?- select(x, L, [a,b,c]).
L = [x, a, b, c] ;
L = [a, x, b, c] ;
L = [a, b, x, c] ;
L = [a, b, c, x] ;
false.
?- select(x, [a,b,c], L).
false.
从某种意义上说,"select" 作为一个词的含义比 select/3
少,但是,正如 CapelliC 指出的那样,您正在寻找的确实是 select/3
。您可以在任何 Prolog 教科书或 check out the library implementation of an open-source Prolog implementation.
中看到它是如何实现的
listMem(L, K, LK): LK is the list L with element K inserted in it somewhere.
我在编写这个函数时遇到了问题,但我的尝试是这样的: 我的想法是将 K 添加到 L,然后对其进行排序并检查排序是否与 LK 相同,不幸的是它效果不佳。我对附加谓词的使用有疑问。
listMem(L, K, LK) :- append(L, K, Y), sort(Y, LK).
因为您似乎忽略了函数和 Prolog 谓词之间的区别:
?- select(E, [a,b,c], L).
E = a,
L = [b, c] ;
E = b,
L = [a, c] ;
E = c,
L = [a, b] ;
false.
?- select(x, L, [a,b,c]).
L = [x, a, b, c] ;
L = [a, x, b, c] ;
L = [a, b, x, c] ;
L = [a, b, c, x] ;
false.
?- select(x, [a,b,c], L).
false.
从某种意义上说,"select" 作为一个词的含义比 select/3
少,但是,正如 CapelliC 指出的那样,您正在寻找的确实是 select/3
。您可以在任何 Prolog 教科书或 check out the library implementation of an open-source Prolog implementation.