Prolog - 确定列表中的重复数量并将数量转换为指数
Prolog - determine amount of duplicates in list and turn the amount into an exponent
我想计算重复项的数量并将其删除,并将重复项的数量打印为指数。非重复项保持不变。例如:
exponent([2, 2, 3, 5, 5], X).
X = [2^2, 3, 5^2]
和
exponent([2, 2, 2, 2, 2, 2, 2], X).
X = [2^7]
通过 "eating" 通过您的列表并同时以典型的 Prologish 自上而下方式构建结果很容易:
exponent( [X | XS], Ex ):-
exponent( 1, X, XS, Ex ).
等等,什么?我们还没有说任何具体的事情......除了我们现在已经看到 one X
。那么,
exponent( I, X, [Y | XS], Ex ):-
( X =:= Y
-> I1 is ....,
exponent(I1, X, XS, Ex) % right? we go on 'eating up' the input
;
Ex = [ (I,X) | Ex2 ], % intentionally 'wrong' output
exponent( 1, ........ )
).
看到了吗?
当然,缺少基本案例,但您可以从这里开始!
我想计算重复项的数量并将其删除,并将重复项的数量打印为指数。非重复项保持不变。例如:
exponent([2, 2, 3, 5, 5], X).
X = [2^2, 3, 5^2]
和
exponent([2, 2, 2, 2, 2, 2, 2], X).
X = [2^7]
通过 "eating" 通过您的列表并同时以典型的 Prologish 自上而下方式构建结果很容易:
exponent( [X | XS], Ex ):-
exponent( 1, X, XS, Ex ).
等等,什么?我们还没有说任何具体的事情......除了我们现在已经看到 one X
。那么,
exponent( I, X, [Y | XS], Ex ):-
( X =:= Y
-> I1 is ....,
exponent(I1, X, XS, Ex) % right? we go on 'eating up' the input
;
Ex = [ (I,X) | Ex2 ], % intentionally 'wrong' output
exponent( 1, ........ )
).
看到了吗?
当然,缺少基本案例,但您可以从这里开始!