Prolog - 将数字合并为数字 [英] Prolog - merge digits to number

查看:62
本文介绍了Prolog - 将数字合并为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将数字列表合并为数字.

I want to merge list of digits to number.

[1,2,3] -> 123

[1,2,3] -> 123

我的谓词:

merge([X], X).
merge([H|T], X) :- 
   merge(T, X1),
   X is X1 + H * 10.

但现在我得到:[1,2,3] -> 33

But now I get: [1,2,3] -> 33

推荐答案

数学已关闭.你的规则是你必须将 H 乘以 10.但实际上 H 需要乘以 10 的幂,相当于它在列表中的位置.这将是 1 的 * 100 和 2 的 * 10.你现在得到的是: 10*1 + 10*2 + 3 是 33.问题是您的递归子句不知道数字所在的数字位置".

The math is off. You're rule says you have to multiply H by 10. But really H needs to be multiplied by a power of 10 equivalent to its position in the list. That would be * 100 for the 1, and * 10 for the 2. What you get now is: 10*1 + 10*2 + 3 which is 33. The problem is that your recursive clause doesn't know what numeric "place" the digit is in.

如果您以不同的方式构造代码并使用累加器,则可以简化问题.此外,通过使用 CLP(FD) 并对数字应用一些约束,您可以获得更通用的解决方案.

If you structure the code differently, and use an accumulator, you can simplify the problem. Also, by using CLP(FD) and applying some constraints on the digits, you can have a more general solution.

:- use_module(library(clpfd)).

digits_number(Digits, X) :-
    digits_number(Digits, 0, X).

digits_number([], S, S).
digits_number([D|Ds], S, X) :-
    D in 0..9,
    S1 #= S*10 + D,
    digits_number(Ds, S1, X).

?- digits_number([1,2,3], X).
X = 123

?- digits_number(L, 123).
L = [1, 2, 3] ;
L = [0, 1, 2, 3] ;
L = [0, 0, 1, 2, 3] ;
L = [0, 0, 0, 1, 2, 3] ;
L = [0, 0, 0, 0, 1, 2, 3]
...

?-

这篇关于Prolog - 将数字合并为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆