Prolog: averages of items in two lists at corresponding indices -


i working on prolog program take 2 lists, calculates average of elements @ corresponding indices , returns averages list.

this code. i'm getting is/2: arguments not sufficiently instantiated error.

sum(h,t,s) :-    s h + t.  avelists([],[],_). avelists([head|tail],[head2|tail2],[x|tail3) :-    x sum(head,head2,a)/2,    avelists(tail,tail2,tail3). 

for example:

?-  avelists([1,4,3],[3,6,5],xs]). xs = [2,5,4].                          % expected result 

why not working , giving me error? looks me should work.

if use separate predicate calculate sum, need evaluate before using answer:

sum(a, b, sum), mean sum / 2 

there problem pointed out in other answer.

what want:

list1_list2_means([], [], []). list1_list2_means([x|xs], [y|ys], [m|ms]) :-     m (x + y) / 2,     list1_list2_means(xs, ys, ms). 

you save typing writing helper predicate finds mean of 2 numbers:

x_y_mean(x, y, m) :- m (x + y) / 2. 

then, can use maplist:

?- maplist(x_y_mean, l1, l2, means). 

there no practical benefit defining sum/3 predicate when can write (a + b) / 2. if did not know how many elements going have, maybe have like:

numbers_mean(ns, m) :-     length(ns, len),     sum_list(ns, sum),     m sum / len. 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -