大家好,我正在尝试在 prolog 中编写这个公式,感谢您的帮助 :)

Hi everyone, I'm trying to code this formula in prolog, any help is appreciated :)

我正在尝试在序言中编写此公式:

"str" 是作为字符串输入的数字 "base" 是输入数字的基数。

结果是,

(基数)^0 * str[len-1] + (基数)^1 * str[len-2] + (基数)^2 * str[len-3] + ...

我是 prolog 的新手,我现在有这个:

calc([],_,0):-  !.
calc([H|T],Base,Res):-
    length([H|T],Long),
    Long >= 0,
    Size is Long - 1,
    power(Base , Size, Res),
    Res1 is Res * H,
    calc(T,Base,Res1).

但它不能正常工作我昨天花了很多时间试图解决这个问题,但没有成功。

感谢任何帮助:)。

你可以这样做:

value(String, Base, Value) :-
    string_chars(String, Digits),
    value(Digits, Base, 0, Value).

value([], _, Value, Value).
value([Digit|Digits], Base, Accumulator, Value) :-
     atoi(Digit, Number),
     NewAccumulator is Base*Accumulator + Number,
     value(Digits, Base, NewAccumulator, Value).

atoi(Char, Int) :-  % convert ASCII code to integer
    char_code(Char, Code) ,
    Int is Code - 48.

预定义谓词 string_chars 将字符串转换为字符列表:

?- string_chars("1101", Chars).
Chars = ['1', '1', '0', '1'].

谓词atoi将表示数字的字符转换为相应的整数:

?- atoi('3', Integer).
Integer = 3.

假设[1,1,0,1]是一个整数列表(表示基数2中的一个数),它对应的值在基数10[=38中=] 可以计算如下:

Digit Accumulator
-     0
1     2 x 0 + 1 = 1
1     2 x 1 + 1 = 3
0     2 x 3 + 0 = 6
1     2 x 6 + 1 = 13

这里有一些例子:

?- value("1101", 2, V).
V = 13.

?- value("1201", 3, V).
V = 46.

替代方案假设你已经有一个表示数字数字的整数列表,方案更简单:

value_integers(Digits, Base, Value) :-
    value_integers(Digits, Base, 0, Value).

value_integers([], _, Value, Value).
value_integers([Digit|Digits], Base, Accumulator, Value) :-
     NewAccumulator is Base*Accumulator + Digit,
     value_integers(Digits, Base, NewAccumulator, Value).

这里有一些例子:

?- value_integers([1,1,0,1], 2, Value).
Value = 13.

?- value_integers([1,2,0,1], 3, Value).
Value = 46.

?- value_integers([1,2,0,1], 10, Value).
Value = 1201.