Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Combining lists with arithmetic

Status
Not open for further replies.

Infty

Programmer
Jul 18, 2010
2
RS
Greetings,

This is my first post here so I would like to greet you all.
I started learning prolog and I must admit I'm having problems since its a totally different idea of programming, totally different from imperative type of thinking.

Here is my idea, actually i made an example i would like to solve in order to improve my knowledge.

If I'm given a number X, X>10 i would like to split its digits and store them in a list.

Example:
digits_in_list([],153,X).
X=[1,5,3].

I wrote some predicate but since I lack understanding how precisely prolog recursion works i cant menage to solve this.

My predicate:

add(X,[],[X]).
add(X,L,[X|L]).

digits_in_list([],X,[X]): -X<10.
digits_in_list([],X,L): -X1 is X mod 10,add(X1,L,Y),X is X //10.
 
Your first mistake is here:

Code:
X is X // 10

In Prolog this statement is different than in imperative languages. In an imperative language, X will be given a new value. In Prolog it tests if X is equal to X // 10 and it usually isn't

Your second mistake is that you don't use recursion in digits_in_list, the process stops after only one step.

To solve your problem you would need something like this:

Code:
digits_in_list(X, [X]) :- X < 10, !.
digits_in_list(X, L) :-
    Y is X mod 10,
    X1 is X // 10,
    digits_in_list(X1, L1),
    append(L1, [Y], L).

If X = 153, you will compute X1 = 15 and Y = 3, you will solve the problem for X1 and will obtain L1 = [1, 5] and then you will append Y = 3 to the result, obtaining [1, 5, 3]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top