The Prolog version is fine, but the nested conditionals make it harder to read and may cause confusion about scope (for example, it's not necessary to enclose "divBy3(X),divBy5(X)" in parentheses, as on line 6 in the article).
Here's an alternative version, that avoids nested conditionals and also doesn't use the cut ("!") to control backtracking:
fizzbuzz(X,'Fizz'):-
0 is mod(X,3).
fizzbuzz(X,'Buzz'):-
0 is mod(X,5).
fizzbuzz(X,X):-
\+ fizzbuzz(X,'Fizz')
,\+ fizzbuzz(X,'Buzz').
print_fizzbuzz(N,M):-
N > M.
print_fizzbuzz(N,M):-
N =< M
,forall(fizzbuzz(N,FBN)
,write(FBN)
)
,nl
,succ(N,N_)
,print_fizzbuzz(N_,M).
This one uses Prolog's nondeterminsm to generate either Fizz, Buzz, both, or neither as apropriate and collects them all with forall/2 (yes, Prolog does have for-loops; of a sort), then adds a newline to the output.
Here's an alternative version, that avoids nested conditionals and also doesn't use the cut ("!") to control backtracking:
This one uses Prolog's nondeterminsm to generate either Fizz, Buzz, both, or neither as apropriate and collects them all with forall/2 (yes, Prolog does have for-loops; of a sort), then adds a newline to the output.Call it like this:
And have a Happy New Year.