how should i design this predicate in prolog?

2019-03-07 01:20发布

问题:

I have to write a predicate called stepup(L, Z, X), where L is a list and Z and X are the integers. It should return true if the Z can be stepped into X using legal steps given by the user in the list.

For example

 stepup([7, 12, 19], 6, 32) 

should return true since 6 + 7 + 7 + 12 = 32 starting number should always be Z (here 6) and the rule should only use steps from the list. The rule should work for all sizes, (Z, X) are always positive.

I started with this

step([V|S],A,D):- 
   sum is A+V,
   (sum=A -> write('true') 
   ; step(S,sum,D).

but not sure how to proceed

回答1:

Maybe this helps:

stepup(_,I,I).
stepup(Steps,I0,I) :-
   I0 < I,
   member(Step,Steps),
   I1 is I0 + Step,
   stepup(Steps,I1,I).

Let's put it to use!

?- stepup([7,12,19],6,31).
false.

?- stepup([7,12,19],6,32).
true ;
true ;
true ;
true ;
true ;
false.

Note that the redundant answers in the second query are due to the different ways to step up from 6 to 32 using steps [7,12,19].



标签: list prolog