The snippets are under the CC-BY-SA license.

Creative Commons Attribution-ShareAlike 3.0

Logo

Programming-Idioms.org

  • The snippets are under the CC-BY-SA license.
  • Please consider keeping a bookmark
  • (instead of printing)
Prolog
1
Print a literal string on standard output
write('Hello, world!\n')
Alternative implementation:
format("Hello world~n")
2
Loop to execute some code a constant number of times
:- initialization(main).
main :- loop(10).

loop(0).
loop(N) :- N>0, write('Hello') , nl, N1 = N - 1, loop(N1).
12
Check if the list contains the value x.
list is an iterable finite container.
member(X, [One]).
13
Access each key k with its value x from an associative array mymap, and print them.
forall(get_dict(K, D, V),
       format("~w:~w~n", [K, V]))
50
Write a loop that has no end clause.
repeat, write("hello\n").
Alternative implementation:
?- repeat, false.

% repeat/0 is built-in, but could be defined like this:
repeat.
repeat :- repeat.
Alternative implementation:
loop :- loop.

?- loop.
71
Basic implementation of the Echo program: Print all arguments except the program name, separated by space, followed by newline.
The idiom demonstrates how to skip the first argument if necessary, concatenate arguments as strings, append newline and print it to stdout.
main(Argv) :- echo(Argv).

echo([]) :- nl.
echo([Last]) :- write(Last), echo([]).
echo([H|T]) :- write(H), write(' '), echo(T).
112
Print each key k with its value x from an associative array mymap, in ascending order of k.
dict_pairs(D, _, Ps),
forall(member(K-V, Ps),
       format("~w:~w~n", [K, V]))
113
Print each key k with its value x from an associative array mymap, in ascending order of x.
Multiple entries may exist for the same value x.
dict_pairs(D, _, Ps),
transpose_pairs(Ps, TPs),
keysort(TPs, Val_sorted),
forall(member(V-K, Val_sorted),
       format("~w:~w~n", [V, K]))
314
Set all the elements in the array x to the same value v
set_all_elements_to_same_value(X, V) :-
    length(X, Length),
    length(FilledList, Length),
    maplist(=(V), FilledList, X).