The point of the program is to calculate the sum of all even numbers in a list of integers.
is_even(Q):- Q mod 2 =:= 0.
sum_even([],0).
sum_even([A|L],X) :- sum_even(L,X1) -> is_even(A) -> X is X1 + A .
Whenever the is_even predicate succeeds there is no problem, it normally goes back to calculate the sum. However when the number is not even and is_even checks it, it fails, goes back to the recursion and fails everything that follows, doesn't even check if the number is even anymore and just returns false. In a list full of even numbers it works as intended, it returns the sum of all numbers in the list. This here is the trace of the code
Using an accumulator with tail-end recursion is fastest:
is_even(N) :-
N mod 2 =:= 0.
sum_even(Lst, Sum) :-
sum_even_(Lst, 0, Sum).
sum_even_([], Sum, Sum).
sum_even_([H|T], Upto, Sum) :-
( is_even(H) ->
Upto1 is Upto + H
; Upto1 = Upto
),
sum_even_(T, Upto1, Sum).
sum_even_slow([], 0).
sum_even_slow([H|T], Sum) :-
sum_even_slow(T, Sum0),
( is_even(H) ->
Sum is Sum0 + H
; Sum = Sum0
).
Performance comparison in swi-prolog:
?- numlist(1, 1_000_000, L), time(sum_even(L, Sum)).
% 4,000,002 inferences, 0.765 CPU in 0.759 seconds (101% CPU, 5228211 Lips)
Sum = 250000500000.
?- numlist(1, 1_000_000, L), time(sum_even_slow(L, Sum)).
% 4,000,001 inferences, 4.062 CPU in 4.023 seconds (101% CPU, 984755 Lips)
Sum = 250000500000.
add_even(X, Buffer, Sum) :-
(0 =:= X mod 2 ->
Sum is Buffer + X
; Sum = Buffer).
Used with foldl(add_even, Nums, 0, Sum) is about as fast as brebs' tail recursion. Using SWISH Online:
?- numlist(1, 1_000_000, _L), time(sum_even(_L, Sum)).
4,000,002 inferences, 0.699 CPU in 0.699 seconds (100% CPU, 5724382 Lips)
Sum = 250000500000
?- numlist(1, 1_000_000, _L), time(foldl(add_even, _L, 0, Sum)).
4,000,002 inferences, 0.712 CPU in 0.712 seconds (100% CPU, 5621314 Lips)
Sum = 250000500000
(I am curious, if they both do exactly 4,000,002 inferences how come the sum_even seems to get higher LIPS throughput and finish slightly faster?)
The reason that this
is_even(Q):- Q mod 2 =:= 0.
sum_even([],0).
sum_even([A|L],X) :- sum_even(L,X1) -> is_even(A) -> X is X1 + A .
fails when there's odd numbers in the list is that '->'/2, the "implies" operator, is a soft cut. It eliminates the choice point. That means that backtracking into it fails, thus unwinding the whole thing and failing the entire predicate.
Your code is roughly equivalent to
sum_even([],0).
sum_even([A|L],X) :- sum_even(L,X1), !, is_even(A), !, X is X1 + A .
You need to
Eliminate the '->'/2 — it's not necessary the ',' operator is the AND operator, and
Provide an alternative to handle the case when an item is odd.
For instance, you could say this:
is_even( Q ) :- Q mod 2 =:= 0.
sum_even( [] , 0 ) .
sum_even( [A|L] , X ) :-
sum_even(L,X1),
( is_even(A) ->
X is X1 + A
;
X is X1
) .
Or something like this:
is_even( Q ) :- Q mod 2 =:= 0.
sum_even( [] , 0 ) .
sum_even( [A|L] , X ) :-
sum_even(L,X1),
add_even(A,X1,X) .
add_even(X,Y,Z) :- is_even(X), !, Z is X + Y .
add_even(_,Z,Z) .
But the easiest, faster way is to use a helper predicate that carries the extra state. The above predicates will die with a stack overflow given a sufficiently long list. This will not: Prolog has TRO (tail recursion optimization) built in, which effectively turns the recursive call into iteration by reusing the stack frame, so it can handle recursion of any depth:
sum_even( Xs , S ) :- sum_even(Xs,0,S) .
sum_even( [] , S , S ) .
sum_even( [X|Xs] , T , S ) :- is_even(X), !, T1 is T+X, sum_even(Xs,T1,S) .
is_even( Q ) :- Q mod 2 =:= 0.
I wanted to solve "the giant cat army riddle" by Dan Finkel using Prolog.
Basically you start with [0], then you build this list by using one of three operations: adding 5, adding 7, or taking sqrt. You successfully complete the game when you have managed to build a list such that 2,10 and 14 appear on the list, in that order, and there can be other numbers between them.
The rules also require that all the elements are distinct, they're all <=60 and are all only integers.
For example, starting with [0], you can apply (add5, add7, add5), which would result in [0, 5, 12, 17], but since it doesn't have 2,10,14 in that order it doesn't satisfy the game.
I think I have successfully managed to write the required facts, but I can't figure out how to actually build the list. I think using dcg is a good option for this, but I don't know how.
Here's my code:
:- use_module(library(lists)).
:- use_module(library(clpz)).
:- use_module(library(dcgs)).
% integer sqrt
isqrt(X, Y) :- Y #>= 0, X #= Y*Y.
% makes sure X occurs before Y and Y occurs before Z
before(X, Y, Z) --> ..., [X], ..., [Y], ..., [Z], ... .
... --> [].
... --> [_], ... .
% in reverse, since the operations are in reverse too.
order(Ls) :- phrase(before(14,10,2), Ls).
% rule for all the elements to be less than 60.
lt60_(X) :- X #=< 60.
lt60(Ls) :- maplist(lt60_, Ls).
% available operations
add5([L0|Rs], L) :- X #= L0+5, L = [X, L0|Rs].
add7([L0|Rs], L) :- X #= L0+7, L = [X, L0|Rs].
root([L0|Rs], L) :- isqrt(L0, X), L = [X, L0|Rs].
% base case, the game stops when Ls satisfies all the conditions.
step(Ls) --> { all_different(Ls), order(Ls), lt60(Ls) }.
% building the list
step(Ls) --> [add5(Ls, L)], step(L).
step(Ls) --> [add7(Ls, L)], step(L).
step(Ls) --> [root(Ls, L)], step(L).
The code emits the following error but I haven't tried to trace it or anything because I'm convinced that I'm using DCG incorrectly:
?- phrase(step(L), X).
caught: error(type_error(list,_65),sort/2)
I'm using Scryer-Prolog, but I think all the modules are available in swipl too, like clpfd instead of clpz.
step(Ls) --> [add5(Ls, L)], step(L).
This doesn't do what you want. It describes a list element of the form add5(Ls, L). Presumably Ls is bound to some value when you get here, but L is not bound. L would become bound if Ls were a non-empty list of the correct form, and you executed the goal add5(Ls, L). But you are not executing this goal. You are storing a term in a list. And then, with L completely unbound, some part of the code that expects it to be bound to a list will throw this error. Presumably that sort/2 call is inside all_different/1.
Edit: There are some surprisingly complex or inefficient solutions posted here. I think both DCGs and CLP are overkill here. So here's a relatively simple and fast one. For enforcing the correct 2/10/14 order this uses a state argument to keep track of which ones we have seen in the correct order:
puzzle(Solution) :-
run([0], seen_nothing, ReverseSolution),
reverse(ReverseSolution, Solution).
run(FinalList, seen_14, FinalList).
run([Head | Tail], State, Solution) :-
dif(State, seen_14),
step(Head, Next),
\+ member(Next, Tail),
state_next(State, Next, NewState),
run([Next, Head | Tail], NewState, Solution).
step(Number, Next) :-
( Next is Number + 5
; Next is Number + 7
; nth_integer_root_and_remainder(2, Number, Next, 0) ),
Next =< 60,
dif(Next, Number). % not strictly necessary, added by request
state_next(State, Next, NewState) :-
( State = seen_nothing,
Next = 2
-> NewState = seen_2
; State = seen_2,
Next = 10
-> NewState = seen_10
; State = seen_10,
Next = 14
-> NewState = seen_14
; NewState = State ).
Timing on SWI-Prolog:
?- time(puzzle(Solution)), writeln(Solution).
% 13,660,415 inferences, 0.628 CPU in 0.629 seconds (100% CPU, 21735435 Lips)
[0,5,12,17,22,29,36,6,11,16,4,2,9,3,10,15,20,25,30,35,42,49,7,14]
Solution = [0, 5, 12, 17, 22, 29, 36, 6, 11|...] .
The repeated member calls to ensure no duplicates make up the bulk of the execution time. Using a "visited" table (not shown) takes this down to about 0.25 seconds.
Edit: Pared down a bit further and made 100x faster:
prev_next(X, Y) :-
between(0, 60, X),
( Y is X + 5
; Y is X + 7
; X > 0,
nth_integer_root_and_remainder(2, X, Y, 0) ),
Y =< 60.
moves(Xs) :-
moves([0], ReversedMoves),
reverse(ReversedMoves, Xs).
moves([14 | Moves], [14 | Moves]) :-
member(10, Moves).
moves([Prev | Moves], FinalMoves) :-
Prev \= 14,
prev_next(Prev, Next),
( Next = 10
-> member(2, Moves)
; true ),
\+ member(Next, Moves),
moves([Next, Prev | Moves], FinalMoves).
?- time(moves(Solution)), writeln(Solution).
% 53,207 inferences, 0.006 CPU in 0.006 seconds (100% CPU, 8260575 Lips)
[0,5,12,17,22,29,36,6,11,16,4,2,9,3,10,15,20,25,30,35,42,49,7,14]
Solution = [0, 5, 12, 17, 22, 29, 36, 6, 11|...] .
The table of moves can be precomputed (enumerate all solutions of prev_next/2, assert them in a dynamic predicate, and call that) to gain another millisecond or two. Using a CLP(FD) instead of "direct" arithmetic makes this considerably slower on SWI-Prolog. In particular, Y in 0..60, X #= Y * Y instead of the nth_integer_root_and_remainder/4 goal takes this up to about 0.027 seconds.
Given that the question seems to have shifted from using DCGs to solving the puzzle, I thought I might post a more efficient approach. I am using clp(fd) on SICStus, but I included a modified version that should work with clpz on Scryer (replacing table/2 with my_simple_table/2).
:- use_module(library(clpfd)).
:- use_module(library(lists)).
move(X,Y):-
(
X+5#=Y
;
X+7#=Y
;
X#=Y*Y
).
move_table(Table):-
findall([X,Y],(
X in 0..60,
Y in 0..60,
move(X,Y),
labeling([], [X,Y])
),Table).
% Naive version
%%post_move(X,Y):- move(X,Y).
%%
% SICSTUS clp(fd)
%%post_move(X,Y):-
%% move_table(Table),
%% table([[X,Y]],Table).
%%
% clpz is mising table/2
post_move(X,Y):-
move_table(Table),
my_simple_table([[X,Y]],Table).
my_simple_table([[X,Y]],Table):-
transpose(Table, [ListX,ListY]),
element(N, ListX, X),
element(N, ListY, Y).
post_moves([_]):-!.
post_moves([X,Y|Xs]):-
post_move(X,Y),
post_moves([Y|Xs]).
state(N,Xs):-
length(Xs,N),
domain(Xs, 0, 60),
all_different(Xs),
post_moves(Xs),
% ordering: 0 is first, 2 comes before 10, and 14 is last.
Xs=[0|_],
element(I2, Xs, 2),
element(I10, Xs, 10),
I2#<I10,
last(Xs, 14).
try_solve(N,Xs):-
state(N, Xs),
labeling([ffc], Xs).
try_solve(N,Xs):-
N1 is N+1,
try_solve(N1,Xs).
solve(Xs):-
try_solve(1,Xs).
Two notes of interest:
It is much more efficient to create a table of the possible moves and use the table/2 constraint rather than posting a disjunction of constraints. Note that we are recreating the table every time we post it, but we might as well create it once and pass it along.
This is using the element/3 constraint to find and constraint the position of the numbers of interest (in this case just 2 and 10, because we can fix 14 to be last). Again, this is more efficient than checking the order as filtering after solving the constraint problem.
Edit:
Here is an updated version to conform to the bounty constraints (predicate names, -hopefully- SWI-compatible, create the table only once):
:- use_module(library(clpfd)).
:- use_module(library(lists)).
generate_move_table(Table):-
X in 0..60,
Y in 0..60,
( X+5#=Y
#\/ X+7#=Y
#\/ X#=Y*Y
),
findall([X,Y],labeling([], [X,Y]),Table).
%post_move(X,Y,Table):- table([[X,Y]],Table). %SICStus
post_move(X,Y,Table):- tuples_in([[X,Y]],Table). %swi-prolog
%post_move(X,Y,Table):- my_simple_table([[X,Y]],Table). %scryer
my_simple_table([[X,Y]],Table):- % Only used as a fall back for Scryer prolog
transpose(Table, [ListX,ListY]),
element(N, ListX, X),
element(N, ListY, Y).
post_moves([_],_):-!.
post_moves([X,Y|Xs],Table):-
post_move(X,Y,Table),
post_moves([Y|Xs],Table).
puzzle_(Xs):-
generate_move_table(Table),
N in 4..61,
indomain(N),
length(Xs,N),
%domain(Xs, 0, 60), %SICStus
Xs ins 0..60, %swi-prolog, scryer
all_different(Xs),
post_moves(Xs,Table),
% ordering: 0 is first, 2 comes before 10, 14 is last.
Xs=[0|_],
element(I2, Xs, 2),
element(I10, Xs, 10),
I2#<I10,
last(Xs, 14).
label_puzzle(Xs):-
labeling([ffc], Xs).
solve(Xs):-
puzzle_(Xs),
label_puzzle(Xs).
I do not have SWI-prolog installed so I can't test the efficiency requirement (or that it actually runs at all) but on my machine and with SICStus, the new version of the solve/1 predicate takes 16 to 31 ms, while the puzzle/1 predicate in Isabelle's answer (https://stackoverflow.com/a/65513470/12100620) takes 78 to 94 ms.
As for elegance, I guess this is in the eye of the beholder. I like this formulation, it is relatively clear and is showcasing some very versatile constraints (element/3, table/2, all_different/1), but one drawback of it is that in the problem description the size of the sequence (and hence the number of FD variables) is not fixed, so we need to generate all sizes until one matches. Interestingly, it appears that all the solutions have the very same length and that the first solution of puzzle_/1 produces a list of the right length.
An alternative that uses dcg only to build the list. The 2,10,14 constraint is checked after building the list, so this is not optimal.
num(X) :- between(0, 60, X).
isqrt(X, Y) :- nth_integer_root_and_remainder(2, X, Y, 0). %SWI-Prolog
% list that ends with an element.
list([0], 0) --> [0].
list(YX, X) --> list(YL, Y), [X], { append(YL, [X], YX), num(X), \+member(X, YL),
(isqrt(Y, X); plus(Y, 5, X); plus(Y, 7, X)) }.
soln(X) :-
list(X, _, _, _),
nth0(I2, X, 2), nth0(I10, X, 10), nth0(I14, X, 14),
I2 < I10, I10 < I14.
?- time(soln(X)).
% 539,187,719 inferences, 53.346 CPU in 53.565 seconds (100% CPU, 10107452 Lips)
X = [0, 5, 12, 17, 22, 29, 36, 6, 11, 16, 4, 2, 9, 3, 10, 15, 20, 25, 30, 35, 42, 49, 7, 14]
I tried a little magic set. The predicate path/2 does search a path without giving us a path. We can therefore use commutativity of +5 and +7, doing less search:
step1(X, Y) :- N is (60-X)//5, between(0, N, K), H is X+K*5,
M is (60-H)//7, between(0, M, J), Y is H+J*7.
step2(X, Y) :- nth_integer_root_and_remainder(2, X, Y, 0).
:- table path/2.
path(X, Y) :- step1(X, H), (Y = H; step2(H, J), path(J, Y)).
We then use path/2 as a magic set for path/4:
step(X, Y) :- Y is X+5, Y =< 60.
step(X, Y) :- Y is X+7, Y =< 60.
step(X, Y) :- nth_integer_root_and_remainder(2, X, Y, 0).
/* without magic set */
path0(X, L, X, L).
path0(X, L, Y, R) :- step(X, H), \+ member(H, L),
path0(H, [H|L], Y, R).
/* with magic set */
path(X, L, X, L).
path(X, L, Y, R) :- step(X, H), \+ member(H, L),
path(H, Y), path(H, [H|L], Y, R).
Here is a time comparison:
SWI-Prolog (threaded, 64 bits, version 8.3.16)
/* without magic set */
?- time((path0(0, [0], 2, H), path0(2, H, 10, J), path0(10, J, 14, L))),
reverse(L, R), write(R), nl.
% 13,068,776 inferences, 0.832 CPU in 0.839 seconds (99% CPU, 15715087 Lips)
[0,5,12,17,22,29,36,6,11,16,4,2,9,3,10,15,20,25,30,35,42,49,7,14]
/* with magic set */
?- abolish_all_tables.
true.
?- time((path(0, [0], 2, H), path(2, H, 10, J), path(10, J, 14, L))),
reverse(L, R), write(R), nl.
% 2,368,325 inferences, 0.150 CPU in 0.152 seconds (99% CPU, 15747365 Lips)
[0,5,12,17,22,29,36,6,11,16,4,2,9,3,10,15,20,25,30,35,42,49,7,14]
Noice!
I managed to solve it without DCG's, it takes about 50 minutes on my machine to solve for the length N=24. I suspect this is because the order check is done for every list from scratch.
:- use_module(library(lists)).
:- use_module(library(clpz)).
:- use_module(library(dcgs)).
:- use_module(library(time)).
%% integer sqrt
isqrt(X, Y) :- Y #>= 0, X #= Y*Y.
before(X, Y, Z, L) :-
%% L has a suffix [X|T], and T has a suffix of [Y|_].
append(_, [X|T], L),
append(_, [Y|TT], T),
append(_, [Z|_], TT).
order(L) :- before(2,10,14, L).
game([X],X).
game([H|T], H) :- ((X #= H+5); (X #= H+7); (isqrt(H, X))), X #\= H, H #=< 60, X #=< 60, game(T, X). % H -> X.
searchN(N, L) :- length(L, N), order(L), game(L, 0).
I have a list of cars (auto in german), where the first Variable is the license-plate and the second one the speed:
[auto(eu-ts884, 69), auto(dn-gh184, 64), auto(ac-lj123, 72)].
Now I try to write an average predicate but it fails with the error message:
ERROR: Arguments are not sufficiently instantiated
My code so far:
durchschnitt([], 0, 0).
durchschnitt([auto(_, X)|Tail], L, Y):-
Y is S/L,
L > 0,
cardinal([auto(_, X)|Tail], L),
sumKilometer([auto(_, X)|Tail], S).
sumKilometer([], 0).
sumKilometer([auto(_, X)|Tail], Sum) :-
sumKilometer(Tail, N),
Sum is N + X.
cardinal([], 0).
cardinal([_|Tail], Result) :-
cardinal(Tail, N),
Result is N + 1.
My code is quite equivalent to that post, although I cannot make out my mistake.
Note: sumKilometer and cardinal are working fine.
You write:
durchschnitt([], 0, 0).
durchschnitt([auto(_, X)|Tail], L, Y):-
Y is S/L,
L > 0,
cardinal([auto(_, X)|Tail], L),
sumKilometer([auto(_, X)|Tail], S).
The first problem is that when you call durchschnitt([auto(foo,2)],L,Y), L is a free variable. As a result, you cannot calculate Y is S/L since both S and L are unknown here.
You can however use:
durchschnitt([], 0, 0).
durchschnitt([auto(_, X)|Tail], L, Y):-
cardinal([auto(_, X)|Tail], L),
sumKilometer([auto(_, X)|Tail], S),
Y is S/L.
So here you calculate the average after both L and S are known. Furthermore you do not unify the list with [auto(_,X)|Tail], etc. A simple check like A = [_|_] is sufficient:
durchschnitt([], 0, 0).
durchschnitt(A, L, Y):-
A = [_|_],
cardinal(A, L),
sumKilometer(A, S),
Y is S/L.
This will also reduce the amount of time spent packing and unpacking.
Sum, Length and Average all concurrently
You can construct a predicate that calculates the three all at the same time (so without looping twice over the list). You can simply use accumulators, like:
durchschnitt(A,L,Y) :-
durchschnitt(A,0,0,L,Y).
Here the second and third element are the running sum and length respectively.
Now for durchschnitt/5, there are two cases. In the first case we have reached the end of the list, and we thus have to calculate the average and return it, like:
durchschnitt([],S,L,L,Y) :-
(L \= 0
-> Y is S/L
; Y = 0).
So we use an if-then-else to check if the length is something different than 0 (in the case there are no autos in the list, we return 0 as average.
In the recursive case, we simple increment the running length and update the running sum, like:
durchschnitt([auto(_,Si)|T],RS,RL,L,Y) :-
RSN is RS+Si,
L1 is L+1,
durchschnitt(T,RSN,L1,L,Y).
Or putting it together:
durchschnitt(A,L,Y) :-
durchschnitt(A,0,0,L,Y).
durchschnitt([],S,L,L,Y) :-
(L \= 0
-> Y is S/L
; Y = 0).
durchschnitt([auto(_,Si)|T],RS,RL,L,Y) :-
RSN is RS+Si,
L1 is L+1,
durchschnitt(T,RSN,L1,L,Y).
That's a very frequently asked question but i'd like to pose it in relation with two examples that seem very similar in my eyes, and are yet the one correct and the other not.
Correct example:
k_th_element(X,[X|_],1).
k_th_element(X,[_|L],K):- K>1,K1 is (K-1),k_th_element(X,L,K1).
Wrong Example
length2(1,[_]).
length2(X,[_|Ys]) :- X>1, X1 is (X-1), length(X1,Ys).
Why prolog complains or doesn't for each case?
Update: I think i got it. What i couldn't understand was that it doesn't matter what the predicate is but how you are calling it. so this is correct:
k_th_element(X,[1,2,3,4,5],3) because you have a value for K which is the right variable of "is" operator. But at the same time k_th_element(3,[1,2,3,4,5],Y) will not work, because Y is a variable, our "goal" and we can't have that in the right part of "is" operator. Correct me if i'm wrong.
as mat proposed, there is a more flexible way to achieve the same:
:- use_module(library(clpfd)).
length2(0,[]).
length2(X,[_|Ys]) :- X#>0, X1#=X-1, length2(X1,Ys).
First, there is the argument order. For length/2 it is rather length(List, Length).
For the case of a given list and an unknown length, your version is relatively inefficient because of all the X1 #= X-1 constraints which implies about N constrained variables. The version length3/2 has a single constrained variable. (It is about 7 times faster. I am still surprised that it is not faster than it is, maybe someone can help with another answer?)
:- use_module(library(clpfd)).
length2([], 0).
length2([_E|Es], N0) :-
N0 #> 0,
N1 #= N0-1,
length2(Es, N1).
length3(Es, N) :-
length3(Es, 0, N).
length3([], N,N).
length3([_E|Es], N0,N) :-
N1 is N0+1,
N #>= N1,
length3(Es, N1,N).
?- length(L,1000), time(length2(L,N)).
% 783,606 inferences, 0.336 CPU in 0.347 seconds (97% CPU, 2332281 Lips)
L = [_A, _B, _C, _D, _E, _F, _G, _H, _I|...], N = 1000.
?- length(L,1000), time(length3(L,N)).
% 127,006 inferences, 0.047 CPU in 0.058 seconds (81% CPU, 2719603 Lips)
L = [_A, _B, _C, _D, _E, _F, _G, _H, _I|...], N = 1000.
Using reflection predicates one can build the following variant of list_length/2:
:- use_module(library(clpfd)).
list_length(Es, N) :-
( fd_sup(N, Ub), integer(Ub)
-> ( length(Es, M),
( M >= Ub
-> !,
M == Ub
; true
),
M = N
)
; length(Es, N)
).
The above implementation combines two nice properties:
It works well with clpfd.
In particular, list_length(Xs,N) terminates universally whenever N has a finite upper bound.
Using SWI-Prolog 8.0.0:
?- N in 1..3, list_length(Xs, N).
N = 1, Xs = [_A]
; N = 2, Xs = [_A,_B]
; N = 3, Xs = [_A,_B,_C]. % terminates universally
It minimizes auxiliary computation (and thus runtime) by using the builtin predicate length/2.
Let's compare the runtime of list_length/2 with length3/2—presented in this earlier answer!
Using SWI-Prolog 8.0.0 with command-line option -O:
?- time(( N in 1..100000, list_length(_,N), false ; true )).
% 2,700,130 inferences, 0.561 CPU in 0.561 seconds (100% CPU, 4812660 Lips)
true.
?- time(( N in 1..100000, length3(_,N), false ; true )).
% 14,700,041 inferences, 3.948 CPU in 3.949 seconds (100% CPU, 3723234 Lips)
true.
Note that the above also works with SICStus Prolog: SWI's fd_sup/2 is called fd_max/2 in SICStus.
I am trying to find the minimum value of a list (as a learning experience, so without min).
My approach is the following:
minimo([X], X).
minimo([X,Y|Tail], N):-
(X > Y, minimo([Y,Tail], Y));
(X <= Y, minimo([X,Tail], X)).
This gives me the following error:
Syntax error: Operator expected
So my questions are:
What is causing the syntax error?
I will try it myself once that is fixed if it actually gives the correct value back, but would this actually be a correct approach?
Thanks in advance.
There are several bugs in your program:
as pointed out by Joe Lehmann, there is no '<='/2. It must be '=<'/2.
when you call minimo/2 recursively, you construct the lists wrong. Instead of [Y,Tail] use [Y|Tail]. Otherwise, you get a list with a list as second element.
you bind the second argument of the recursive call of minimo/2 to Y or X. Instead it must be bound to N. Otherwise, your N will never be instantiated.
You can improve your program further by adding cuts or using if-then-else ('->' + ;):
minimo([X], X) :- !.
minimo([X,Y|Tail], N):-
( X > Y ->
minimo([Y|Tail], N)
;
minimo([X|Tail], N)
).
In addition to the other versions posted already, consider also a version without if-then-else, and using a more descriptive name for the relation (which relates a list to its minimum):
list_min([L|Ls], Min) :- list_min(Ls, L, Min).
list_min([], Min, Min).
list_min([L|Ls], Min0, Min) :-
Min1 is min(L, Min0),
list_min(Ls, Min1, Min).
Such a pattern is called a fold (from the left), and we can write it equivalently using `foldl/4:
list_min([L|Ls], Min) :- foldl(min_, Ls, L, Min).
min_(A, B, Min) :- Min is min(A, B).
Example query:
?- list_min([1,0,2], Min).
Min = 0.
Note though that this is not a true relation and cannot be used in all directions due to the use of low-level arithmetic. For example, if we try to use it in the other direction, we get:
?- list_min([X,Y], 3).
ERROR: is/2: Arguments are not sufficiently instantiated
To make it a true solution, use constraints like clpfd and clpq. For example, for a solution over integers:
:- use_module(library(clpfd)).
list_min([L|Ls], Min) :- foldl(min_, Ls, L, Min).
min_(A, B, Min) :- Min #= min(A, B).
This works in all directions:
?- list_min([X,Y], 3).
X in 3..sup,
3#=min(Y, X),
Y in 3..sup.
The syntax error is, because less or equal in Prolog is =<, not <=.
I think the approach will work, but you really should avoid ; in a clause. Just split it up into two clauses.
Also I think that you want to do something like [X|Tail] in the recursion rather than [X,Tail]
min([H|T], Min) :- min(T, H, Min).
min([], Min, Min).
min([H|T], Min, Min1) :-
( H < Min
-> min(T, H, Min1)
; min(T, Min, Min1) ).