faizanjehangir
faizanjehangir

Reputation: 2831

Call predicate again if a statement fails

I am fairly a beginner new to Prolog. Is it possible for me to continue execution of the predicate if a statement evaluates to true inside? Here is my snippet of code:

%Ylist contains: [1,2,3]
validatemove(_,[],_). % goal if Ylist is empty

validatemove(X, [Y1|Ylist], Node) :-
    X \= 0,     % if X is 0, return false
    Y1 \= 0,    % if Y1 is 0, do not execute rest of code,
                % call validatemove(X, Ylist, Node) again
    Some predicates here,
    ....,
    validatemove(X, Ylist, Newnode).

I am struggling to come up with something like this. Either way, I want to iterate over all the values given in Ylist. What should I do here?

Upvotes: 0

Views: 279

Answers (1)

Paulo Moura
Paulo Moura

Reputation: 18663

It seems that you're looking for the if-then-else control construct. Maybe something like:

%Ylist contains: [1,2,3]

validate_move([], _, _). % goal if Ylist is empty

validate_move([Y| Ys], X, Node) :-
    X =\= 0,
    % if X is 0, return false
    (  Y =:= 0 ->
       validate_move(Ys, X, Node)
    ;  % Some predicates here,
       validate_move(Ys, X, NewNode)
    ).

Note that, assuming your list is known when the predicate is called, is best to move it to the first argument to take advantage of Prolog first-argument indexing (which is implemented by most of the systems). You seem to be comparing integers, so use arithmetic comparison predicates instead of unification predicates. Also, is good Prolog programming style to use underscores to separate words in atoms and also usual to use CamelCase only for variables.

Upvotes: 1

Related Questions