如何在Prolog的列表中加倍偶数? 例如:
X = [1,2,3,5,4]
结果应为:
X = [1,2,2,3,5,4,4]
谢谢!
答案 0 :(得分:2)
基于iwhen/2
,
首先定义
reified test predicate eveninteger_t/2
:
eveninteger_t(I, T) :-
iwhen(nonvar(I), ( 0 is I mod 2 -> T = true ; T = false )).
oddinteger_t(I, T) :- % defined for the sake of completeness
iwhen(nonvar(I), ( 1 is I mod 2 -> T = true ; T = false )).
然后,结合if_/3
定义integers_evendups/2
,如此:
integers_evendups([], []).
integers_evendups([X|Xs], [X|Zs1]) :-
if_(evenintegers_t(X), Zs1 = [X|Zs0], Zs1 = Zs0),
integers_evendups(Xs, Zs0).
以下是您在问题中提供的查询:
?- Xs = [1,2,3,5,4], integers_evendups(Xs,Zs). Xs = [1, 2, 3,5, 4 ], Zs = [1,2,2,3,5,4,4].
根据if_//3
,定义dcg evenintegerdups//1
:
evenintegerdups([]) -->
[].
evenintegerdups([X|Xs]) -->
if_(eveninteger_t(X), [X,X], [X]),
evenintegerdups(Xs).
使用meta-predicate foldl/4
和lambdas,代码变得更短:
:- use_module(library(lambda)).
evenintegerdups(Xs) -->
foldl(\X^if_(eveninteger_t(X),[X,X],[X]),Xs).
答案 1 :(得分:1)
即使检查可能会做得更好,但它有点工作。
even(N) :-
N mod 2 =:= 0.
doubleeven([],[]).
doubleeven([H|T], [H,H|Z]) :-
even(H),
!,
doubleeven(T,Z).
doubleeven([H|T], [H|Z]) :-
doubleeven(T,Z).