recursion - Prolog, skip adding elements to a list based on rules -


i have prolog code, , able skip adding element results list if product of x , y greater value. idea how go doing this?

e.g.

if product > 10 

the code have far

make_quads(_,[],[]). make_quads(x,[y|tail],[[x,y,sum,product]|result]):-     make_quads(x,tail,result),     product x * y,     product > 2,     sum x + y. 

the function called follows:

?- make_quads(5, [1,2,3,4,5,6], x). 

which give following output:

x = [[5, 1, 6, 5], [5, 2, 7, 10], [5, 3, 8, 15], [5, 4, 9, 20], [5, 5, 10, 25], [5, 6, 11|...]] 

i've tried along lines of following, swi-prolog returns false call function

make_quads(_,[],[]). make_quads(x,[y|tail],[[x,y,sum,product]|result]):-     make_quads(x,tail,result),     product x * y,     product > 20, % need skip here     % else continue running     sum x + y. 

you've observed reason predicate fails because needs succeed (not fail) if product =< 20, not keep values. stands, once predicate fails on product > 20, entire predicate fails since lacks such clause

you're main clause needs split 2 cases. simple way add clause case product =< 20. also, can use tail recursion here, can optimized prolog interpreters. no need recurse before setting values:

make_quads(_, [], []). make_quads(x, [y|tail], [[x,y,sum,product] | result]):-     product x * y,     product > 20,     sum x + y,     make_quads(x, tail, result). make_quads(x, [y|tail], result):-     product x * y,     product =< 20,     make_quads(x, tail, result). 

you can use prolog -> operator, little more efficient:

make_quads(_, [], []). make_quads(x, [y|tail], result):-     product x * y,     (   product > 20     ->  sum x + y,                   % if product > 20         result = [[x,y,sum,product]|r]     ;   result = r                      % if product =< 20     ),     make_quads(x, tail, r). 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -