且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Prolog中将数字拆分为数字列表

更新时间:2023-02-11 17:03:03

可用的内置函数是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].