Library func provides syntax functions return values in SWI-Prolog. In this example, you can print all parents sam , writing writeln(list_parents $ sam) :
:- initialization(main). :- use_module(library(func)). main :- writeln(list_parents $ sam). list_parents(P, L) :- findall(Parent, parent(Parent, P), L). parent(bob, sam). %bob is sam parent parent(sara, sam). %sara is sam parent findall (Parent, parent (Parent, P), L). :- initialization(main). :- use_module(library(func)). main :- writeln(list_parents $ sam). list_parents(P, L) :- findall(Parent, parent(Parent, P), L). parent(bob, sam). %bob is sam parent parent(sara, sam). %sara is sam parent
Similarly, you can define a function with several parameters such as:
% return a item at an index in a list. nth0((Index,List),ToReturn) :- nth0(Index,List,ToReturn). a list. % return a item at an index in a list. nth0((Index,List),ToReturn) :- nth0(Index,List,ToReturn). ToReturn): - % return a item at an index in a list. nth0((Index,List),ToReturn) :- nth0(Index,List,ToReturn).
... and then use it as follows:
example :- ListIndex = (nth0 $(0,[1,2,3,4])), %returns 1, which is the first item in this list writeln(ListIndex). returns example :- ListIndex = (nth0 $(0,[1,2,3,4])), %returns 1, which is the first item in this list writeln(ListIndex). list example :- ListIndex = (nth0 $(0,[1,2,3,4])), %returns 1, which is the first item in this list writeln(ListIndex).