Divide a number into a list of numbers in Prolog

I am having trouble trying to split numbers into lists using Prolog, for example. 123456 becomes [1,2,3,4,5,6].

Could you help me figure out how to do this?

+5
source share
2 answers

built-in built-in ISO standards:

?- 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'].

I also have very old code that I developed for my translator. :=must be renamed isto run with standard prologs. But then you are best served on top of the built-in ...

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.

change here the additional call needed to get the numbers:

?- number_codes(123456,X), maplist(plus(48),Y,X).
X = [49, 50, 51, 52, 53, 54],
Y = [1, 2, 3, 4, 5, 6].
+6
source

First you can create a reverse list:

//Base step
splitRev(0,[]).
//Recursive step
splitRev(N,[A|As]) :- N1 is floor(N/10), A is N mod 10, splitRev(N1,As).

The recursive step works as follows:

N1 is floor(N/10)

N 10 . , 538 53,8, 53. .

A is N mod 10

N, 10. 538 mod 10 8. , .

, splitRev/2. , split/2 :

split(N,L1) :- splitRev(N,L2), reverse(L1,L2).

, reverse/2 .

, !

0

All Articles