Split a number into a list of digits in Prolog

前端 未结 2 814
不知归路
不知归路 2021-01-18 11:20

I\'ve been having trouble trying to split numbers into lists using Prolog, e.g. 123456 becomes [1,2,3,4,5,6].

Can you please help me work out how to do

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 12:02

    You could first 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 like this:

    N1 is floor(N/10)
    

    divides N by 10 and rounds it down. So 538 becomes 53.8 becomes 53. It cuts off the last digit.

    A is N mod 10
    

    takes the remainder of N divided by 10. 538 mod 10 equals 8. So you get only the last digit.

    Now for splitting the list you only need to reverse the list created by splitRev/2. So predicate split/2 is defined as:

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

    Note that reverse/2 is a built-in predicate.

    I hope this helps!

提交回复
热议问题