我是Prolog的新手。
我在大学课堂上听到了令人讨厌的Prolog练习。
我需要编写一个获得prolog术语和基础的程序,然后将该术语中的所有整数转换为此基数。
例如:
?- change_base(g(7), 2, Result).
Result = g(111).
我写了这个程序,但似乎我得到了一个无限循环:
change_base([], _, []).
change_base([X|Xs], Base, [X1|NewTermAsList]) :-
integer(X), !, (calc_base(X,Base,X1), change_base(Xs,Base,NewTermAsList)).
change_base([X|Xs], Base, [X1|NewTermAsList]) :-
change_base(Xs,Base,NewTermAsList).
change_base(Term, Base, NewTerm) :-
Term =..TermAsList, change_base(TermAsList, Base, NewTermAsList),
NewTerm =..NewTermAsList.
calc_base(0, Base, 0).
calc_base(Num, Base, Res) :-
Num > 0, Mod is Num mod Base, Div is Num // Base,
calc_base(Div, Base, Res1), Res is Res1 * 10 + Mod.
我正在使用Amzi!序言
谢谢,
答案 0 :(得分:0)
重写修复问题的代码:
change_base(Term, Base, NewTerm) :-
nonvar(Term),
Term =.. Arguments,
change_arguments_base(Arguments, Base, NewArguments),
NewTerm =.. NewArguments.
change_arguments_base([], _, []).
change_arguments_base([Argument| Arguments], Base, [NewArgument| NewArguments]) :-
( integer(Argument) ->
calc_base(Argument, Base, NewArgument)
; compound(Argument) ->
change_base(Argument, Base, NewArgument)
; NewArgument = Argument
),
change_arguments_base(Arguments, Base, NewArguments).
calc_base(0, _, 0) :-
!.
calc_base(Num, Base, Res) :-
Num > 0, Mod is Num mod Base, Div is Num // Base,
calc_base(Div, Base, Res1), Res is Res1 * 10 + Mod.
样品电话:
?- change_base(g(7,4), 2, Result).
Result = g(111, 100).
?- change_base(4, 2, Result).
Result = 100.
?- change_base(4.7, 2, Result).
Result = 4.7.