I have been trying for instance to have a list [1,3] and calculate its average inside the code without inputing the least itself. I’m not sure of the correct syntax to make it work, only the first line has a problem since it works perfectly fine if I called average and input the numbers when I run prolog.
average([1,3],X).
average(List, Result) :- sum1(List, Len), sum(List, Sum), Result is Sum / Len.
sum([], 0).
sum([H|T], Sum) :- sum(T, Temp), Sum is Temp + H.
sum1([],0).
sum1([_|B],L):-sum1(B,Ln), L is Ln+1.
Well, you don’t want to input list all the time. It means, that you should have predicate something like
my_list/1and use it in your program.So, what we’ve got now, is
Btw, there are
length/2predicate, already built-in in swi-prolog.