在Prolog中将数字拆分为数字列表 [英] Split a number into a list of digits in Prolog
本文介绍了在Prolog中将数字拆分为数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试使用Prolog将数字分成列表时遇到麻烦,例如123456变为[1,2,3,4,5,6]
.
I've been having trouble trying to split numbers into lists using Prolog, e.g. 123456 becomes [1,2,3,4,5,6]
.
您能帮我解决一下吗?
推荐答案
可用的内置函数是ISO标准:
the builtins available are ISO standard:
?- number_codes(123456,X),format('~s',[X]).
123456
X = [49, 50, 51, 52, 53, 54].
?- number_chars(123456,X),format('~s',[X]).
123456
X = ['1', '2', '3', '4', '5', '6'].
我还有一些为解释器开发的非常旧代码.必须将:=
重命名为is
才能与标准Prologs一起运行.但是,那么最好从内置函数之上为您服务...
I also have some very old code I developed for my interpreter. :=
must be renamed is
to run with standard Prologs. But then you are best served from above builtins...
itoa(N, S) :-
N < 0, !,
NN := 0 - N,
iptoa(NN, SR, _),
reverse(SR, SN),
append("-", SN, S).
itoa(N, S) :-
iptoa(N, SR, _),
reverse(SR, S).
iptoa(V, [C], 1) :-
V < 10, !,
C := V + 48.
iptoa(V, [C|S], Y) :-
M := V / 10,
iptoa(M, S, X),
Y := X * 10,
C := V - M * 10 + 48.
编辑,此处是获得号码所需的附加呼叫:
edit here the additional call required to get numbers:
?- number_codes(123456,X), maplist(plus(48),Y,X).
X = [49, 50, 51, 52, 53, 54],
Y = [1, 2, 3, 4, 5, 6].
这篇关于在Prolog中将数字拆分为数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文