Dongho Han
Dongho Han

Reputation: 97

Prolog how to make a new list of numbers

I have a original list where the format is [name+name+mark, name+name+mark] and what I want to do is to make a new list that have only mark as its element like [mark1, mark2] (mark is number!). So I made a code

getAvg([], NEWLIST).
getAvg([_+_+Mark|Xs], R) :-
    getAvg(Xs, T) ,
    append(T, [Mark], R).

but only thing getAvg([susan+andy+43, susan+mike+43], A) returning is

R = [43, 43] ;
R = [_2918, 43, 43] ;
R = [_2918, _2930, 43, 43] ;
R = [_2918, _2930, _2942, 43, 43] ;
R = [_2918, _2930, _2942, _2954, 43, 43] ;
R = [_2918, _2930, _2942, _2954, _2966, 43, 43] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, 43, 43] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, 43, 43] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, 43|...] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, _3014|...] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, _3014|...] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, _3014|...] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, _3014|...] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, _3014|...] ;
R = [_2918, _2930, _2942, _2954, _2966, _2978, _2990, _3002, _3014|...] 

How can i make it so that it only returns R = [43,43]?

Upvotes: 2

Views: 46

Answers (1)

coder
coder

Reputation: 12972

The error is here:

getAvg([], NEWLIST).

this should be:

getAvg([], []).

since with empty lists you need to return the empty list.

Though another thing here as for efficiency is that in rule:

getAvg([_+_+Mark|Xs], R) :-
    getAvg(Xs, T) ,
    append(T, [Mark], R).

You have the Mark and you go on with the rest of the list and at the end you use append which will traverse all the list in order to add Mark. A much more efficient way would be:

getAvg([_+_+Mark|Xs], [Mark,T]) :-getAvg(Xs, T).

Here you don;t traverse any list to add Mark just place it in head. Even if that changes the order of final list it is yet more efficient to do it this way and in the end reverse the output list to get exact behavior as you previous program.

Upvotes: 3

Related Questions