0
votes

I'm new to prolog and I need help understanding how returning value works. I know that it's either

pred(Y, X) :- X is Y. 

So when giving input

?- pred(5, X).

output is: X = 5.

or when input is

?- pred(5,5).

we get: true .

Now I would like to obtain the first output from the predicate that looks like this:

main_pred(List, RES) :-
sort(List, SortedList),
check(SortedList).

The RES should be either T if check(SortedList) is true or N if check(SortedList) is false. For now my result is just true/false, but I would like to get RES = T/N.

Is it possible? Thanks

2

2 Answers

2
votes

When check succeeds, return RES the second argument equal to true

main_pred(List, true) :-
    sort(List, SortedList),
    check(SortedList), !.    
main_pred(List, false).

Otherwise return RES=false. More directly:

main_pred(List, RES) :-
    sort(List, SortedList),
    (check(SortedList) -> RES=true; RES=false).

Replace true/false by the values you want (T/N). Does this reply your question?

1
votes

1- main_pred predicate takes a list ([1,2,3]), checks if it's ordered.

2- If it is ordered, returns RES=true, else RES=false.

Note: I have commented sort, because if we use it, then it will always return RES=true.

main_pred(List, RES) :-
%sort(List, SortedList),
(ordered(List)->
    RES='true';
    RES='false').

ordered([]) .
ordered([_]) .
ordered([X,Y|Z]) :- X =< Y , ordered( [Y|Z] ),!.

EXAMPLE:

?-main_pred([1,3,5],Res).
Res = true

?-main_pred([1,4,2],Res).
Res = false