From 1ef7eeabdfe695d25ac17f30621db7c112d4f160 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADtor=20Santos=20Costa?= Date: Wed, 30 Sep 2015 00:02:59 +0100 Subject: [PATCH] fix files dragged in --- GitSHA1.c | 2 +- ID | Bin 2162323 -> 0 bytes .../CMakeDirectoryInformation.cmake | 16 - .../CMakeFiles/libOPTYap.dir/C.includecache | 838 - .../CMakeFiles/libOPTYap.dir/DependInfo.cmake | 50 - .../CMakeFiles/libOPTYap.dir/depend.internal | 832 - OPTYap/CMakeFiles/progress.marks | 1 - commands | 15412 ----- comments.yap | 15434 ------ compile_commands.json | 892 - docs/DoxygenLayout.xml | 194 - docs/LOG | 34 - docs/LOGE | 1 - docs/abn_tree.css | 121 - docs/abn_tree_directive.coffee | 2740 - docs/abn_tree_directive.js | 492 - docs/angular.treeview.css | 56 - docs/angular.treeview.js | 98 - docs/blog.css | 166 - docs/bootstrap-treenav.js | 1207 - docs/builtins.md | 0 docs/builtins.tex | 6124 -- docs/chr.md | 527 - docs/chr.tex | 596 - docs/clpqr.md | 121 - docs/clpr.tex | 180 - docs/customdoxygen.css | 179 - docs/dir | 18 - docs/dist/css/bootstrap-theme.css | 457 - docs/dist/css/bootstrap-theme.css.map | 1 - docs/dist/css/bootstrap-theme.min.css | 5 - docs/dist/css/bootstrap.css | 6358 --- docs/dist/css/bootstrap.css.map | 1 - docs/dist/css/bootstrap.min.css | 5 - .../fonts/glyphicons-halflings-regular.eot | Bin 20335 -> 0 bytes .../fonts/glyphicons-halflings-regular.svg | 229 - .../fonts/glyphicons-halflings-regular.ttf | Bin 41280 -> 0 bytes .../fonts/glyphicons-halflings-regular.woff | Bin 23320 -> 0 bytes docs/dist/js/bootstrap.js | 2276 - docs/dist/js/bootstrap.min.js | 7 - docs/dist/js/npm.js | 13 - docs/download.md | 0 docs/doxfull.rc | 2341 - docs/doxsmall.rc | 2329 - docs/doxtest.rc | 2328 - docs/doxy-boot.js | 121 - docs/extensions.md | 0 docs/file.png | Bin 263 -> 0 bytes docs/first/footerFile | 21 - docs/first/headerFile | 55 - docs/first/styleSheetFile | 1440 - docs/fix_md | 36 - docs/fli.md | 0 docs/folder-closed.png | Bin 281 -> 0 bytes docs/folder.png | Bin 289 -> 0 bytes docs/footer.html | 45 - docs/header.html | 49 - docs/index/.cvsignore | 2 - docs/index/Benchmarks/.cvsignore | 1 - docs/index/Benchmarks/compress.P | 112 - docs/index/Benchmarks/go_xxx | 33 - docs/index/Benchmarks/go_yap | 32 - docs/index/Benchmarks/mutagenesis.P | 13111 ----- docs/index/Benchmarks/pta.P | 16405 ------ docs/index/Benchmarks/sg_cyl.P | 1132 - docs/index/Benchmarks/tc_d_io_chain400.P | 412 - docs/index/Benchmarks/tc_d_oo_chain100.P | 112 - docs/index/Benchmarks/tc_d_oo_chain400.P | 412 - docs/index/Benchmarks/tc_l_io_chain8000.P | 8012 --- docs/index/Benchmarks/tc_l_oo_chain2000.P | 2012 - docs/index/Benchmarks/tc_r_io_chain2000.P | 2012 - docs/index/Benchmarks/tc_r_oo_chain2000.P | 2012 - docs/index/article.tex | 1319 - docs/index/iclp07.tex | 1394 - docs/index/latexmk | 2514 - docs/index/llncs.cls | 1190 - docs/index/lp.bib | 640 - docs/index/splncs.bst | 1098 - docs/install.md | 0 docs/install.tex | 388 - docs/layout.xml | 1501 - docs/load.tex | 1032 - docs/new_stylesheet.css | 1439 - docs/offcanvas.css | 59 - docs/offcanvas.js | 5 - docs/packages.md | 0 docs/run.md | 191 - docs/run.tex | 214 - docs/scan | 99 - docs/solarized-light.css | 303 - docs/style.css | 1474 - docs/swi.md | 0 docs/swi.tex | 325 - docs/syntax.md | 512 - docs/syntax.tex | 494 - docs/texi2doxy | 923 - docs/theme.css | 18 - docs/yap.bib | 62 - docs/yap.css | 8 - docs/yap.md | 1143 - docs/yap.tex | 11025 ---- docs/yapdocs.md | 15665 ------ docs/yapdocs.yap | 15552 ------ editors/Prolog.xlangspec | 261 - fetchatgs | 1 - jhc | 192 - .../CMakeDirectoryInformation.cmake | 16 - library/random/CMakeFiles/progress.marks | 1 - .../yap_random.dir/DependInfo.cmake | 38 - .../random/CMakeFiles/yap_random.dir/link.txt | 1 - .../CMakeDirectoryInformation.cmake | 16 - library/regex/CMakeFiles/progress.marks | 1 - .../CMakeFiles/regexp.dir/DependInfo.cmake | 38 - library/regex/CMakeFiles/regexp.dir/link.txt | 1 - .../CMakeDirectoryInformation.cmake | 16 - library/rltree/CMakeFiles/progress.marks | 1 - .../CMakeFiles/yap_rl.dir/DependInfo.cmake | 39 - library/rltree/CMakeFiles/yap_rl.dir/link.txt | 1 - .../CMakeDirectoryInformation.cmake | 16 - library/system/CMakeFiles/progress.marks | 1 - .../CMakeFiles/sys.dir/DependInfo.cmake | 38 - library/system/CMakeFiles/sys.dir/link.txt | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../CMakeFiles/itries.dir/DependInfo.cmake | 40 - library/tries/CMakeFiles/itries.dir/link.txt | 1 - library/tries/CMakeFiles/progress.marks | 1 - .../CMakeFiles/tries.dir/DependInfo.cmake | 40 - library/tries/CMakeFiles/tries.dir/link.txt | 1 - man/doc2tex | 179 - man/fancychap.sty | 43 - man/html.sty | 174 - man/name.bst | 1254 - man/pl.bib | 1101 - man/pl.sty | 508 - man/plpage.sty | 32 - man/runtex | 221 - .../CMakeDirectoryInformation.cmake | 16 - .../CMakeFiles/HorusCli.dir/DependInfo.cmake | 40 - .../horus/CMakeFiles/HorusCli.dir/link.txt | 1 - .../CMakeFiles/horus.dir/DependInfo.cmake | 64 - .../CLPBN/horus/CMakeFiles/horus.dir/link.txt | 1 - .../CLPBN/horus/CMakeFiles/progress.marks | 1 - .../bdd/CMakeFiles/cudd.dir/DependInfo.cmake | 40 - packages/bdd/CMakeFiles/cudd.dir/link.txt | 1 - packages/bdd/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../Problogbdd.dir/DependInfo.cmake | 44 - .../CMakeFiles/Problogbdd.dir/link.txt | 1 - .../bdd/simplecudd/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../Problogbdd-Lfi.dir/DependInfo.cmake | 48 - .../CMakeFiles/Problogbdd-Lfi.dir/link.txt | 1 - .../simplecudd_lfi/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../gecode_yap.dir/DependInfo.cmake | 40 - .../gecode/CMakeFiles/gecode_yap.dir/link.txt | 1 - .../CMakeFiles/gecodeyap.dir/DependInfo.cmake | 8 - packages/gecode/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../CMakeFiles/myddas.dir/DependInfo.cmake | 50 - .../myddas/CMakeFiles/myddas.dir/link.txt | 1 - .../CMakeFiles/plmyddas.dir/DependInfo.cmake | 8 - packages/myddas/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../CMakeFiles/libpython.dir/DependInfo.cmake | 39 - .../python/CMakeFiles/libpython.dir/link.txt | 1 - packages/python/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - packages/swig/CMakeFiles/progress.marks | 1 - .../CMakeDirectoryInformation.cmake | 16 - .../CMakeFiles/JavaYAP.dir/DependInfo.cmake | 8 - .../JavaYAP.dir/java_class_filelist | 0 .../java/CMakeFiles/JavaYAP.dir/java_sources | 1 - .../CMakeFiles/Native.dir/DependInfo.cmake | 41 - .../swig/java/CMakeFiles/Native.dir/link.txt | 1 - .../CMakeFiles/NativeJar.dir/DependInfo.cmake | 8 - .../NativeJar.dir/java_class_filelist | 0 packages/swig/java/CMakeFiles/progress.marks | 1 - pages | 110 - t | 4 - test/CTestTestfile.cmake | 7 - test/elisp/CTestTestfile.cmake | 8 - tmp/bads | 340 - tmp/comments.yap | 15434 ------ tmp/foreigns.c | 1544 - tmp/foreigns.yap | 46302 ---------------- tmp/pages | 110 - untitled.txt | 17 - x.plpushd | 0 y | 61 - z.md | 17 - 191 files changed, 1 insertion(+), 239675 deletions(-) delete mode 100644 ID delete mode 100644 OPTYap/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 OPTYap/CMakeFiles/libOPTYap.dir/C.includecache delete mode 100644 OPTYap/CMakeFiles/libOPTYap.dir/DependInfo.cmake delete mode 100644 OPTYap/CMakeFiles/libOPTYap.dir/depend.internal delete mode 100644 OPTYap/CMakeFiles/progress.marks delete mode 100644 commands delete mode 100644 comments.yap delete mode 100644 compile_commands.json delete mode 100644 docs/DoxygenLayout.xml delete mode 100644 docs/LOG delete mode 100644 docs/LOGE delete mode 100644 docs/abn_tree.css delete mode 100644 docs/abn_tree_directive.coffee delete mode 100644 docs/abn_tree_directive.js delete mode 100644 docs/angular.treeview.css delete mode 100644 docs/angular.treeview.js delete mode 100644 docs/blog.css delete mode 100644 docs/bootstrap-treenav.js delete mode 100644 docs/builtins.md delete mode 100644 docs/builtins.tex delete mode 100644 docs/chr.md delete mode 100644 docs/chr.tex delete mode 100644 docs/clpqr.md delete mode 100644 docs/clpr.tex delete mode 100644 docs/customdoxygen.css delete mode 100644 docs/dir delete mode 100755 docs/dist/css/bootstrap-theme.css delete mode 100755 docs/dist/css/bootstrap-theme.css.map delete mode 100755 docs/dist/css/bootstrap-theme.min.css delete mode 100755 docs/dist/css/bootstrap.css delete mode 100755 docs/dist/css/bootstrap.css.map delete mode 100755 docs/dist/css/bootstrap.min.css delete mode 100755 docs/dist/fonts/glyphicons-halflings-regular.eot delete mode 100755 docs/dist/fonts/glyphicons-halflings-regular.svg delete mode 100755 docs/dist/fonts/glyphicons-halflings-regular.ttf delete mode 100755 docs/dist/fonts/glyphicons-halflings-regular.woff delete mode 100755 docs/dist/js/bootstrap.js delete mode 100755 docs/dist/js/bootstrap.min.js delete mode 100755 docs/dist/js/npm.js delete mode 100644 docs/download.md delete mode 100644 docs/doxfull.rc delete mode 100644 docs/doxsmall.rc delete mode 100644 docs/doxtest.rc delete mode 100644 docs/doxy-boot.js delete mode 100644 docs/extensions.md delete mode 100644 docs/file.png delete mode 100644 docs/first/footerFile delete mode 100644 docs/first/headerFile delete mode 100644 docs/first/styleSheetFile delete mode 100644 docs/fix_md delete mode 100644 docs/fli.md delete mode 100644 docs/folder-closed.png delete mode 100644 docs/folder.png delete mode 100644 docs/footer.html delete mode 100644 docs/header.html delete mode 100644 docs/index/.cvsignore delete mode 100644 docs/index/Benchmarks/.cvsignore delete mode 100644 docs/index/Benchmarks/compress.P delete mode 100644 docs/index/Benchmarks/go_xxx delete mode 100644 docs/index/Benchmarks/go_yap delete mode 100644 docs/index/Benchmarks/mutagenesis.P delete mode 100644 docs/index/Benchmarks/pta.P delete mode 100644 docs/index/Benchmarks/sg_cyl.P delete mode 100644 docs/index/Benchmarks/tc_d_io_chain400.P delete mode 100644 docs/index/Benchmarks/tc_d_oo_chain100.P delete mode 100644 docs/index/Benchmarks/tc_d_oo_chain400.P delete mode 100644 docs/index/Benchmarks/tc_l_io_chain8000.P delete mode 100644 docs/index/Benchmarks/tc_l_oo_chain2000.P delete mode 100644 docs/index/Benchmarks/tc_r_io_chain2000.P delete mode 100644 docs/index/Benchmarks/tc_r_oo_chain2000.P delete mode 100644 docs/index/article.tex delete mode 100644 docs/index/iclp07.tex delete mode 100644 docs/index/latexmk delete mode 100644 docs/index/llncs.cls delete mode 100644 docs/index/lp.bib delete mode 100644 docs/index/splncs.bst delete mode 100644 docs/install.md delete mode 100644 docs/install.tex delete mode 100644 docs/layout.xml delete mode 100644 docs/load.tex delete mode 100644 docs/new_stylesheet.css delete mode 100644 docs/offcanvas.css delete mode 100644 docs/offcanvas.js delete mode 100644 docs/packages.md delete mode 100644 docs/run.md delete mode 100644 docs/run.tex delete mode 100644 docs/scan delete mode 100644 docs/solarized-light.css delete mode 100644 docs/style.css delete mode 100644 docs/swi.md delete mode 100644 docs/swi.tex delete mode 100644 docs/syntax.md delete mode 100644 docs/syntax.tex delete mode 100644 docs/texi2doxy delete mode 100644 docs/theme.css delete mode 100644 docs/yap.bib delete mode 100644 docs/yap.css delete mode 100644 docs/yap.md delete mode 100644 docs/yap.tex delete mode 100644 docs/yapdocs.md delete mode 100644 docs/yapdocs.yap delete mode 100644 editors/Prolog.xlangspec delete mode 100644 fetchatgs delete mode 100644 jhc delete mode 100644 library/random/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 library/random/CMakeFiles/progress.marks delete mode 100644 library/random/CMakeFiles/yap_random.dir/DependInfo.cmake delete mode 100644 library/random/CMakeFiles/yap_random.dir/link.txt delete mode 100644 library/regex/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 library/regex/CMakeFiles/progress.marks delete mode 100644 library/regex/CMakeFiles/regexp.dir/DependInfo.cmake delete mode 100644 library/regex/CMakeFiles/regexp.dir/link.txt delete mode 100644 library/rltree/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 library/rltree/CMakeFiles/progress.marks delete mode 100644 library/rltree/CMakeFiles/yap_rl.dir/DependInfo.cmake delete mode 100644 library/rltree/CMakeFiles/yap_rl.dir/link.txt delete mode 100644 library/system/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 library/system/CMakeFiles/progress.marks delete mode 100644 library/system/CMakeFiles/sys.dir/DependInfo.cmake delete mode 100644 library/system/CMakeFiles/sys.dir/link.txt delete mode 100644 library/tries/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 library/tries/CMakeFiles/itries.dir/DependInfo.cmake delete mode 100644 library/tries/CMakeFiles/itries.dir/link.txt delete mode 100644 library/tries/CMakeFiles/progress.marks delete mode 100644 library/tries/CMakeFiles/tries.dir/DependInfo.cmake delete mode 100644 library/tries/CMakeFiles/tries.dir/link.txt delete mode 100755 man/doc2tex delete mode 100644 man/fancychap.sty delete mode 100644 man/html.sty delete mode 100644 man/name.bst delete mode 100644 man/pl.bib delete mode 100644 man/pl.sty delete mode 100644 man/plpage.sty delete mode 100755 man/runtex delete mode 100644 packages/CLPBN/horus/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/CLPBN/horus/CMakeFiles/HorusCli.dir/DependInfo.cmake delete mode 100644 packages/CLPBN/horus/CMakeFiles/HorusCli.dir/link.txt delete mode 100644 packages/CLPBN/horus/CMakeFiles/horus.dir/DependInfo.cmake delete mode 100644 packages/CLPBN/horus/CMakeFiles/horus.dir/link.txt delete mode 100644 packages/CLPBN/horus/CMakeFiles/progress.marks delete mode 100644 packages/bdd/CMakeFiles/cudd.dir/DependInfo.cmake delete mode 100644 packages/bdd/CMakeFiles/cudd.dir/link.txt delete mode 100644 packages/bdd/CMakeFiles/progress.marks delete mode 100644 packages/bdd/simplecudd/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/bdd/simplecudd/CMakeFiles/Problogbdd.dir/DependInfo.cmake delete mode 100644 packages/bdd/simplecudd/CMakeFiles/Problogbdd.dir/link.txt delete mode 100644 packages/bdd/simplecudd/CMakeFiles/progress.marks delete mode 100644 packages/bdd/simplecudd_lfi/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/bdd/simplecudd_lfi/CMakeFiles/Problogbdd-Lfi.dir/DependInfo.cmake delete mode 100644 packages/bdd/simplecudd_lfi/CMakeFiles/Problogbdd-Lfi.dir/link.txt delete mode 100644 packages/bdd/simplecudd_lfi/CMakeFiles/progress.marks delete mode 100644 packages/gecode/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/gecode/CMakeFiles/gecode_yap.dir/DependInfo.cmake delete mode 100644 packages/gecode/CMakeFiles/gecode_yap.dir/link.txt delete mode 100644 packages/gecode/CMakeFiles/gecodeyap.dir/DependInfo.cmake delete mode 100644 packages/gecode/CMakeFiles/progress.marks delete mode 100644 packages/myddas/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/myddas/CMakeFiles/myddas.dir/DependInfo.cmake delete mode 100644 packages/myddas/CMakeFiles/myddas.dir/link.txt delete mode 100644 packages/myddas/CMakeFiles/plmyddas.dir/DependInfo.cmake delete mode 100644 packages/myddas/CMakeFiles/progress.marks delete mode 100644 packages/python/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/python/CMakeFiles/libpython.dir/DependInfo.cmake delete mode 100644 packages/python/CMakeFiles/libpython.dir/link.txt delete mode 100644 packages/python/CMakeFiles/progress.marks delete mode 100644 packages/swig/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/swig/CMakeFiles/progress.marks delete mode 100644 packages/swig/java/CMakeFiles/CMakeDirectoryInformation.cmake delete mode 100644 packages/swig/java/CMakeFiles/JavaYAP.dir/DependInfo.cmake delete mode 100644 packages/swig/java/CMakeFiles/JavaYAP.dir/java_class_filelist delete mode 100644 packages/swig/java/CMakeFiles/JavaYAP.dir/java_sources delete mode 100644 packages/swig/java/CMakeFiles/Native.dir/DependInfo.cmake delete mode 100644 packages/swig/java/CMakeFiles/Native.dir/link.txt delete mode 100644 packages/swig/java/CMakeFiles/NativeJar.dir/DependInfo.cmake delete mode 100644 packages/swig/java/CMakeFiles/NativeJar.dir/java_class_filelist delete mode 100644 packages/swig/java/CMakeFiles/progress.marks delete mode 100644 pages delete mode 100644 t delete mode 100644 test/CTestTestfile.cmake delete mode 100644 test/elisp/CTestTestfile.cmake delete mode 100644 tmp/bads delete mode 100644 tmp/comments.yap delete mode 100644 tmp/foreigns.c delete mode 100644 tmp/foreigns.yap delete mode 100644 tmp/pages delete mode 100644 untitled.txt delete mode 100644 x.plpushd delete mode 100644 y delete mode 100644 z.md diff --git a/GitSHA1.c b/GitSHA1.c index f3ddb2b45..4182afe7d 100644 --- a/GitSHA1.c +++ b/GitSHA1.c @@ -1,2 +1,2 @@ -#define GIT_SHA1 "880a9989c3fca9bd8184f0098049fb87795fde62" +#define GIT_SHA1 "fa586f8769671bdf084b01dfe51728a5420a793a" const char g_GIT_SHA1[] = GIT_SHA1; diff --git a/ID b/ID deleted file mode 100644 index 5ee7a8b87c30ecdbf06d1f4fb0eb07b61dc46a0d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2162323 zcmagH34mrva@SW?T|3jeTBO!$B^Du2X|y0AX?p8B-uu3X461u(Ry{kdo!J8{T=TxG zyJqT|I;OkVfEpn#1NH(wFc>UjW6Q<}Fvehmt>y56FBTsd%prjfj4>c=V}TYl{zYcK z_cH!p_0rN#eHj^<85tQFnHdq8?@#}!mG#w?#q%pGN6)RS{LsVImA|sGvhv$+t*m^* zqm`9!4pv^E z>}&Vm_(k>k$_wi&D`#Ny=kn1}`1|tx`{D1^Nz6Vznq1TuPXcUbfBV(&V{&vF{_ckV zPR~v+&yMHe_tEL}_<9z9zZ`Ks``PgK-b?rIg&*hj^zHh=JT^PIK02NS@Y&_#7q1>( z%^_Q$iN2jy1 zN3_alpUox=Awakib05s7XU1KF9ba9{`3bSpoieAs^fHi+ypPYy80`0o=wV_K_HC%z9T^mc|QVsiJowK9*cs@nKpyQ&3cKXFn z6Sm{Y;z1mMhgVmTmfd^zcRmr?o1PyZol*<}uV>WG-^mO~;P2&wli1r&?i~ccBE!y;%)f%4OA1x|L0mIWkT)9W!86z?XJT#zuyjOs3gb%;By4? z`0T-9SL|C?R^FIj!p4J@mHM1~26s2F_oMXk;e7h`8&A&XuOEF5mcfgz{Lf+ZzCFt0 z9yOfKF3ye^tHH_&W7o8^^1{nOR##s5mX(!Rg-C)4qMqkjT$p&2=-t8yOA{;?-Uu2*emMt1H zl|rfE-OYq!*l{o~AJ+W%*@>2K7Buv-!!{ z$_sa!O0Cv<>CvpA;W--+t1 z-$jS98pa?0j34-S;4~WI@G6SMxzBw)h|&*0rHRtN?lb>Il4oelIDbFqi~J(i>1GN1zA)1Q+0b)F}c*WqWr+#~IZeGf34Me=c`Kh~3f8A*a1csn7xndnhc;_SymbnY zGV{k*7xgq~)ZgmM{&Q43Kb@VNT_9Gcb2bMQ%Paq9L1-o9-u>-8YJRw~f*$?$Z;x#I zOkm{73-E}}^f!maQg42XuX9ea8;q3~7>YNpFRpCg@r35m;`*l=eG;4bcSyqaKZ*>* zKT)`2=I>isIjB#Lj-mhGjx!^||C?Co_pYqGK0o=4?H9;~7dC9vG^N`sFOVAxzxqbV zxB7t{g;gQe^GBjCVw|k{rkDRA(4!M-0Ei$R#zixh_|KZ!X(rB%2>*|}(f{FQaf&(r zZmQ%sCjX0=L}p|9kEe~r4?#d!9V7VPv!!7=KfgL+>lW$rbhBti%>QI%Iyk$7if(iF^;m}q?Pl(Wr2tz5Z4)MJFTx+dmqk^&rMhUSy&ua zpudqMp1;>uM{ET6(Twi@ji}aF^(3g4pX}gYGQOQIjvm~7xN@+L=+-Cp>np;q`lP;W zlJ(^Baf9@dUNc+))Q{xt?PtG4S8Lv<4)6@Bd zZ3r6B8})M_<*{a6 zowZ4LntlgSYkqUCm^Qypj%M>kQ#qQ+7MaL*5@#*H>WibRhy5n!;-Y4$>Hm-8kORcD*JIJ<7@o?c%aHYCg*9G^|P?#>=wUR_*I8_e19NuALJ)JPplS4>Z}g$7)>Cj)XQFxJ%N+@-t0qjvMBdRUN00f7XQ#(c8pzrC z#eCLq@rWHu-p(mokLlY@?)mYHCTPb;mknEhL`qU^q-_t-rR-4KrPwjjSeIrINQrk^ zf-ds*FC6PGe6KIyZBzcjbKt^p;Ie*q?kc*B>XKP{dHL{Y(e&mjZ#o^w6MaFyG~&gA zadHUcsOc!jxI+}vyY*Egbk|q4NoOh@_q!?as6Kw%Q3Dr_n#uBHesOWuw6lNu?$O2B z>B;=`>J|2JR{r+N$}5*IA;PDDjU<`whe;3Y)R#xoop!`h<}!3PpIkpMf={nl)>5^L zkmhhSeLF#d;2fRWVX0|52OTyPw7|=&n?NnzaeaAp76uH;;u3gh(_4vq@K<35--Ovo@#jxNJg_NeD= zFEdoAJ~^^w-?}n8nj$MV(0P7S(_yh%Ci4->Fvy#=zQmL#b$#O5kwIGK23W?NHhnln z#+n`rbh)%ZGPcH|1`wRKqY(p5+>As3*ly$cqUl}^@_5~_1RRn+KO3QdU}=xhjaEP) zDf!PHxLDwZe5t|rl`;1D`S^w^JVbUMg$L9}g6O{LH#xTVlA%~0W z(>N(w_{mXRQyt(2yz{6AU7eTb7>^v}@wiOsv-7LF-F}qX4RBIVu>ocnCmdVDq)!O# zb|IzX(%Y7}xZ7@94dFs6ytsQgVgK0f6C#emTE-?&Skaqm*-X27E$t{Z0ILz({hi&#uJtlJ2ERVcBSHe)fh->gY7`HC$Y3-;R`ezQ3SVagf9=f}nFu-P_%Gt0Lb zq**^xT}I677)jzO<~fx8@r#q|#Uic|F+IJ!!ftH^Qu>OGc$b`AorO6NGu!nvCKp&V zI#f#qafq2r87#V8HnPj$XXy+Vef#dw)uPKpELeuRG^3i=b(I#;*itvEV*2`OF-}F7 z#tS=iH(n&d>~B=|D_Ocz*)23Go+g>;)CQE)XOnD~@rI_c6jd4p=S zZnpWJzIM7c`K{6eaKmP3(VH!DhWRRA*Zn9BNo9-stGIY7LKr*(*3cLMLTU*=F zh|%mBn*3}o3&^+C4NIt}-5)iDvJnah-TtV-=te6bwELqr|Jef<3*3gB@_P{Sg)84mi8Mh)dSDoBj9lp(&!Wu`aS=om}?At_IkYCF?RM`+~%2 zeG(Q0`+atNoDO-Uf|ajt^^h=&T~p*q&46M7Oj+1DAI#hJuZKMlE8gL3((W5J5-6Ea zsjz|MC}w??QUT;}>SN4=f!yze-1_(mgR7B2>X_s5CO~|BoHh;q zqID^*O7`<{3pG!jA^dDijLpV?-;1+oYvSk0tVjr_XQ$yr8PB(58JALCbc0#~Pl;^~ z0u5t|V_LrmM`sevRN?2V!CS^wC7PCg7MKBIRkVpi>bat_bPBu)4vJZJ!eHh3Hvk{K z9lF|K0qC<^O`9d)(YA~>Xl$_efOV;lnUuusBR|c)VASF->NYhb!h(}Bu!FI?!oQu; zEsw!##Fn3l$M&mbmnE(*`2SS&N*VdgAn)?+BW#M%z+=f% zWai;nkO-2TTI^83V0L{>S!IVlj7(Ii^Fkz=0j#^gt`5w-9$iU>c= zgUVdDlYOcK$Y~fjL&WMbJv+e3xzv zQW#&Z6XMcP{{}bIhopj|Arl6CVwo`D)>*>%rya(x$NybFnP2WCbH#a98 zPp_XHV)_pr6iXDvA~`Q1V5QZ6Q6!zU6BT}>4c z>{^VVPc<61E&J&pCT;RFyPr5nblk7)#KO30`d*TC3c=0^Hvg0BKRK>G6DW- zl4f*H3f+>NrorRaG+NFAlSpRmkUCJdmeN(DGLZN^5V~a`ni1^PDK|c${6QfPDWcxpFN(>K0ObW zk<4;ljfP!--_!Jj-<=G!iPi@bAQyo<{Ol@?u^C3nF+B-^8fN)yOtl>_ok0NvC%u*U z!Sp*X(83Zv>CU?QYn#Mj%5{Le8Zwe&-x~Ul;N7F3fBvoD>P;%`_XJgye0%>j#6(A` zmFQAaZ0eU$Mgev!&mTh!PHZ0%-6|ww@sSmeDV&%ok%`ZrR*?Wegq9(Gfpyvfo9y== zL>SE(gYWKWdWeHKkpEvf=%wv)&aTrrcsXxzd{&1MBda6)#~MnDtZM)}j2}1Vg@x@e zW=jvh7wjbC93}C9SfntK?e}q<4*WctwI}l~Wyh!J1Ob-Z(sYu<oC7-`kE00+%T1x|P^nP5Gn%`M-4>=*@YIzvO znEdO&75kA!iJurz<`D=*_$x77c)vhwlMqp&j8r*XRn==JH@`FwWIOg*2Rhmi$H;72MU<`)ce!L8m1 zUz3(~Jb>>ZIu4H=pG)5`X+yzm-i9=@lM@88ODDcM{I=a%n}F2rH(I_;yp#Qg=MnBr zBEUEeonqcOqwg^lj>dbk+6rXbGzO3Dc~~u8 z4E6oin{q-d-dR*%EYB((0^Pn`HnDPFK3hoRL>2J=Q`mln zu8adlieTQm56{noPmkY+=CrqXs}|@-E@9#r56Y@>ASG}!qAA%8X#!+pnjmga6Raf( z8CfO?;4(=7Zz3rZGOL@UCkcR%1Z0UM!(vNuymIi%48QqR9|iC0sb%~|+mD=2QWGO_(Ml+DaclIoZdvGwq968zo~vyI4z$*^f|stf@c3I3SFF7pk1Rbq_Nkdq`rIeSE*k?)2xrQw!#vY4I5c=prfy z`fKx(q|}pKc+ajLqOoF5I_#&!@r$fsDTnBe28o{y1A|#CVOWSp^D{lNQcHFrQ<=YCVr_+D0uH$2v&#MRsZ1`g9fe>f*t^#SOklmkLD2 zrWYqc5yXUPsIJoFrff@MnQeb3mt~jEsosm|PLJnU67b&AGHI7fgR`v2ZkKQy7^n?6yO0Cm%H>g%*1F{xDvr zSM0Y9`P;js-OtKF1pGHB!9EB!7XQc!JK&iYAi|J}LklO4DNH8ZtFgqZ9P7d@AWQrL zJL820xQvpp`DJC(ITEDrVq?)xr06&>!M5_rjSx&eT{10NjgKM243^=9*trz|;8qBY zh7luSam;`}!C5)?HUQd4pyX}HAnn8g#d#YdPUdZh09S)69NiFyi<7s)8uXpi*Mfq$ zW{_o^Q}ZRzM22+9s-Pf-s{@&%gZ8q@1H_jLAai`Ql?TZ6RTy(?&Tjgo+&S@TZ40gQ zB$jNFhxM%KU<+#0D%G{HW?JR2%j+OcfKJaIbtFJuR;#7RP9#~%Zm4C+t`^I@KK0qe z#k2&HPcmF_>dM!~vjsZRfh7H~J`QRFQbQ%|27+)kX-8l!6xM8~nvRCj{3mbBk^E#% zY!UX-$Yp$u^Dyc!n#}-b6kz*l&Zzh^U1J+!paSqc3?TQ7?B~9XRJ_ua{l)Qq}_OqG< zF-gQ;*2hPm3$6ugsmnWgf(glk?E0yPoS$7@*`+cMO##iWy2c)*z~f*E^U%&$>EMLP z9v;u%#f|2`jeK;ZXYR;|85>W0`2WMW$rq zij2vta04n;850N+w(tZ>e#5K-jq{T72Z$oLsdJ<_gZHBjA<_1Z-_e^Hi*yGZGUATG z8YA(}^%+k0_}e_2+0U-pMuUOhj3hsEA7`u}`Z(inThgP=o%GhqirwE$y5K&2h`Zy^ z^4D83`ZYl%MUZjO3jAzbnlU4|G~-XA6!3rH7>>!^{d@Obf8`hNTkzR;WLm!-cpIzUw-YAZ!A~z>DOM_ z6B-PpbbV&`k5D<5{jY%%)9<*@pa(6eGmtG0u^Jl1((^Aj^IMd9nMs57E#}u077=t^0F_!bR z9$Gs2))q$t8 zU_v)~JK#;Q`RN(k43B3Qk38h$?O-nB1q%T#RIP=~!({=Xq_N zF{?#un+6_TjIp}#JGdBQx^pqcbhEHhtnnmrW%6SHPDL83ca2Gt(fOdWOPzP=Uh#F8ALexM~c#u!}7GH9K zL=C13C2D|OFi{J!aH8Gg#74Rm;){NfEhxqy0I#GVqb420g9tP700NCXAPY6}8J~*o ziBx^8j@TlP6rzh7P#0gc1PKvFEfhtBbuz>lH85+ft=l4tnv5p4s7YthMGYt}fuH?s zz6cuGzn{@>huKV`vC`kuhL?m2Lb4fRhZP6afj)&y8Xy?`tPM&h3LReKfe$S(*PIW& z0e*SM{y!Fr>(|q06gEO=aEq z6Yy^~uOg)MpKH>uzL6k*3B40uRY>W-5RKI-_4i_`sqRNf+U_J$@mISS2omJ)q}K^j z@^2G6VZo&l{cnU}4p+cC$N?^%t1fA`cphNhYD;|l{ympypEkBSHlU{PgFy#bAw zEjAr3-W#l7T`EX>n}+}$g^MyBB$<3$zzz{N^ZN87R})Q&w=mwifr4EXYbCBFOSfpXQ$ZI$xH+C6OEK+>G{7@+vIF7(&2YdZt&68l;3fRd2PfoAu z$NRy4-d5$Cved^-dv&D@^xD0>4)D_aYJU1|O8*1a7%m9RXNY@446s+vW*x$7u+e;` z%aDc%l(>I(etrHb5yX4MXm^-QoCjU%bqs0`UaDtyQzQ0(k{K|o&&cj|NS4fUvzbK= zmdY|eYgg#n>i5!9B7tx5U5F<4OH8f#qP{-9`tnHo_C}61(r}1^L}#fw0J?j8b~%6P zy1rOLa>Oq3nYN3UJ%o*iGGoQD0v zYu8t=Ek0>x!)KRaVR+;0jJfbklwBgr*hZW-{dqPbOvn^n+c73&vzEotxgqDi#T+i@ zVz{w@?`Jo8eSyDxsbGNa;R|d9qHFS+NbZvZ(?RBSlO~%!J_}A)a9&@>=L5d!ou2|u%MhGwqTS9wjaMl(GdG3)@eC){$GUhRGvPV60BzWvH;&#slgiDza$ zGvna;`1qNbX%`}t(m!4@d1fIKJqveS9?BrzuZF83&n#_v$inue&3yT8MI!)r?8(aI zwmymP;x(QWX~yoE4ZhASy+N>EXDsLT%7s$WX1rn!4I%Rln@;~2F?oZd^d$a5i%M!z67sTYJ#$;3amJ@u9?+{vM31cKs=2;{7o9MNHs#uqf$}@g2lZ zm;)gs%=jK2YK+P6HbV*4_K=6Yoz~h4v5m)PI%BRS&6XTcu@sx_Hzw{U+n4p}^6u5+ zs}Q3a4fIXQE{zjHhW(q^78Z&Y&G!4e9X4wL;S7;g_0`L@a|(?ojT#4OEcik81nAWJ z@d?p;tZ1QSz&E!{hE~Dl^P8$@z}xp+^b41<2qb8$N(BiPP|z<}27T8u2;aXJ>@9~EGUz)yPju`d04+9N25quVzqT7o@H=?j!XP8;X7-3VB(yFjfP%1$OwZUzTOf9* zgL$DiKhIv-s%M;f0tQLN_?gR~d)VTRCcVMt=G|G%YzajHYEkCeC-=AaUfquvBo$+@ z4C3b4y;pYkKk<4hwY7}$E!HvSRIK(l!Re#Zw`1asJn>I17yX@WY;+Un5{Q5EX7Kmk z4F1J8ga3`2!B;nff5pw!P5iOk7~DW~AdUPak$^7L_Iu9?@(PZy%ms zPmkwBxN}!Cm1gN7UT(sTfCh5<;^b`hq)lDm9-dM0K1r zSm#HxBcAzgDaQSU?IGc_%VUqnPPYMEp0n@cJ{}=8*d!9xRsDAJ^K)~a{B9E5J3Y1V z8GA}Lz&?uF3$I}}DPC?pJu+E^xl;TB4X=va8%BzbquqA4wtodw7EtE(q= zD-7+CU`&qeCzaP>ht}mDw$AhnmK@U=BzoNQs-n}UK}kNKl)PepaF{h6(yqXx!8AN0 z+tk?XimZa~u^kSVKDcX~l7#$l6*r{5AqW=n=Jl}!Ot&z0lCUlE6&#DzF>khAfQZp1 zH)qB8#+&o5IgB1%#lcTi#x0Ril>ip35CRpU(C%erS!U+JAoh&h6EobKipxrHWyYoY zdGf;cSuAB4hB+gBl8E-RD?7)znvDH9BKfD6_U^z9=w=#&b7|7i%isu1tsEnp7UPhT z=k*bBMOod1KUvn#hW{b{DJ4SCQyNY3nvkZH8=R);cRuc5CZ9x8DM<{3hs0CcSu+($ zkxeOubGgY#aZF7{7s%uw!4;N4E-$5AjCV>HEhix^2(?9gWqF6vw}2zP2r%~SF+3|T z>{||a?T|MOT1Zt^#`iwQzMh>QqAGbUlCZ<3h(%$g(jiQ%`Q23-0<{v@9+D2|{h)>- z%k4J@6GPc$Jvhf?mHnp3o}@WLRp&=M^qBHEwq%Wv%G*iF ztmaFu1gDb5wXCQm^Ri9a(b)j0@$kW9!9$#Jnn9G$;+=<^ay1t#+!HgtbHI4uXy(WZ5cZLnd4cPlcH!^cnE2()I&RWj} z5Nw(kG(ehwO<7i2UW37Y?zsaOJQH~G+|?a*;NfzgFOx|mZ`V%!HxbA}VUd$Ls%Zso z$71L4eX)QWvuY$&b`E>64_oPNT8&d7{{_y)d zqM62;;%8{v%r<#CzLs^B7z$RfR{Py;ggV=fWn4E7^K(DPJ`(ul?ed0Ydq)MRAV5{bs0hkK+MuMfVo&(V-&)wWuMu}OVW`} z*(5Z#?@cfy{F40)JaEO+fHp{Y4(uu3jFJ>Px&+DOKNU8c+cM2jt_n&&Pq0D!V4>OHRksLkANSwMU&u{P>pyzHVN9Ywhm8fPKG~cm+7D4@nLcs_@v?*>j zu>+N2`^gYEn?OgGXNTpW3Uy$J%q7N>N!Rf+*ek72`h95OvrVy});bLXN*?=~N zspVg?DKeE384hH68qY^Rhixe_-F%5C)J~GR?m}lsz8sUR!gfnRHAm}*ssT%~ zvorlpTY6$(kkvqvTPHSrydh!I5L*Upbj4Xvrvw-5qEIA2oERj`AkdzB0|ie7*d2yr zmCw$Pm6HF!oX}h{jW#PhTKGzfpUXXFjC4ta7iEhh~p=O+*$5F7BBgldz2*Z07u@5q=&Bo`(pFgb(5jjo-+ zsR!8M(w^sE4nr5W(fkgVcdQA1BV(a8eoiKb@$mR>^84NH_kvk;a(4B(4#H;goh)^= z=n|*d?_gl*vf`79*6#0uTnj2rzaPx)CU8pF{nYf68O7^ki5-+-v9tJ`CL8gxNAMFe z)W`7#0N~SX= zDLyxqsBRKwbqIt5VB>x@pVq{ZG>~w_h!RLXDcg`XnOEm#pFM2Pmtf>(FKZ!I{maY` zN6ZI%qbOzoX76&V$esr@rv1hY!Gj$RCfXyOadNQsJ6|5$ws)A+-LFG4c0ar9%c$>u zhbd00J$8RG@s5LMBFXP`EyG6t^GIH}_GXEHo*SsgNt*e6{v_Ha_<5C< zMt-9G58IQ+CrvOhme#nstOn9y^O7UjyC|0T1j4edD#>=#9?)Ha(b5=_!rGp6!P~Te zI&Ht87g-B5JXmY>p2q!S`kGs43J`{(L!1caW;CQTW@`K-gr)u^Dt&aGPAPvV90fVl z+SY+B@EK7`hpp25_har`wy-Th`C84<5-=K$wF0~OZYvI+70pUcze|@9zL6G4{|_Mc z`g5Nk|G6>PzNZ#af0$zSjm?nw-xxO@#^>WIhWO`P z>Mvyj@%Q5Ien9(C5{>2hud)fXk6?w2zm0aWPu*Bu|8Krs{9l525Qr19NF{4|lZvllz82&qYHg!&&y96gB7 zfLbPLbI=4t`~8H+e0lmNW$}%!*c-Cqjf0dC?ld;PIf}+t%o3m@o?@*%o!@OQ_|0^S zdp>?&hVP3ujbbBcOlIVn_HJ^T8w;tOY~+3-8!LXVtlYi(u`a%wr^{}yu037f2=LvH z!KvksVS%x>g`bd;yXLQEQ3(%mhLY@ofVU5Q-duj^Ea8+RwgrkTvdcm^3^?62D3IWs&0R0ym&GLGqCYw9 z0G+G1w*sBq_^{1V7`sqzeKqnfoqa!+{zk@bt*)-{nc?47{rczMPK_^MCSJzW1f~{`!0Go&D(9AARe+zx;>({@XwPWAFXcd;j3QKm5hDKfCqKf9IR0 zKY#SYd*|{JpU0+=Ndms5n8>`>_HJdL{Nj-b+_w(nc_}`cK-+Mo5|M`)h`ibxR zJMaCiANe^{$-f`{srUZ+_kHO{e}td^i2vE&@BE4ITsf$Pa$o!!K>FUVY>5`lg@pTkb&a-IWi0$E~fcAKY8Ly%y4&E5G@>SD*izTU&Ql zZ*M%^db+W-_1oBm(F&({lAKD2ggb!%&F70!1Uy_FBGuYGXs_Bsr2pupDFegHY` zV1RC|ee}-OhfIJHUT?ATA*9)cDnLT9tTQn7fYsL3A8l4;HST-paM&yQ z)n+xQicP*68S1scw4M~h{-79-DK;JsH)D0To6OO$90I0yHn9>Zz0F>)HyjNFh-G9{ zjEB8pH5!gx8@<7(9QDSPFHm?K2;VHKq8biH!-3`v#=UBDT=mM$(Wc~$`{ROdM>+z> zIoh;wwLwVy=vTv0 ze>B`Idc$H+cwR+zG?;^;R}|HFb3EK6Cdbz@81+WIVo>#|uIfduwB^Qwq8L_;S1}q@ zzN^FjkV1pOpd5`L!%;S5(8uGUANS#?qW#hXsq@y_>Ic7&x>WQx%OMQkEC&5@ko$GYSix!eZ^%lsy1zy z$Gvhq@LVlNbibD*xT%aP22eNJEH_J9b5xFs{?IBL4~u@k=OrJRggN73)rZ-APsGUh z41Cnz+_Z08=0Y&u?2U_lIj)eC(icNU!4JI~Y---H*n|;`5wayhjHH$o8KZ)kqUD&I zumXk^Wv}x5sGRUPTHr_ttHzss=4IjW=ykssB7_XX$jMmG1eVb@c8v=sVq}$@sF%U0 zCvLmN%nq%)UcZtXIZN#vZbO@}O?v zFuMk5qBn@0RL|mM^umHMguDKuGzW!gki^Z^{F)vTB1d;5O>{5^&-$}Fy z;uLF2q6Uk4V53fHX5hqxtO~J4jD};$fginoRSi%GXfa2bX_!7+85Th1m(TKJ$Qn2* zDp+oV?Byk?(Zxg!PWt&bRe(y2V*BAD4(1#N0zKzX>XV)v5i=_5)2C# z^L`w&M2ab!SX~1cyV@NYY&>!@SpTTa^~{l3`dREaHu8Hg-+MM%D6fQ(=yENO-8iAl z7}f}Cu)X4k)tnF$PbxnR_Q+db{qWPck3WE4>#OTeZ8u7d?_aCgnXPYaZiT~2Z!_zE z5AoY%{$;~xM6~R7+Zz_EF*+c}9kBQCrE_NY(l#*?-5ZsgNHA)kC_*LctAXBL&Xyii zh?$(V;dV+e3GJM-39;uG!d8ZUu(`8>sos87u<1xMKk}66!|cj?JIJ{)*zD1ERTU-s zn>aqHE~h_O$l0=IB-)MuAvHS3&-IXQ?2f{Uun4zIE=LJhq zGgTt0t>?GazOZ&D5^W54?$!tF#GB|e`CkL!c0yoSAR(h}R9I_pGz`1jCym$yp-^&U zlsaQzx)bJ(ZC@N%zO^29gkv_MMOyG8ee61V&9*v0a={85-HPY+%BBSe@3qkFD(`lM zN`|Q@@y#L1o}Hcv{H?V&pWAvGTV_~oMaxKyN2;xj4V!SRr<|eVI7Bi`_dmDx`H!rx zN5&vvRyg9*_E$ZBX9M%m>T^$TuUX$Vjh^+jP&g)5?*x`P3&A*0y%CP`WP}d2XvV3o zkV#0Ja)=HuM>DMTwLmX(A}il_3G2xEdZc=o=de4^3dQ~g_EGWAeg4kvwU#;gYqkKTIw_~i8L{2iQD*Y7@h^7wOE zJz+jZDUD)~en)v<-!LhmKOZtK*rS|>Ob(q#sU+XR-#xPiv{+UIueY=C|{ z3JI-z{quLeb#3hvcQ(FmedG2W)A(T^9P5$8uX>JFViq&_Yed*eYi4b2Z+$Irfqku6 zmv%Ppym`k6Ep666zqWXaIBsl4lxba}0q1r`@0T{C*EVi{!EhIw<*2UNo{!4Kr0z0U zG{5q>m+x$RboEX{KIc7#G_fAbgRN2rch+`pr*>`5b#x;?W?(fbxwrD0|H|5}_rA0- z_~^H8ZGGWWtKam6`=5Mnb?bYcZhrXI)791WJ8Y@n`|IyRb3i@HA@SL2$VH(gsy zd(~`Ojwj>kte6Bn7yJBp-3of-F;>9eJG?dc4L@cp(9^B8wGZFEea8$ykB!H_ z;noIhUVR#P2*hB|J^#Kt8(Vh}K+J#gq@D7#~CTsD-w_^7&tJhwgo0=Q$4o-kS0x$K7T_OP2;C3-n@N3Cz6mbC1wGA z&zY#-UcY0?CDO=%tle6(xtzgF5>vf4VGzu^-INra=M{7TwcN* z8)3`1L7=gyH=Q!JYuUJ#+|()hbnDjludO<1u))zPq5^*3(m0@s*KR#^#p&oO9-x*Y z8$hj&jssm^s*aAkvNp(C7DfPlZmI14cr%a85I8AKADa z_76cgOk!NY1^`x4P;g;_Tft2U#kA;U%q2;@6!!* zmN|ua1It;~}&g_`SU)ti1!QYrfzvx`H8baib` z%&6m3Tn}7FnE^tb9iMt(PG{5u!1(HTY4_oMJwe>_LMp#z-xd{wtyF5k&m^P9=~qXs zXO1;5I(Vt1rqS-M))d4#C($H2+k-zw6OH*lQ=J(*u#Rd?D)POmzncy^E&Ho&odvyW zS9M))2R3;D1T^0CdbzhlN$K#;!4jvaT_#y?cbR#+SjweESk>F{o!-aCDj=ch09~FA z@o6K~v)SY)eotppPiIq4XH!pSlO40XtS!x^#dLGTI-QLgg8%+oS8;-EZDmu;7BHJ) z8?7GqQ!EO9x0SKQYSuXr^!v8A08?jgj-J|}lRz6zVVBok=bicr{!-f3(debw51 z)!O}q)ZjZ4jR1G`+wL?=jV_>7kdEmN)fANRb}Q!G=BBSxt%mSjBy+(}1@ebrgG`-E+!5>PI8 zL{|ulZt%RuC1Rj#7cv;J|MJ^O!hDvoAjr?qfh`#_L3Di>gnIG`G2UJ3>X_rTU+MIBH|t>mdMQ zyE3T3{VsU8xxE{sX1c0l2U-Ces!|5v`v@S2f6F)kVZ?Gk*yZGaATl{1h(Zns(<}!B zAj!U76n?P8pR7Z}T zs$wV|J*A^3DhxF)b?8tQs-cOq)*{Nnv9eG#G$t0ULrGV4T&OxORQndHeF=4wR#fPS zAyy2fL#42&goV1JClXHf6U5#5R#2D<5S2m{lgH2_0D*YYN(zVU#4=s0$pIqCT%yoc zmYS7$OOTfo(Y}mSf(WP8A|fy&l@APAT0{xc(I;%%7tu2dS__W7uRFv85IVRqrFF;z z8tc3r>#W3zFLm@}AHilsFqC6sT|c<|q(zi49|y?Pq}d*t?0<5ds|s=Ra@eiaHpYR zic-yrsJ7&if;6jROO&W$D1&r15FMpObSPCEDpih^Do5_FNTo4QGV7eGzCD74cdbyj z55?lKx$QxEQXST+x@w(>wN8;*r%0`A)Z_0^&4>W}c^H87c%o7?Q5l)&?4Ic6XriP~ zl=O*;#6$;cqC+v!xjWIlke=;_Q)6;wp#dPhooa8V+S{r2cB&hSsdj&=-Jfdrr`r9g zc7LkfpKAA~x++hVA8N@M21`cHkD2mgrrLj|{FrIyX4<)#c5bGcd#0UJ1Ilo&BR5yA zJ6F=@s$}Qdm$?r1Tst?{!Jg}2&vmfp%8$A7W3Kvet_+&1`kO1q<|-faB^IiD%vC<- zDj!Qmsf8+~g>rqNTwkc#A_CW|&_y(Wb}DqCYu!QzYN2c0Lf5**rW}kHI<^a4{1&?S zE#lS1j4&04MZ7JUVd!8lbg&mX*b5!(g=+1Ej{ZWof(u>z7AhYLT@4p{R9K9aV=7V$ zT^<*@JTBrr-Hab9g$r3PIiC70hXG8=vh@;>SJMEzng-x^LmWS~S{Vp1v<~5!-LiC& zYL~*@*2df*f}yRb$%$*{)RAql0SFyxa00`hF93KG8n?KG4z*E%;rEXK{BWE9#`lGb zR0>c^m1BJo87fsuMP#^uqm_!D0z)WO8y9!jgi^I}f#G-D07PKa#>I6_A#4yG7p-uE zAw0za;pIcEU=|Y359zh>ZR~ImYcHsZ?30MlsxpBFSnL14EisqnKT! z_sy!63=F>o2OvYKR53|AXAL@L;O&dI@oH9BUDuDP_FZ?hp$wPbA=k`00=+SS_g&*9gpW| zD>9VaViyb*I<>_WBiW(>SgJ$mP%Sl5ks2vK)b!Sb9dv`OmNqb?b802SWGv&NMlmp? z4mD^Yrc#F*w7?L4a9!FnSq)kgkx9tg1zKc@FmJEnn)YJrqlCF}R zo&xE{g(n|`^d+9E{!qJ7Q4vb-V=9X6<&Ez)v8aNzv#kMl#V)I8=w@qSDs~A^3H|Co zdtgajdrNVT#s1!AU+OwQg9OHRbsb>S3PRF>7`!}0rBH(w07_)G1pqRfYT*Jy7+ve8 zq*jrrb%&u=vO=w70F(|DiCPD|R%Ku7?5=e~p{BP&jZuYKV+u8T6nY+KVEh7V0Ev4nzGpLt#5c85->KaxuQR2%K9f`WWa8-V(o)OQ*NY%jul5O-@>imAH923{(Cs(>%J$|F7kQBP^#4$fZrCC!Qz|+OO(L|oAWyuA#;pi>&pSb43$X;TMI9- z_NHFc3@v{~o5TwEQ5$j7Oau!N@nSsUuo=x!T}>+cBMY<)nkvItx++Dep{nUdi?%Zj zfL{bhdhFnR5+RVz$2YLL#)IT%4CA>izkMBzmWD3gLdeE}*XV?)mDaM)9hZR9HNB7c zdSMzJz#awBQ3b&;1ub2n8ObU$3i6isRMqTA)$B;s>`2w@NYyN-{Pr?f+f&k3b*rI*M$iqxin%24$Rh^SDfGRjPPsih8c@?R=QAeh#*w0ez) zJ3-55s(5TyWBf`mRvUl;l)=kk&pgbsL;{PjaiN{(yv@ctYMwEAK4Nb#g>VfqaZoXGBsDd=6>JM2qDne1?giSKZ> zoV2??dtQ0%(4f?{%MjhN*D~62py&kTe57md?k1`+oHnz9+UnBY#%$MCYCjt62sV43sk`HC6uIN`E@Q1kAi?3Pf47<3-R6xr z>GlpgJE(u7F=chJ+FwCv;1rSCd1N0V7d)2B9YMs{gR9n$$UF)>2by`!W zr*xtmn_j^|(auh^vlH#?l&-S5Z0VZv z)T`q;06!`Kyjc=}HwaDBqkt_p0B9Xz%mG8{NH<%%I(RwM6UNiw3XoRRC_U9t0pR!2 z0Hh9H`1Y-+&6TH}w1`rw_R^^uE~m9}U5zkc2-j=ndM!4!sTxoKXdTLR4HKBE7aR%m zlVheH-C0uK?Z^S}3JTP_p>;@KX6p9=;D-``Kh@1tU;tExO_5q6iL;eywiASIVIA&0F8~t!q!e!rs9A{MyFGt>@O(e)*mCuXwtC=ku$# zzqo&U{dRm|@NswsasAeZ@7UKJ(nA+vP5G+!L4`FQ#<{(>vC%z-1cK>idtqkn_F5p% zKnd1fKMSx3&0aA{P*1VntMFW@mk|TF@il;(WCm~(6@Zr!185z7q8f(OfmV(Z&qHsq zpRw=V!Hm~dyi0)>*@bujzG0pObt@S~gtYh?B$Km!$4=gYH1=hAvU>FF?od9pc`w?F zF7J|t)paZ0&E~!M*w03-0gxI7u@7wlL_NHZ)NUtv?_KM_kjDz%7LobX8!V)a_toT(_OiRwp|ZncnS!CxGv-|2W|>-3dOWQu7_txUsWrs_ zZjk|?b?7`A>pY?>zFGU)hND!?FMJn5G32Pl*9jCu$A!n;r4=0)yHM`w&~d4BT-5Nw zllxkSoIZMLK>?sebQmg$LGGzZ1%T9nGp{#W%^%&i&btv^*-K%vd^^n}Fb&Az+$jOHuqk91S^w4v4uhzlV zb9JxQ8O1?chEh%&JuqY_C4LwT9ZHGY1w+;a09vUIKO`?JH+u!H7=fX04qKP}-ak^49=+ zbERai6M0_y(^YR?`=e5C5u0t=A;{fxV-Z9yBYhEdSX%&(QpT-?E&>bH9C~c(EmU?E zejjJ&pw)KciLGVw{HQ(eY^-tG`OMbZo%LH!*FV3{ON`Aq%gmqei)Wp^)zx&`31j^g z&)WmyoXhO2lfTbMu5lwj>KG`&+M`Z@8T9#Es~=h4c=Jwkyh<5t*RyA&u|LN;c+WkZ zEBL-o1buY|Ld>kr4`d*Q*FdWo$XrZ-?5Xp3M&W1_L3#DtVREKtwt34uAEG`wbF>ID z-o2gM*Ju0y_^D-&&IMW;DF>h!B0Ki|KPe)iBVcG9BGPeIB=xB6Fz&ho&c;M~(y_lHTV*A;A!pXRq=JhNywQK0pINy06d6^arw;=?_E) z_6M?s3@`sV2I<+0PZCM9=9cwEL@oC9Wd#8CH9!-+OwM>-K+4Cc z&#gqMLrm0tuCfV+a&4$wD`J79`1&>z9Y+AT%?jU{Qj8Evl?kSv75QeB){#8e?W`kw zTbd0aAbF+AuNbk}sqj7rP^m-qS$&N@GeEQ?2f;g)!DF z>kF}Ff+4{*=8_W(Wl*UMB05Zpi20qbuPFxGnUWY8C(EpC(jN(l>2t!CmLwphPrQ?0 zsHB!EsQ{!|6pw9qFvdH|$|j*SL1@$ob*qGLmBlC+}Y z&Gtc>RW+-jN`2yjq*5J*ky;} zs1K4vBK8SV;rp+?qq|TL{FPl@`|v|RIzKdSrLR^OF5zjl)AqNErP19+w3PaCcel6WMt7TdWu)@zban8^}@PcX|zj!n;QsP{WfAJ1-Ge7TD13r1+;_TK}fYoBgLXgFX!7k zdn(k_zUyPo`iQyLdm5C|S8G~dgHrk$l+xFrl)hTi`f5Du*Uqy+Qpr-4pr*6Fn$G&Q z?jvfQplT`WYXnMvqRj#boNsrdld7y2!AX$q@h7T1CedWs?3~rE)1N4<8bH$50Fu52 zko2j-59JiG=?oKnwfpqd?$cL8PhSl^{i&`18pzRC%MV}SQnHk%L{tdjx)+%$d!{;+ zQ{4ehbs?S6M#c>)@Quzqw`RIindwG+rn^6aC!|W{7BLBeq5BXGIq1)nTQlX>Ou0os zfwZFB(qMqT`u_WKC4H`>&y{qn%)Z&Vl8!A-FqHJUl0H|`=Q_}H9ca?N6}9N~7dn&+ z9m<6c!e(+fcsYCg(P=1)P5IIlJn)jPni$-Cw27RrC zjQ*0Xwf8@@@QAI(b{BX+$tD7gv^BoAwz<)KT`qtO_|ew-mOw7P!C+2HvSauCFo0ml znAj)7Q~QmfZ?H+lwvM-b0l@#!HeZ+wp8|YLT855?4YZVq@?cX$dBC1a8WLABk0U6C zjOAcc#&WPJV>#HAvE+dTtyE;&o`Uy;^)|6fu<+-{@_~LMhsWTxm~xWO;rQ|3d)v~I zvQfW%!|M-PMA_I=uIblR2KsfCftqCp`gN6oeqCjNMcrK6xlNGF;t55y9ERNZh<|z@9WS{4A_Tr1w;9v=3!po z*CNUfH4obnLRwLN43r;g9vPef~Ud&{&Y1+w}0Crx^k&OcEC+vsZ<$= z{Z%kjpw!&T7umIlGO*m^LP*fr%|Uul9xQ{D&1!BPaJ^KBn-+^Hj(WGGs10^dsw~Ej z2sitV0Tx(a?Iwy$T^JuE)&jw$+j2_{rKTBu3u-y#v(1X3a;SDuUQ&`p-r_O3GtmGusow+; zS0;e4)o3CX`NE2uUc@s9`dG`$@tGIR6$96IPExH^)>=Tv!XBc@YnW;cQ>{SMOkAo^W#u>=uZyTtE+5plD)5d8GyA~z@ z#ZVQ3ja!C6ZZ8a~LYZ7BlSBAWPP)9(L> zR(y^w18s}%VsKzLh&}ZHhW<62!ND$DPib)%4@ZdH?5f}6IT`1937?M7cy&OJwVnfL zlBy55f9+mmuoItG1pxdMBmy{$OS>}EtPXUcDZJI!b8U zhHkd%u=Zp#MZF>ejWHgmo5TQq9suzA8i3av0Q}Mmz-zEtSEpKnTWMBi3IJ_Z6c!lT ztiL!xrOHuVzhXpn&M{rTG@^Q-ZXp1oTQuf+06@lGmkBVWx2p4N)%i8M6)#W{*-f*` zQ(XjV)#w0}QdtyhJT|`Bxd7M;`#L5)e{*|4ymXu`%?d|&G=OaV;tI8&ZO0C*|^_*reYUFmpRgH9dwBM~DhGiBxv zTIyCB%)<5|8`GITSE-k2z@=0#oiooCbvh071}cU+*C{LvzQVc0+YaVY*c&ducPSvj zwF8Y82OvbNpKCCe@a=*6xd3P#ELm=z5_2v9-Du5~dFtmH%yk1wiQJ{c=zELKU6*um%h5tNO483*AGi4{NaGw92pjrbjlIAe+yBOB)8iw)W{e z>uc+G_Ph9ZyRS+7`_`TAu5UOGzW)~YbH8`(X^MRh7hTB!+XcQGD8bsm_W+B~?2d1O z#;Eu8H&caC-zC{>ALVIuCIHWC?&f=52SC(C&AtoJQXzs!T$m60DXm8qd@%NhQTuik z%j(R-0AAw&fIeP6SzXHtDK(|v1@LqP{dBQ6_JLg|QUJ6T5jtMpR*ZcO4`Le&d4c5} zc`^-oI!@~m+YzrHD27vd&6D5lpvp;RxGAR)3oG}%1>km0hT&8@0HFbZ77;e9!;jI` zIz%-Nxq~f)$&Pl2OVBMs0G5jQeInuR+FO;^o(d-bx98=XpvoZG(T1;v=IYe|T8DB> z9auMiE@d2Il9Y&3u$OaPt%0OI|- zwEL!r(lHPT0YfVlo`E5is>0|Gmo&THf8xW}YRDMcT@ zE!VS)VaC~Nh8mjyKTK>$R77-oTL7V_R;PD=rmg6F@6WUq@m>!5I^Q*D zVrcPPjt)+7af{c?5E!i^MBwpe{4jRQeG4`ai5Ob+b~ws(SXNn3^BIU}cE6XhyJS(t zc35oWv>;*9T98NowP1`JYqmCp-@XD zu;Fz47%77Q2!?7XK9VYxDnCZb54{OA94SBaCeU!C{D2JKEPECKAc38UW2pY_=3%l% z;Pgq}p}N0^dMzkCT$Z<>!lbXL3}Kbf$kXR$zs_SN_-eIcDM$4sm7!i80-)Sbjiv9T za3|DFK#1_P>Z2&bifb351k?*Vj9%Ez3Sa($Y#asBH z*KdaU=*dtWQ2?Y4hQ-qnJquZH)eSJzr$mNo<_Dmys95P!B18HnbSOXcw!^Sie$=X? zYLy_p?J(4LK`bK8(=pLGsjqDe^|g(mzQ_qc_@OUy4kvoBVv`_rC_g4TqbACaiSk2V z${6a63IIYWRd_n|g2ZsDo8l=4o=m0aeTm^z_odUgF>kb(UY{7ohchyfoU+HxTTo@g zS5Ad!clTt7Ia~9!fM3}4uElVw+bgwi6S(M9kzR}#@@Ax`LCw`e0DkYS_G>U?Pp9T$ zq9vsj#@9Csz_+5N+#vwLfSVcn=YH3-aDk&kwYUNhlI+Dq2Dcgh1*W{Lb~UaJ^@6}q zjjKa7t`60>I#lB-B!5+F(@W>5_0_Fl#kBpUV;KP7gKz`%eQO`Qwe|GP?~kwR5oM-@ zWG91LQ!zv$_z;|82_&%EChWUDqtO-UF1Q7PIa#ROAM-RuvXM?ThG~)DZu|0&aZ~9Tkj5f}z7SkQJ@a zTLA#H4jo8+MW)bu0|2xR9cq1NrqG)O0JILB9Qp>R1>5`Xn}fu0OrNIV8=;D!^9jq4 z)S>b*RQb@yYl@-Dhdx|W*e6Ilr79nG`t}$)N$r~@9z*5B4qYBY<-^Vs9z*A~?XW$D z%EwR)Q-$8f0HAfKeAuSNx1zd%?Sx>cd<@0PWRKnWBDU_iR`iMopA}UMl@EQ8wa`l- z0JIL(AAE>b=urK^7e58V1uYbMjRb%eP;sF~snTtj_&%uSt0?F-lR~eV6nf31&}$}z zUNf|ay1rMds@mf(T67%8lG6Fk)iOhh9tE@M4#mW47JUh#P!mMq z-*_OY9aC;i;vJ!8a_N%~g&HV|i8IlYlon{f^U_{`$kdR&08vbFI&{ZPl3HFR&zm<2 zeIKGwdq<(~LlkP@C|Fj7Xca_#AEHnbMxpOR6l$|5^nHjzZ5C*K$1AjhCrclMC^TxX z&<7z3wR;qN=Rzvgd8*%}DAY1i=z|c2M(!2*AVi^|dc{n2pT_1D`XGd@fu8iat_2!> zSIkvKhcr!cRSYlA_RXzCy$K3Vo8IP-|16@qGoGOCd{{rxvF|El%7G)jCv|)Z$dA z#ffd;?X@@CZ*th~$&tllgbEPN#6`uXP_yoq`Z`1a#Ckd$SvgA$mg7tB+O%xe%#SJ5 z3KIz&QVbEfQteKqz6DXL-KpFZZEsIUdOFnZRI1&nRJ#+OvDZ38LzNmRRjS>oRJ&8D zuRN4$cPcf?r&POBsdlGQ?M|iIo$Ow==SSbIex;hBO0^gP=!a0sCXmVi&iZSBXiZN( ze{)$&qbdv`I=yH1)fU(C6-c6E_{qs3&`45 zs{N!?b4jVMNR;}DMED?hSVkJ@!s+ehPapm*hn}1I$^`jZgYyQJ`U*varSpDn?$*^J=f;t8D2r5~YUKl=`kj$v4HNQr#3_ z#uNLU`RhSik%YDB4FHKo2AVPoj&(03zv(LphEu4&**sev=4zNgFk^IEC$ zLoHf_N^23_B&kKKREt)r7OhgB&o!C#{7@5CsUa_=ny^YWVU_w0ZmA}$QcYN;ny^Z4 znhRmd4>e(xYQie@#o1C#Sf!e<>^W}VtXiW=wMLa{ekwKOrBw4%sqcN3YJRd1JE24Q zq2{Mj%}=G8pGq}9m1=(CsZMDYne%k0`KeU%Q>o^sQq51Lnx9HFKb7_o+U|@>QmIh( zsQIa!#En5R9+A`^d;7ec5*saB;@txBa@mCC8-m>QW%H8QdM zIgY83sZ=9VsYWIM!qXX1!r7>)&8eKZkQ9=_ty!TJay;*hhNZq)TB?bvR1;OHCaO|R zRHd4zN`JYOq*5904K(7e2CPyISmn&wN=ZtEcGooPrJA=&HE)$_-YV6+RnA@P7fEfB zk;t3Wk(fL8SgE$Ka_&OKNNW8qGRz{7{k+ikSWB~%xDa8|0}tW?8Usi9h> z8qP{JoFM>r*1q?)d$!efubT&9&NgPQksU_;m+k>=4|jq9c323=PzvsDZWckzTC8H} z0rF9?!|NYm+nr(YMu>oRIkYKgZwa)A15L2@c*tKs_Cmjc^yQUNaiGt-k9MfaKeNL9 zA|UP}D?abCR9u32^tOg7s-?)G=N&*4G#+^k>?;J$!>^c2K9@bU3TY+g)I6zz@uH;v$`84qg`W!XW_2Fya4R(?(K?9?Cx{1R+zKTb2eU>b`P)v zDu{O?e2aTfI`Ev>GdreWapQHz)3rC?K9VN_QQ92%;n*|FgJ78uh9Jv!9QQ{1+Q+>L zOQ`4l-uBY$;Hotjn%xLx7t`;gZ$s1A&wc(|Hk!{-ue}@ZrJK3C`7)b@Iq((g{APMk z*3a3^^yZsvVOIheTz407#|CoTror z!99c2fl#Rf0e}`!j;RBoQU`*4by?_eR>(@fAXupbp;8AzHJ~4v_ECRAHE^3)l1c%m zJf>Eo?$p~*skgz_Uf&1xCsgWBsD?V{)t^uexk*zktS6bCRwqNHPKHXI4EE7#Ax;&e zIuR;$5>!LaQS}*AL(frlAyn!@sMLjE7B)|%zmLiroSLs%R6`o8f|WZH1NA6W>QSiF zqfn_wfmb}8WT+*-@^49#6r#(pMQbHX?fg~g&h{j=ys9WQ`&VVyMs+Rdx~X0OyQ}9J zuV#O~ccU1(ZmQY8QnP=hX8$U^9^K3_^#YhZ)sv-m{z{*VuGG$7shz)4JAb8i{z~7E zw$HT-9Xfl|&R?mWzfwDYrFQ;G?fjM6`OTc{=@^GCbUV;$_UD;pE#PHKug~&aofdHB zi%OjWl{y7@S3trzGA4NQ&8qS5|uh6Ds@Nz5ME5YIMSx)w>m7UiSw|W_si=2sQh(dl3Ifoa`lZ=>Km!lH&RVqfCx!#K^Z^wn>}@sRO%I})GK0I$Fo-5 zAeFj7Dvher~uuaTV{W}a8-wW!Q%k)f+s zqMEbHXM0$6QjkBZtI$SvNbs*@R_e&8=6)xjevL{U8I^|ZR_3|L$<|$_x+?4?20!BJ zo2WEww^C-y$_X!?N)O?<<%L%;^z9H&In#1ckEZ+M5VroN_`WR`X(y%O;qZe zsMI&X!{)*~bw*U`jHuKZQK>VcQfEY^&WK8#5eF+D`pUI8pFZ8V6YPx#&J=qT1k82>*F~43%qJ$xzA4`+*kKwir%Y_!6@M+?vNXLo{F3 zJRYV~47a$Yh|t0%36(+0Q%9!k}S-%1{niT4CS^OCu=oM z)@q!r)i?=2TM=7Ot;R`Sj~0HxE-waZoMgAF7%H7=daU*Od#$F&T1}5URO1F(Es?d} zhHnBz8_ChQ zJ=X)T2{Z`09x z&{~75Yc+({L$^03sVykuy&<$#Lujpr&{_?lcFy&zRm*3s!PB)`K5I2~)@tgk)zn$5 zsnb3hA#@a{NQsVEs z8eD68(Kj!kOO4uJYj1xgDKtW&C)yq%$XZbQt9^_`3OM^~t@hVi?XR`kUu(6$)@py{ z`!3q3vR3V{wc1~6wZC$7*GhF^R{N_NC4J}B{#vWKwbp>{TCJncg@he}?pi>q2!YqhS{YF#CS+)+sro_T6at<9L4t#WEittWn_YixL} zw$*y#C$*YdYqhP`YFn+nW_w^n`|z*J@0yy)l)fHmP%b>UZjDOs&wOUVWwVu`*23~92 zcdZuGS_8e&2~H~1q*|*DwO0FRtp?Fr4WhLgL~CylB`IT~22p#8)sLDQL~AvO)@l%~ z)gW4{L9|wbXzdN6B!vpno-8$a;;vE*ou_K@tkvXMtI4xglV`0a&st5MwVFI@HF?%* z@~qY5S*yvjR+A@tqb@Ge77xdqNep9cEMp`!Uw9S1G}dV>l3GBvgcBbZNm2`lpiR_D zX)pQ;(Xw3dWWQpF)|zZOR~$(#AlsOUS}7;qN=Z^`@K#D&l|9jFrJQIG<-}VlNoozs zTD4M6)Ji!~qvS+iKA5Nta-ufKiP|71YJ;5U%LfxRIr8;6=?h}z*`p@M3Gt9vbXcO3 zfpwxbNC1kV98;s@M2(UYHA+s@D9LNlxiYrLqlIu4#&kC+oogp*lmxKgBOF#~=kS`S zrIG+jZAT?k4U-c!OtQ0cq{AIgx*8@Y-Z1(96ZY=Gw`5m+-#w4}`<=Nn(wrGa(v>Wu zGY{Yz;o;Yh^D?&Q%;?U|Sm5NM8u5q)n(p4GAy|c#7#qqw=13Y~aB$^jLK2xuV1h{? z`6En-Q+8QNbQLHUP$9?^v0W4om5GBZb`?Vsmk`6uFWN zxjt*{-MZurZs}MvnzAOCtVtqkBax?NmoE7PENE)7$hvR~8eK96js--IwMUP-WDaiW zSTne?HWHb>1D1|8(W5P>z2eClYr@64^qMAXtjQW{vc{UMvG%M{mn@WT=wyuw<>U?2 zv}cVqS!2zh%i6O>UGfQ3Em@=4B3`v*jWt!l7PvgXb^`kyV<_<`w4yKWn1Pn&`47x~zGkLrrv9 zdvvKwmVs@O=&~ldtcfmbqRX1-vL?E$i7so8E_I1=s+eARgp)OCWK9}bGqkfNeyoWf zYvRY6__1EIj}kxD#E&)cV@>>66F=6(k7nL`eULZS8wVwH$s7E5NBmfmG}apjC3MLQ z*|ta;Ym&yAp`GzNPf52Xc&tepYm&yAp`G={&mAOXOgk%%mK>E=ehCe}Jkkc>|j%p=C`YJE2RKf<`>iWleNh6J6Fsmo?F4O>|j%bg4@eOV?goM3*(uWzA^Kn&`47 zx~z#VYog1V=&~ldtcfmbqRX1-vL?E$i7soROHJ{oul(4+=9JTTbg4`Jj*+dgZ%m%1 z1YPn5@U_OHOI`8?EQA`O%ZBK(xxg&Z5M4GGK$ne2m%3yrFqAbHZUWXNZ$P`#6yX#@ zblDJH>X4*#IMyYeKy=wKz_KB_Y=|x!qRWQpvLU)`h%OtV%ZBK(A-ZgcE*qjtn=pMt zB)V)!DjROpZU`nDg2{$pvLTpkJebrai^Znq!DK@)*^ohM+dH#lQzL_H$RKS$iPsjP zV?)Z=_-IF6G6(ikAO6@7IyR(?4Fe$Un|LUtql^tHW5WQ)hLo`(R&2--8_yAS$uh8? zk|Q?chz&VnLvYxX&gjr39!iebbVsWUhLJ9LgE&we4SG)B5G*#OTkSREh>aZxds^J- zl271>NRHTej;KrKK-H2X+LG441vz3vj@XbRHspxS(lH8M@)<5Hw;@(+$Pw*Jj3_1h zI5}cNj@U5Fv0<2FLzdVO9%_N_YD`VS7t6E6hAgomOKivz8?wZPEV1z{QI{+O7JUs_ zVndeLkR>)`i49p|LzdW(B{rTV>JsH7OKivz8?wZPEU_U=Y{(KDvc!fg(LUPgE0HX* zAxmt?5*xC_hAgomOKivz%@*|KAWLjKOVlNA@asIX#D*-f@hnl7%#dx1EU_U=Y{(KD z!o!B}u<_f(b;(k2RP!vcAxmt?5@l7pb)Lo!uW7Qx#1IPdXJ|3d`hO*km)sqcnu+*0T{0>LcE3$uknG1x?~PqoA^M)hD@&^(`yLv8bZ9r zLp)uw3{)N=UPFl25aKl+;^~sl;FMstu3J(O;x(jp4fky~e&4n(nI#7~5Ahm8yoM03 z@eog!d;)dpAznj>*AU`0gm{gIc)H{xsairjyThxN5U(M`YY6cgLcGS#t4$WLWO_~T z>pUX9hWO6DR*h0pm&A7s@m)iF*AU+|L7X7rA*6W?X`TW(-Fr&ezLb8ecSF|Kko7fW zeGOS(L)O>$FhyOm3>-cgrr416HDrAaSzkle*O2u!WPOcieY!+Bb?uc$*4L2rHDrAa zSzkle*O2u!WPJ@;UqjZ{ko7fWeGOS(L)O=j^)+ODie|W)d|%1BsZ&oN-V5DXp@Utj zOWxpCfq}Fya65JIv`?4J5KS$R_65?uK-w2b`vPfS@U%~tECt5A;Ax*Oc>`LW2E4S} z+xX`-P1+Yc?b9W1z{DL$`vPfSAngmJeSx$ukoE=AzChX+Nc#e5Um)!Zq z>2z~SP#>gyfwV7>_65?u;Ax*O`B2Od!P7on@&>E|18HC2R_H+57fAbTs`T0-?F*!R zfp{-4h%k`n1@gQ=o)^gTf{z;1CCf?mkmm*Ryg;58JkQf5pTV9;o)^gT0(oBWae=zT zGsyD-d0y~5PnXOA6KL@GPM5ray7W9Rkmm))1qSlG;CY@d`ADjkJkOS3z9Ew5=^Fx+ zpf1Vt0s&qiu?s#BP?vlLmB&E9K!6tr@B#r|AixU*c!2;T4fENhx0s&qizzYO;fdDTM-~|G_K!9hqi`NGMULdgxM0A0OE|AFu?j#Om za)C@PkjVuyxj-ft2;l+)`U0t2Aa%3I3$G7iwm_~H7^4@+)dIO%AXf|IYJprWFbXe_ zs|9kkK&}?Z)dIO%AXhWX)$4;?Es(1PaS|HyFw zDiB!(BC9|~6$qsQp;RE03XCaJLZNdHM8bMkumaaubhZyw9d6w_dIkR%0?q(G7sNRk3c zQXokRBuRlJDUc)ulB7VA6iAW+Nm3w564X3xc-{LTvArE*bwZwM7XH$m+OhY$;r2c( zWnUS?c6Y*t=%- z=6FfUY;Kh#XYcaR@Zf$8t}$rK*IOpz@#sVM#P4n0p6dHO@i0ppBDx#$v5zfjXiFN}l7_aVp>6j$r~!8ClEw1vfULA7D{aY2Te8xY zth6O7ZOKYC&7_UfW*x6QqSKb>v}K@VOLW>2owh`$+FZ@YQd_ySb?Ra*kCkl6N?S%o z>Ps|y1~5WPR@#!4+8pfFLsr_7m9}K1Em>)6p^&G+M3;O9yJO)-+mcX+5b6 z#znRyscq@oB?Bc}lGK(YwIxYyiB4M{-`EnJ+RD$jOQO@3=(J@hWJ`3~5}me0r!84& z%V5Wrth6O7ZOKYoveK5Uv?VKT$x3bE>-9kz+LDI0q@gWoXiFN}5`VV*%uP%D*{=Mc zPa4{ihPI@kEoo>=8rm|Pu_gXAGr+6If8D+%4OK$FupZVTO3;E(19FnkExwKkVD&9| zX-gW~5`MOXpDp2MOZeFmezt_4E#arxKwcYUoh?~s>(}VIWDXp|H(D?z(-%o-OA^|W zgtjE1ElFtW&s5YU3&jbLV6-I|Z3#wY9=i7+CvC||TXNEtoU|n;ZT((mUE)26OZG2tzrmQb}NRBZ`WTSC>AP_-pgZ3$J)vi9wcP_-pgZ3$IdLe-W~wIx(-2~}G{ z)s|4TWjJC>sM=O+TV~`X6Db*MOUBxgu^MOa>M>I==|e=WEs?7ddV_x$lgMCO9f#vb zEkfCrP_`wMZEX{B@}^|8Eg5a=%~Do5;2$vTccMjoNti64|!etR>{? zKVRRH|2 zwaaa#r#w&b`ig9}>*7q*NhY{_vAF)XeYC4@>n~&czn_d6x$40Ynm_9q3_ee}Za4-Ff z`T3V^&ThPTuXMh9Wwdzq-r00EfBN{%>xjc1nmn;No6W9`cDD}~s+-+t@wJDUNK7Pa z9Ur=Xa(?~nhH|<1M*TFME>1tH0w10H)MmPPQ9sW|i^bua4znK59gbyDMN9C3$tUKE z@zv)JySJT9r=wXn)7T^8&r|!-_I;z-Ze+NwPu6W`=cDV>#ofhRzZ|CNZ~AdO8eJ@A zE>WpRwGO!$^%~tXosWl?m(03Aw# z`Y7^cxt8I0Hr^~|v)$~X8xuejbtBaTgeVEB3CvIuR1+YfB&a4pLP=0ffP|8unt%Z_ zb53|Qf%{2;>P;E&%kDKqVo(Q4&-V!W$() zB?0J3f=UA6lLVCn!Y2tf8W287u+f0pm>s?K0xs#L4APYWfz^#VpwQu2?442T2eUQ;93luNAsI(;W5^QYx ziXJ4WU;DnB&x6ge(v0OLSOfNPEib_aTWM7D609TpdXkr5leVt`c?s5{ebmNFu+i%? zFOXn8+viDq9_$vC7?PJ@OR#T8cnNkK`(A>VU|X?I1~>^7lnInz@3I5leI9Hdc7nN= zVEeE$x4i`0N6q#DvYB1jk;gs{wvU?a1F%zhuzi4jN`mbJ{8JKaA2r*D&dfwf**@&( zNB=HtA3D$w5^NuKBA?HL?W1P<0Aw7dk{haDv4CD=af zv?MRV_MszxAd!Y8s1zJd>|`6CC7TPduJYhu0jw(tRyDA$Bv_Hax{_cu0qbV6?qk7+ zFq9g6aX~l?2rT$}0(~M+s?|l_c2Cfqf;xQBDf= z3Ig`cE`WWNz!nJXD+x9zU|&ga_5t>l1m_lDUrBIe0QQvx^#SZF3F<@FULT;m*##)C z5~vSQUP(|NZ5m{#-`RcueI>#61L!LWwjV%WNl+VLypnj6HX`=DD%3f8o`bZL;b$w?<*#x zt~}ka=I?3rhJN4j_cX#(zxxPBC8Q@{+a>Q;C~R8bAr!i&%F;byG$6W^vTefeF`b0${lgqLYBu6}jXN#;VL^{Y7!PHn^OWz4dbujrM} zYUOLqh1lrcG}>5~X|!>s?|r-HuKk17{y}yg`O(vxW$ut4U8Ygay7YBfrQvT`=1#8G zWg6A3%QUK6mr{G89CsRYmhJs>TVD&UYqEOV2gYHhzrLI1n?jf-^H4%cI3M3U%BUXS zonGeKe7jovTgvq|*EwpYpW_#DvU0y!>61w+{Ae-SMf*t#O^1c$a<54*YWZ|q9QJm7 z0axX=*mP~@BoQlokXRR+a#O|EJV``-4iXv`?JwGOqiN>^+KB0vT_EM@E@d(u-;@`p zliB9wYL&&hNMyF|&uV78>ukksRqEVT?=jDAU3qXa9!hfSshg^v$>gxxjpQ$iD!Fw_ zB64WVyG(Rx3CgrDg)>J#s4HdHzl4f5Nd{Scv0GallsKJ8-{ZwN=C9_F3e}r+vD~VP zr;}Q)wds65I&=fDTG^?jF??evf-R6#ZneRFB;wH?@(*BzWC?C0;%Oeb1xqF#-ysQ1 zc|5*D5}5LMe1{}36dV9l8Z`AW!7Tf(Bx*F?xRjy+1sHLwR6Dz#}*$ zfflSuG(qisX&H_;jcPUGPMMrd-Bv`kIZj%JtIxz@$DeD$aTErmS zrL0@n_lZHcOF82%WhJohlY4NNvTkADC->kkW!*x3kb7{KvTmV1$UOqNMgMbGRNj1|(2IG5lVl zri22}y@cjUpP)$#36v16_7X$uK5A^(7kf%T9+}$Zi3M>xaK`PxO6c1D&^F}L@%5?% zU#}T!UI~z3y~>oM1Zpi~t!3#x4V7{j)rJ>mT;HIW;XUMe^6#MpUxu7*JXf%VQ-97k zRRZ%s+sYLv;q#y_WRoEewsCPR<^gTx)K<L7%2fy zVMV#qJTh+lRRR_r+UXm0F|>1eM|~-k;2&A?)s+AVzNumgDS;MP^2OXSiz+tzD+36% z+;Z;~9gvuDkFOFUdma2bw&fR3;9D+PpG(%K5>P1CC!-CukJt^! zj5X9QV*fi8=RFX%bJxFx5`2+XZ2K#YYb&-0B`^18cp_BS*zw~dbe66#*ty!Mj3$2}DlPoM4rKA0au0Pv1 zzFjrAV{Nh)I|G#voixYZ%7_))DCirU5`1H+b&804q)bg;2J=v9K{~v=J3J@jen2Jo zSF%qH`TU*RQR{V=dr)x`g%L<_yIrR3cK&`pa1bQO8gSx!Uzko4^UjsS?O$0-i&@*h zTyCweZ5qeg>E*?#nii$usHW2U+EjwC&32F4jGNlV^LghKdea^*CFq@}GVK-Sk^@Mg=jkSqkG{4z7x>Uz6{maqhd^5dq=yr2` z$82`-~cC~Gn ze3NeAJO1veiEi*MP6>k*JiM5gqF0U*Qur-Dq3&|(gKJC@R1REYlAv<1F-j8D793xa zptj)nk_6Qww-$;{eZYXqt*!W5;MS4^^#Qk*B&ZK;jFJTP0WX#$s1JCtBtd<^izNx_ z0~@0xL4Bwr_}9lisGR$tl)%n|4NsC_U%`eaN%-}>68QSq@FWSoK3sH?;Ok?H*Qly^HOPyJE#?6rmMP`ZJQ1>2z{!N!8^P?BI{fi)xvY75(;BtdOqJCr1- zEo_I91hoZgCg*l2C3u&G5~vSshmr*Kf$dO|pgyo2N)pruwnIsR`oMN5Nl+iy4kZcd z1KXi;Zii9=^`RAmZ$a1&rCX>EY=@Er^?~hBlAu1Y9ZC|^2X;P5g8G0vTN2aU|uFLQ(BdZ$L1~QI%e(qr_cb*XaHt305jTqSuRj?q+oeQ zYcHd5m$`3^>4ubo=`y8+c8Mb6tcpCN1(wkQ%V>dRw7@bNTp10njMh&^>nEf2lhOLg zXsBc~RJ6?jZ%ac(k?oXVC98S*N~WQb(NM`~sAM!$w1LM_A1igo6#8VeT$J!834H|4;z5S(1bIg5MhU!$L&-|*&OeyF ze&x49>M7Lw%I|%Y1S?|Yx5`R_Bge{bm6Zg?C%KDIQr4XuIgnswuKZS6Jq2qgB`^;* z|CQe=t30q?Py+K{2U+>8vdZI4EoAVS^x$x){mzS!+d%8z6_L4;5OYn&K%D8I-`Ny! zrh_C{(TK~H1gjBoxsqTd;Ykl)Qx+r8%9^oK}bmi%yNwSk^(6yoK$L#zIHP%-(LBy*9%~mF%fYv$d7RNa&S)NIG>(d&}XboqyhBI2j8Li=r z*0A=y@v(e;TEiKw;f&U>_Qx?(HV0b68LeRh`(7WkhBI2j8DhipjMi{QYdE7doY5N2 zXboqyhBI2j8Li=r*04D#{L5)GjvowY+-gq?Z{c7-Yd52{s{}rUg8|K7?a<(3**<9g zW;A~@n!k#TXQpf)w09LAj9WCGcoovX&GwnT&K_6cM{mAVMm5sv&1m&zw0bjIy&0|E zj8<<(t2d+7t6igfA1aAfZ$_(Ep|i+C*Ir4qdNW$R8LeK0G%*i08d|*>tzL`1Ksh+3 z(&|-Q1aF}}X!T~adgbl+d1yJZur2S&hFi1jAVlL=J~K*S+Lc?$cPx1dcnj8}M#h~= za$3VmV5V403Mw*>nzx{136<~`>d0t7x-QAFb27IC=P#By%3I`_jmx2a=_qrQ5@=O9 z9mrac@)l~0roL7?yoDO016gwfZ=uG>4{|z?V-s>3BR|N=4|4JYC7|XA6!LsY3F?Cm zPA74` zW^cgJmwCQkF%OQG>oq0V_}3LBINz>0-(ttJ%E93Rr)5fl{ROeClHe3gkfIG7C@IN` zjuoK#h z&*bDYIinSF@)_H`gtz6eMLv@=S|KN&$;oGIo#>xJK4Y7vAVDL5d?qKK(Gf<>gME&C zCMTb*-^+7(9Gg={Mv_j5k1zRTjr;y;-7BNUr9|Sfz!xM7ynVftkXLv$RK4Ux6 zP!8&Yd?v@bOD2O`>#>y9rl`n`p3I@j)I4DXbMLR7R4R5BY(|SSNQIKvFgc$|H6bizOf-s|C zG<-prQ4nSnjD{}=GYZ0tg3<7rviP=GTbgC=^+A|X5M~sF83m)^_1z3+igCSQd_+N* zQ4m!WL=^>5ML|?i5LFm<@NY|0Q4m!WL>2mC9rNJZ5>*sL6$Md6K~zx?RTM-O1yMyo zGEtCB6eJV&DqbH9@F<8X3ZjaF0UiZWML{xAFuc7Wswf!Vu4DCBQjC@bQAI&iQ7~$x zAek`e6eJS`$wWaiQIJenL-zV0 zswfx$QV>-XL=^?2ISPV^f*?XCxv(762SG$Z5K$0B6pW%M7~WnmM#B2B*9T5(6O`m^ zN|;gLv^L$s@q=`uz-eu|h5EqpZIWR7!0~O8017XNDhiT`f@H#mF|QBCgcM{K1yO}g z4`m+I2ZKNgq6!^yz&zMK$Sw-9i-PQ;AiF5YE()>>8^ygo$Sw+^ih^XKAem6e6*J{* z$`B46$G}^t5AKL4NG1xBiGpOJAeksgCTtS(`XHGoNG1w`h=L%ZAc!akA_{_tf*_*c z9tb7W`_{JV>NwfBnOM#Ob|I37f^i=O<30**izpZfV$-@;5n)9^SW%Eo6hsjP$wNWV zP!Kc}1Puj2LqX6`Fc735XebC8bU-fOmJ3pX2037G3qeD{K#+oZCq#$T02pS54hJv8M7InUT5Hu774Fw}Z3WA1$prIgWCx00fAn+&{^HC6Z6a*dxfk#2$Q4n|(1Re!}N5Pnng21C7@F)m8 z3IY!uu8zxCrC>96 zs)^nh5e+4wNJ%JSMxR#_p-4$6QWA=kgd!!ONJ%JC5{i_BA|;_nNhnehij;&RC83BY zJ>M2{klDOm9~Qn7;tq{dY*|TCQj(OEBqb$DNl8*t^4x%uq@*M%DH--rGVG%yODV}x zO0txaETtq%F%ICBM3$l$hRw3xqj?grlmsj#0ZYkPkdlB!9}-|$umCOzSV{txl7OWo zU?~Y$N&=RWfW_E|R}ukBNx)JPu#^NWB>_uGz)}*hlmsj#0ZU21QZg2#Bw#5CSV{tx zl7PiZ?)5>yQWCI~1S};1OG&^|60np6EF}R;Nx)Jv^rIwTDG69g0+y11r6gb}8BkG@ zW0d3=B{@b(j!}|hl;jxJJbX2fW0d3=B{@b(j!}|h=-bJB3cD#ehCXA$Td=4s$uUZD zjFKFqB*!SpF|2oZeUM|6D z$uVqj@cJOfD9JJOnHb&zu2Yg@l#H+_$uV^LA~U5v$T3QCjFKFqB*!SpF-md_8ymeo z$T3QCjFKFqB*!SpF-mfbk{qKX$0*4$NHQ(4r)? zCRME`k-Z3(X!KL z^Oy(w3oW~fmYpqTd^u>@RkZ9XT6PsJyNZ@wMa!(huT6PsJyNZ@wMa!x;^Gc%gyrT2GqVv3>^Sq+-yrT2GqVv3> z^Sq+-yrT2GA`GesgDS$HiZG}m46;GS>w_?;A`GesgDS$HiZG}m45|o&D#DkCpgS?{ZU9ZE;*el z!5>bgZxvHQM!!9}|Gc%#RYXxLffB&YjU6cN^8kO=_r@uK*-#(5qXeeM#tvHcPr-Vs zxxlev`r;tp7RQP;BtA;uQ{V+@>{MT04y-{MJLlF*3>DQM($HLJ==Kt@`Wid@)Jp)H zG_h=C!S-QW z>b(TpN6z-ac#lS3=R+QBANp<{B-lP|YpyQ`+lTEu^%5LEa<&gr#m06g`aIY^Y|o#U zVEZ6gu@$Mmg@)N^f|X`VeGsfP zTk3;grP)#+1S`#!`XE?ow$ulG`OTL4AXsU()Ca+e%v0!tV5O<34}z7(FuWVb=*w>m z#Ci#?3oGh_V5Kn_FV{P#>l8EAP1TAqQHXQ1UNHx6G8E9pSX(-tURA9U#l zTAqO}{Xokz(4`+}c?P=lZC!+NusP8340P!STAqO}{Xokz(4}uaE?*A1^aCx=K$m`? z16}&&;q>L8OFz)1AL!B#v^)b{`hk{bpi4i{ z@(gt82fFkFUHXBRXP`?z(DDp)>6>xl^+A_@pye6p(hqd$2fFkFEzdxgzS%@52ipf- z`hhO}K+7}Gr5|W{2DA82_7TAuob0-pj)%PeA)gY9F#)lrVEkM<8VM+42# zKyx(E91S!_1IRgkM+42#Kyx(E91V2o2b!aS=4hZf8fcCNnxlc{ zXrMW|*LP&(`t()N?$fUq6<1z*_Dd&!eWs5Y9d_5o)A{_}_sp(;R^JP}J&k)a3Mq6l z8EZ2|x9>xCW4FrfT>f_Hbgl$X43(h&OX!xaJRwtpc9x9C^X_X?cF7xjvy?>KD{{KQ zw^IG?TWL(t4v}M&ff9VPjR}zO>jFvmb%7GR9j*kwZd8I_H!8uqxZ;V7UOCu$Aqnae z?rlj>pKxAFf(pde3rSF8*nTew>H}LZBtd;(`@JNn4}4&uu*T!{5x-w~Y8&wX>ISL@ z-d#yhJ=lpM391L!MiNv{zKzXkXtJOPUjh%e$U@dBZ20SHNg+5!-g1l3cnOryy_1wy1-s4r~imjv|%LL`ZrPvOW_3g-E8 zuytu`q?Z68(n+!UGO5c0gh&zvB{=jimz3aGzg$y-L;G?|36A7T>H~yGC8a(`#bIki?tx(H7dx znKW&ks}i!cTb}6fVD_qYj^Zl;`LNNf*=Ur2TiA)#RFV>K3meUvjYbK$g-QZ8iYFuc zK?m4K64VE7XUh)P|tc%+_9g$LF{x3hi)Z!eKcGE0O2VQcA$nG2ux46u)j2%{Q&uN z3;PSGpCni>z<`oa^uMcYa6w71q5ujdv1cA!mkK4~DQ~JdE<}J5^=$zTeSwP*CHT1> zY*Bfz1Ia<^n}ZUN2M0FMNB=Hz8X*rZQ$Qb84%Ul6I`ZJU1vpZ9Q0w56lAzW#)%(dp z3I1I`F!cckb|4^4Nw8kPI3>Xzr35^dQxc%3@?eib{EZ}7QA)s5I0I>y6C}8x5+j8K zrzAmBNN~v|iV6uDcEYNV;GzszRd4&Ix@C`2AM};21pk!w0*wx6R$uF2?YA600dI8+ zn?uWP3cRaZSo@&4l8D=$jteV*S^eI`F>F|=fz#@DYP{uS({|r~KIVWC%r?n5ZAvjr zz*;RMW6j7|Gh?hLAf-!YiB)li(`p2Z(C9NV)C{N9=oYkKZ7btrp{) zWSS9~W<;hLk!eO`nh}|1M5eYe3FSba&xlMjBGZh>G$S(A=kE9vHW#%8Uk)a|XebBOL(Z9zb7th6898T0&Y6*OTFdw4AlS?ZHZy|Fj9@b( z*vtqvGjdGZaffnHALN)BIcA1PH+`Ln!wDkYB*E^Zn)Kx$$IKAvrcXY>5Y74!i2afT^+DK@ zk*$~o;PpXrk`a_-b{a~d={XdeZmi$148lhdHdY0%^}XzbV?|N1m&avC%`u8_B20iV;L$!XB! zG-zy$_T`{KlhdHdY0%^}XmT1f+GW6}aDb&jlhdHdY0%^}XmT1fIi1!y4Vs(=P0kft z{7_wg)?T3@tZr)md4$eaHb|`WVP*Zt$oOIwKTxUeXZ4^t&)#I=zFHi(8lvH zM~m4amL(Q!(4P)cYV~nuUk06q(QYh?JIyIN=7!t$`i5JUNjIs4Lax7d{Gt1H^H(08 z+a8I2S4681E9yTgtMoDN%Fxzr+0?qh-5;-Sj*d5)F=Op`GENgsN*bCDI%&JVKR&hp zQTL2Sy2lit7WOA5>py$<{Km|-ZX9-##rT`%hig-PHDf;Q3SC}YdFi90$@%8&#^GK` z?OwTg&rq(o`n@)J$Mxy#ntr)h?D~>)YlV9!SFcZR+@8+=!eMsGF22Xr$tSK)7pkzs z=nxNyv^(Mpjy^G8jHg{==@RwY)A74!^E;#2F77tzla+ptJ>il0^r)2KCu@bHQK#Z# zT6{zt4UP&>Beu$zj{1zPrFY}Skd(H1Tk&+i>l48JE%KC<`pmPdzfxUkGBizF6?HeM zL|wZ`L|24F!ms8v6FHuPN!vmA3sN&Cy!;XxDvL zrPSTWGeh;kB7Fv{s$4HC>-9R*-iWl+b-ZgRMy-usZRNXRsowjR)Aw4+prKy-p?uCU z{BbDiu;lMt>bAnOF-?xd#VGa$g|E1H1WEXaI3;Z4uEopl<>5v?F-9ZJIEG{-3F5)J z0f$iQiDZ!Z!SEtqkEbA2pz>lLw}E z54(BSDweT#X}C45*++nm)!QwB$K#jPh3DO`7yG4FKCV`lnJhT>1oO!t!N2V?(~fK} zv2F70I_(QfTOB!>LNiy${9L2W1b9}VZtZVV6P35B8>YJ0-(^yRl|ep#FO29pjUOMUiWy|q~Dx!(OEYQ8QNnt?O5m$kfy?s+t42Q=Ke!mr4&4LxiaN};zEn{I{ot}}y8m>YAca{)q-SWW zH&$B(D0E{@U&FOLRN$?L@Q#)*Fz)Tr+OZ>h63h}y>$t!oW)34=zoa)xgeA|P!(R3FlJMACxp@vHE zBhGrIR-&&x_@b}$VJyu!{#h$IXVQ97+t+cJ!B5_6HNnX+1FScyYJOL5z0ntu3hcC3 z;;Pg+OG$%TZ$$vz^R`%Uthb0WUf;5H<8zC7U*EU7Kds8o)K5m;SNqobHjci77S~~? zdTF%SReVTnm($oT*IiOq0+$rmqcR_C9JV3sE5?8A_6yJ5KfAa+y{$!fZz367=~vmq z(!5WKS@zcFx<6{XU%aoo7|Y{T93W3ueTK)i{<<|^jx!IGq?@Mp!qaZ5u#`clA1*A( z#Ey1GmtYwkSLR((6q@fw-MhxyqULT67FRDOxp$9m-ZL9NGV5Ai6m2`pvR^b0q92T7 z%dT6G4T-(HJ#RRsUrp&flefuWGehv%+0kM%3+WdpPxLn4E91pN*3JzrxUXP zWf}GrF_>i2$;ajkq{bH1Yq^s%rM`9Y^!z7e6(2ryPki#-S#Qe@B6izg9UjwSZO1wp zJvN_qpDq}FG!>fFZ1pmveNeS0qxWT(CP7uH6O7BPQE%pME^aNKR%DnphGV&P%!T}S zZcLDw(P-(g>?&_`IK-#O!>^NfA!%crws*#woQ|VhZ}GZPm(6Cq$^4+XS!!OXxmWcuQ|MZqkWz()EG#R2|( z>Y7J#a#I?xit9VdP0cS!^LaWIeOijL*{BzNy3|_nDc8+(>pP4l9!*mtmB&Zj>XfYt zRrl@2sax+8&Ge7F^|S_;Yl#)6|( z!QZx7HhUfMU}c?;;w)B0TeYv-s{f1n>4~o_f@Zl7eoUwae@fR4V#nZK1XNfoBVFsv-=q!Hb}EzH32D;4-O9h< zEiR4KGU+i68(&uqb?c0}U2fMhhh0rJdjH2Jn{IW}Em%G}-Svx0E1@zNsBvFlB}Mw) zuTzH9_%eU|4SL1#WHeojI$$J!*K#W+=L?c;>sFz_K2a|0jU0JMtaE*Q%U1E@e%fxt zkS*yWXbNVqA19Wk(8<4oJT}(#(}TWUp~&IZPb2Zm657z}ADVU)eeRuIP?Icd@`_-~s)hqQ&*2sQaFLel_@7jjBjx}Rmhtow` zXZyC^m+Q^SDQ~ZD&RgN#Dnp4nXmTU19GmW5O=quNMao=L&^W$_SvU5uUbVJ*bM}{h ze21M@_C01FJUrW7pZ6WzI>p;NMgG~|Xu00Kx!H8~h~Ct%KhTODhUV=bZ)N7KGbvHhp1kSfwPURvagvowzcDhsQb3? zxU!Xs-saz}f3<$#PTwUR%jdJG)poPFDGaVA>}HuZZKB7}#;#49Jt{RXI#qno9x%MI zR^)$7i?uk%UadCTT4fGNUE}T3)Re9cgY}KWtbY%!dF^?9t+$GhwI>djYH`=P*Z1~l z7dd%cSGD`S4&pSh?_X1mC@N?g4F|jU&(7~VEGAFRe(T0=djC(C-*Mlo;}>?bFYLxQ zpB&w@P?H+%x;IeEu=U$?(93U zTpcr4_VQ|Wzw$_hYqKL z=!`$Bsbe2hQk;JJ8CI86ol>qmc$VG}6ZGUmQU!LStDeQ|<*p{|7egX80Np+%S@YB^ z-1QWbL34>IQHzQOINfI3gtdsUw$it&D5xU->B(+7x)pVCQiS~&`_$FLxbr`E;!0KW zbo}IEI*tSNkZgm|Rf`$uJI;{a|9`82{ws~cFE$8|M!WIh%9ZTOkFGv^erbQ-`Fp?j ztCyGG_?{p7t)KhEgO)sxctK9SN_(=|MoNQz5F}h z{mv)e_7!K3T;5r{{`!CVL%%lr-v46szQ6j>_g!A@ZvMZoDXTYPhVg%1zr6f=Z(M%w z^OwK!#DDp_mzUptdHLIKeBqxw|Hf}W@y4qX_`(yHm%pd~|JvoJzi|2K=l|kYf8x=9 zJvzS}<#+zp?@a&xeU~pk@{!jrM$_k>_^B^h{Mv<7pFM8&ncjA+HlIDNTKbhqwc8zb zyXW4>rsKo=599fr7Z2B`(=UGR?s)v^!~B7Ve&)~2-g;xCIZ^Vqn@q#(N>;mk`WA`0 zmd~n;bCqf%%B)L8?G>A~;_wu^x+xU*W>r7@ywSF%a=qG?vZeFQdbKXM8-*}B8C}dK z8nt$hn8lMl9@ihcg_?!_t!<@6UTlkv9C6#N{;BiP6l;@apt$7CTG6@NRkqSXWLpZG zuT&l@nmGFoTBu_cB#cvq7B8r>Pp69yrWQ&bdH|{<(ONSnHFL?b+L4>R>*MI zNtM#DY(v$@Hn%eqmoC>*udMgh%Wt+)u0Cbws-Rq}K#IFw>D^T%eTQl*XtMHIY&JS( zO>U=^pt<(k%6q6Vo~bo5x0rcxglJxYxu|&&suaUaLIvq$s;0 zRf62PE9rGrZtbwJa;w%M*V=mRWY!mYC$%M2rZQP+5!x9#U87rSJQ!<)h(!@MUoG`^ zTVcdP>-JS)hdhmj7P!(fVWrcovTfWa@XE9A{f4X$869)CfC>ICU z>~Xbj6>}|)vsy|qYCVMb(S)yu{XGN_|CD(1+(q*a+r^jq{u%cG_g~F1T zrFLKXOt+862~QynR-fC)rI+dGk=gaxS-e)M@|Be>{_n~Zt=JjYGgO^QDz!sd9aT~M za{VQ5uc)c-n4Dk!_zRCrr=!LHHNSnBU;k%k(>phQR};-*dUo$&bkAGIv!B#ax|#$p zU!9L8cfWVFyLI1N@=yQ5KmOIT`z}8E`u&St{q864d42TA`~HpH+g`Z5{PZ*b_qF%` z-O>8xd$qLq>x%~tlhOJ0(fEH_>=eQ>`@V-KcQV4zSo$WO9 z+T>unK3;libpHBi^z$#jcQ&5AINIGeyQ3LmbopKKJxu?qu>AO*_w4RGGoF3wDJ`mB z82!+A`a*Mg|0DB9FJ}34etwwV_uNm6KNd5y{LjYcH|C?c7Oyc$DX*NDFU}X=FxNCS zzudg?@aS*9GMbKm?ftv?_@~ErCf`3A9lq-Fer5jOj7Ja69-EIRyT#STuDji`yl4DP zi}BeDV-;v&6JQLzy7J%?=l}7?)D!NV>-9eW+-Q8~vE7f&u8n8o!wZjI-XBTa3lMO&K7aquX@r~j4$=`*Dj`uThsCUuG|}%6Fa2W z%UF3Hn0#!k__n`zHl1oFiHno|SN(YZ`1clyn0rdBQ|khMbF2Va32{b^t6Tk#^+@@0 zkEMu7)A7xl3Pu`UHp<$gb+aw}hR1cNM7nlqHq&eJzt7gfy`)m~F1tlc&?Iwp@`BpH zNN?Xi!vN9bFqcU8Ok3NZch^%3Fi<`kz{h9$eYlP`$2`uj7l{oc$!LJwK9*l=opHC? z*Ke{BCgam@!k=f;(L-GwsbG(t|HxrBoy|wjjP5=%n_pFcVfXkfzI|Uj3$h#yS!P!D zq+nS$UUn~%oxqVMkyzv*k2wAf7ik%l-#gA#B*i{j5oAn81$2>Z$D(&0_kN+M;Z;vn ztv%T}m~>rU`O#n066KpF)9^Vp(a-L_dNDpcrX|)`bLexIZ=9XYpZn-fec<_@{Rg9O zJ-ar4{%c;jv-rr>`Qq;D*VOJlFuM7DFDo>3Hvb!1OV00^kIoN=dlnxv&!S~+jbT2y zCg18}A~Ug1RpNNEkoqh-%fzhSRs62}di${gS=5W-k8yR}*Pjaiu0Q6L6BMWuV^XCX zxgVeEu|rS2GK*BRg<0rYQZM=+RUg;8Cp|S#VW z9ZGwpr0Pp8l{A>o&UTOWURa%LV`<$mq5;U>yo|mjS);Mnlqah-o_X^p&Zmc1@qNk6 z^FJ9sH9B++s&l%Gc5&&W^JuMO4U%bFGnaZ=v}LLk3-g*JQeq|HZ@gnxNK`eclRaI%rU7?Wupbt2k78kR-mb3177v9oBG{)nHtZhb#Zn4+B zauQmndli?V4f|Fp_5$NhrG2U?KqF7o@;cRq)(45Ay6B0%$W~#;mszJ;TBk3w-nt@L zRMzP(3&OFQ7^+1t`*yrww{+;A89z!tDA1zalLof2jK+Px*rbIs*mQiR{{2pS#O=dW zt@v!(4^!K;lUR{$z#f@OwJ@;f^d+z}M~@AsdztAWs(!m%=N;)961Iv%TIE`t$Gjuo z%{oRNd5n@@+GwQt@t<7u3yjG_*Z-HZJ2(FE{O;YWw!E0x;zD!!VfT^U&FLfGuNJnH z34Z;PPrh&Z#f#nD`@Zbu*#nyI&+hw!?|krKt34ZSuX_z@?A8c(_7my|nmN0d>inMl z8*02cy_1Fub4FSR?Rkpwv@UV%NowFHeb}qL&7Swn_%tZQQVdFpf%Sv-74LMa3fW0% zMpEplHno~h1(Vv$GONv@=*o_-+nG3Bb!jP|WYaImW9QH@M@c)klEl}riKAChkrp*t zL46y@bOcb6YtaSm^$*nk4fmUS$SUb2vRzWaw69tSmHRE#h3rK4TbvDshx?24-EBBO z)`GSlx-0jlic!+B;quGKRioALF!!>fc(zQRqAW1T$Oc!oLz{B-=~~H3 z=7{Ve>rmtIGYUtDUGA7_la(Tk;tD!DruIw4KPK5$hxR(Ng-vMg4*SV?(CJ6KQJhMS zB~F`C3^E*=s($GD$5ErMX{7_YPNqq8Yhh`}deOgQ)vKcWicbe(%_^y^g;|SaNEQ8z zBJ(sRS&qk~*ucBNT4%!e+Ookr845P8C}~aV-|xX-myY9E7pBoS&vfL@(rHMHCMkbh zd3ED+e&wYPp2p{Io8O+yZFv4V4bRg!I=>(mdVMy!ytCVVXg8fc^1sc;56*Xgck%G` z*>5bK)ROYgYmlCeAANZ?zx9w-g0s7=I0+* z<#uyZ+)?-*b9Q|GpGyDpuR4q;H>PhL&tI5Nwd+T9V$HA*TkKvok3)Lj2y_O(>HUPZ z+!983Dg7~N0^0VU{Gtvrbj>rFU?Y2CI+zO$q|$gu7HhOGTc&)6`BX-CdRtNvwoH!` z_07X+P|ov#w8d9WhkEUGPjX6!dTnWs?Ws3HwSV0;H(`tP#5ul%$!@&s-@337@oKm9TA22f@VKDMR+iLcu%wQOw_IXcMItd8TC#3%&`=z+ zN(-&$-s=mUuF-{3l0v4VwDxVMzleX@XZhT71bLLWEqr3yOwy4)SFxk|WNRI#)x6tm z(ko?|7A76R#e2*w8^n~;>B6e7ANjO%+Azr=ma0Kgag={n#)Ezz7J7NQI?vOgKJRAk zZcK8kgFNvyYuymlG>D}yuYWJ)P@0WK-zneG?yJRP9{Q2p?!LQI3-Y|GK_zyZ7*#!# z+4fEh<=~OJOwRF@Lq)o)6r>{T%UBQ~U>|?$g;WaJRrnP>cN(X)|ZPOxboQZe#s%yy=4V z`UYbk2+&{pb6UJEmT!?r_;BGLh0TjP9A$>viXcdEOGz7c1rqNbx z*GX!#73m}p?YE;2Qu9q7gCu|byL+>fp3}iwuBcQv?FZ@L9nH64`YPgh-OpuK!?Day zDMo%M^(Jkpah*IUA{|xb@=K~wvD+&*Zx@#0Rt%Q1hRjy(E4_g#(io)Ki}7`1X^wp_ z8TeGP-#`EKdtNYj@zgvHd$+WBjSFJ|=*v5^+0){2S7#6Y55_D;pM3Jk>5ti%XOrP> zbagh0gPpb2*nah(qh_`65MQ3`c6VP<{@qSgIl8zUlLJ!k-RsX5HgUOeTdSg8fAUzJ z#yPneb2(IXG}V5kBhO4@-3(pt_i*s`Ku8y%!M?S48n z1Y2OC)yOk?TC-R$i>utz8dt77yMKDHC9W>I8S8YZs-7mlu2m%po;d8HbS(8Cn^|og ze@fc2Jli@fLVxzVv=wia=T`@O%57cBYq+{7)*a01u$5MRZ~i%E-~X=MyQT7}4m%b1 zTC+i7+_zo1PZJHP5UZmK94kR~P1q9!9NY-tHTHR9l{Z zi}pITNm~rZHhD`$}Ch7vsmCy>EW^x_M@AKGy!t z=j-dc-Qw(#ub+hvET-jR@ySd1Up{klH^2Iai$9os`TXPU^(W`!oAc3`)(;P>OGM{` z1)te?Xq_@P@TV5Wjk`%DlA!6;x{G`tM}BTo%Td|An3=!BYnW31#3 z)YYZUbuY$p9q*4b+Hk{KVFWhZCLwj%s!L1ABOGU$i!DyAA zsaHuot4tp`zr0rlOV_pMv1?C6#pM2Ni)!CQI3vDw?--&Gi z`eJ*fXBV@B!uGn_h-U{)jxI1cT27UtZOzHWP?I+oC;QcO5*6HrxSB zukG-;)N)orw($uHU~vhmG3FANVm(GPL-3iQE%k4wqZ;fL#`aa;i1fY{0{R)_gKAN? z$T?thh%UN@w}=_2Iw>6+W?!3TV`8{dV65fV4IArZ6G&!Lm7)dX>RkE$!1?9mg~c;A zWTRf+xValEuJ=b456|8&Pia@Rb8~d`=7>!Ym~PB4eN&QRzzQANmX2B49d7#Rv}J?Q zTfKf1@sj?Yv#58=~-| zpu)dSy42ZP$%XzM>Auryvh~~^t3d30Erwc{cZPK2hpfwHe$KO@=r)*Tw z7Bmx8Vng=vLQ>aa2O4Tw2XrV{=}hzLXmNJmqKm=Unxz!?l=peqF#6W%*`Y&X@er7M zl1u69T5_p!-=AEnn5nRe@Idmbiu$(XQiXlz=~6%XX;aQFIT40evq9wTiL^@jCCR1g zKgrr=wXZzhsWSfgL{w#b|M54K@Y|E$RETdr{-*NP)3X;Ay(Vc^?>9t#d5(wX{qd1k1JkFcd)`^X-$n3MrZy#g6&JApJfx z&$d2l=CnZWY~L}mO5wt`Z`^xwoVtSC(ZKx zlT}ZrU!=j)g>-(rNFQnxEf())A8WnuP+Fg32hWC!v`C#bGyD=qrlAvQ&e=E9Bp2Q4z`cJe|~=DN5A<|Mb3Zz)1UvAzw#@ueCqNW|K#Y`KQnpF zBIn<;`_F&n^2X&q`u*3Qc=hfZ7CC?Zq4D-x|IT|a>Mx#N&KLjc^@kKS|BWw?A9(8W zjp-jzpTGS2H{SRsAO6+f z{L^o|`iqyBe{lW(y!@T7dj7Xxy8M|Jpa0xno<8~U@xOci+NgX>HNBW#E*9VVsd6;E z{hpu8c0cxISFYp=6YX0;bSTcoyDyzTASLT6Q%tmMI_XyH^rcyE@{8-BA5&kX`I6C* zz*>li;VNu-tM#ZhGbTUB#=Wy}uKe-Xb`&=h|DD9@>X#(cS6A)<3gO+zl3DA&f{ltb z*4OP<>onXse_Y(r{9tK7f_V!pABrjvCNf-V{5FG9aw>a!+_b=PB*)24JP)7T?et%awm zNde}1o_mqC9PAtWZ>gOCcB+yABt;zWG~nltuanqtT}j1yk}Wa?m&N!tDw4vEA}xqu}tR)6PcQ0^|@ZR5OZBx39NLn?FpFfE`_DfQsYvn zdm%&K&Ihz}Hcg+Um(gwwMb<0OT?aBt30j6FS!kI0+4IYPUyDPH)oV}PeB}E4Sp`?0|C^fO z=Cd!dnJteIy$b1E9PC2RxM7Q!?|kv)`Q$~}+#jEvEiNedDp>btCz+Uu;l4yJ?L9K>gv_W528VIjS@J4r`a}8}|RD$MS{i?BWs%*7; zth>|}jO`WqCdI2PK~MFDosyKMhZ)Aug^DqoPVZezFXE*}=JPWx@+{?cOi|G^xn8sA zgBWkX>=Nu1LlC@mrldGe#VH|1C3tFLA1a7Lkxd!4A;&Hv4bg?}{L1sc^`~^L6{PkC zz2_flk@3{SAD4IYxx?uD$7(DVa2tagl4!raI=eYbiZBW3%p0)w{e$GedakEZ8c>Ht zxgD!WIK~H(u28<1O+j z8k$N$q3sIMgS%y(_7rLPZ=LDc!|sI2Y^zah_))dpG@_)^w$n(%_t-kApT+e7hQTQB zZ3?A`+egpf@OFB!*j!GgxNR3wWS;!{X452;NWrr&CLMoOc1d6VS@6a_WV<~uc7rf9Ht#bqn7ZN_cd>6?u{F0VLZ$1>> zMz^TrE=ahS?m`rX3%&g@(N|(l0*RQO7RiM|gpUx@boPB|6EGh`Yy;1C zopm%*U+r4JqYK$?ooO2bhGKV+LOPX27k$5g)z4aeBtiI^AlY1Ov3&m#<7zWlf+Td+ z4Q8FX4Mx2swZ`M_y+@Fe)Q>$GrRy=#$Yu>=7`|o6C90)>bfx_@HhfwTtFPdr8#8LJ zf8|c`eIcdZZp0llq5}PLM|lMUe@T@(P~K}|k{18`+1+&f+*nBP!B-xBarW!;yJzZf ze=r;WDciAQez!X+O59p8%&Inb;34|5xjtI8URTYw=}yUv-ajozsB!Zo`u=YoLZ)bW zsxuGv`%-5<+ZN!?nW*I;h=_eLL#sb&dfc}*a|%YKDYWgV1F1UJL{FrmHLfpbutIel z{HfX6JQy=lkkgS#>gyWGcxRp1cThe2Th1@X3lCne&8F8!()IHneQ`8>b~hh?Y4^t_boA}h^AG>foe#YAzWL`4kIXL5e&b@Yd-(io{@@p8&&@yaFBWrKevPcms<*4I z+gYf>Jw8P>Gee4Ab(p|4<*CIOn~5mj0#m->{QJj`+?{Ku+w;3=P@ni>IauVx5*hvE z-53aZZDfn3-f=av6CAX?vVY9iC=kwqMPmV@=gQWKQC>YD>hstd%}LeG{2Blck?zFs zIR6GV(&IkWf`2DticGP$l+kMA$10th%>@NnX$?=1)=&yDuf+9YQ_c^b|0m;-6s1k% zrYc#m)A{0W&PVrs@>NsQnKT%+V5oBHs=zpWaC2wsc}r`nY=!P!uK~<&6zK9I*Hn}nU+8Cw#Ils z$7=OS6h%X9bRJB|_34Ua5K}Jy&iT(DZrFytOH<%zrolk%?8e=(te)xoOvfz6_zms( zwMdN@)ag1uqfAu}fK~`!uQnfeEgDQs3a&ljr!m2t8Pijx*u?EC#b$4>l#R9zmkA-% z1TXixCCKQrfQQ@$N#C^08I63S|G6KvH$i9Iw|1y;xen1C+mHCV?W@kee|k6e%qiJ9w_Z!y&uyD=oYzn%)>3s=NMCM|2sv}Qz>#hcHV1=$ z+s?tzuQdfYPU_Z1ChMTxKw+66bNz~}q{^gzgg27R-lSBkgNYnJUBNzRqMa!g_FJ9* zuamv>EwC8lI!vj1eI`^}@|R7%(%G3RQ2#@5JpBCpZKDtT z+~nCmJbUhA@Bh?|4}T{6+;gwK?X|<`pN`-8%%k_t9(m}SwUcW8*#`~}T>jDGZ@l_P zpZ~+l&p-O_ednit>%F_n7k}&f-u}Nn@sLru@afln=AD;HNA$Pc_{Xk5j0t0JF@C#}ztg{7ZmOV93tf*E#QgD}C{}HrFdC$1slhCUu6h z28)eKo)+XyluozlcLA5F=9xmoOdkc%NdRiFIu}CcHR#l5gKTLY>y?6w#2F=~U@V=s zuuMo$@%Tok_UoK(kuKwHYW#+jw0%FxLLI3+e<60Y%iAxguf2PGXZqibA3n@}NuJ{A z?A4#r;#&t1&dzU-7e6eIfc3wk$33yh=|Z!gx?jH>i=g`2c^tvMV`PB>!!)R0^te&i zQtiU7wD28Uj`mSRU7s@1c}wcS?pj^-v^hJ*=?=ciKA=c6^fXwW(mFG+FRk9+3K6Fl zqo>=hg$>v0d&d&$dBX^D%&h3ParEN4a<{8JC7J8W{i;>+EZ^BAh^pJwK;8?uaa+j~bNF-9;C9@Rb~N3_};%QrQx zjgHO1=K24Rw094V`^xS+(GLPm3X+->W`;B7jG7c@%$bZ8P<#kX{AfH$j6ebcKs{Wp zZ8W+YAVwe>gNG<75A{6aXuVEFtJ21-c)Kfo87o} zv+=B*#G6ejX6(((tY<9l=X>tGzu*1+x;d%r(zc8~_wl>;+;h)8uX}EG?&>8hshfjj z+4LNP((^M{v~zBfc@~KX@!n?(BftG8ux}xuJ%$$a>(w6Vnrp+y$5t!V4>**+Q=K{A z{>qPI?=0TC(JK)Ta}BQeQ@>Q7oT>lNU#)%TLh(1N)zgI&wfYE~;G`KSNo}70Hg-ZI zaW*jvV9}DvL2CijS+tooBcM&BlSPNj2wBW4njnynLy-7)t`#_nPzGB7P#M9QhkSny z2}Fs7;Ybn{k1GUfs#XQ;VP;RO7sP_37{?uf*Nmod>A9)-)yDGT%kwiBLjAVpWw7Qt z4-oKR2Nn;e6b={u{39d(sh!2%QUypbrD0%UH;}A_qbic8G@|n(WpHBx4-w1t#Bzk+Ax~z~v9n*1e3#t@(y?=O`u3YN z=PY8C(gki4&4_a<#hjg$8JtL^&aRfU=-h{Kw{QXhM{8C1pT)cfq_|c0ueo)|^?7-s zN!36%4Ds_LV_>FQe9d$ZGQgp8R0!0eBdN|=j^R~j$BGmhm;H_u;_Q^A5a%F$h>|*- zk@fN9`lw_d(cFXE74KOC_iy)n)%M`yb=W%GD(m4u3g z3(`<^h1N43cR(m;GP?w1hZ6Q3R)~{|et;12t$7s6ck0F*c@>TJy#XOQ@&U{DJpkCHWs3-)_gBW3DS;j z7tA21gu_$pFT1|td^t$}x" - ), - sub_string( Env, 1, _, 0, Env1 ), - sub_string( Rest, _, _, _, Env1), !, % check -% writeln(_Pos:_Line), listing(stack), - pop( list, it(Env, _, _, _) ). -process("@end", Line, _Rest, NewLine , _Pos) :- - sub_string(Line, _, _, 0, "ifnottex"), !, % check - NewLine = "\\endhtmlonly". -process("@end", _Line, Rest, "" , _Pos) :- - sub_string(Rest, _, _, _, "cartouche"), !. % check -process("@end", _Line, Rest, "" , _Pos) :- - sub_string(Rest, _, _, _, "format"), !. % check -process("@end", _Line, Rest, "" , _Pos ) :- - sub_string(Rest, _, _, _, "group"), !. % check -process("@end", Line, _Rest, NewLine , _Pos ) :- - pop( match, End ), - sub_string(Line, _, _, 0, End), !, % check - gen_comment( Line, NewLine ). -process("@end", Line, _Rest, NewLine , _Pos) :- - pop( language, End ), - sub_string(Line, _, _, 0, End), !, % check - gen_comment( Line, NewLine ). -process("@author", _Line, Rest, NewLine , _Pos) :- !, - jmp_blanks( Rest, Firs ), - format( string( NewLine), '\\author ~s', [ Firs ] ). -process("@*", _Line, _Rest, "" , _Pos). -process("@*", _Line, Rest, Line , _Pos) :- - !, - jmp_blanks( Rest, Firs ), - run( Line, Firs ). -process("@c", _Line, Rest, NewLine , _Pos) :- !, - gen_comment( Rest, NewLine ). -process("@comment", _Line, Rest, NewLine , _Pos) :- !, - gen_comment( Rest, NewLine ). -process("@cartouche", _Line, _Rest, "" , _Pos) :- !. -process("@group", _Line, _Rest, "" , _Pos) :- !. -process("@printindex", _Line, _Rest, "" , _Pos) :- !. -process("@bye", _Line, _Rest, "" , _Pos) :- !. -process("@cnindex", _Line, _Rest, no, _Pos ) :- !. -process("@cyindex", _Line, _Rest, no, _Pos) :- !. -process("@chapter", _Line, Rest, NewLine, _Pos ) :- !, - jmp_blanks( Rest, Firs ), - run( Title, Firs ), - nb_setval( level, 1 ), - title_from_words(Firs, Id, _Pos), - title( '@chapter', _, TitleDox ), - format(string(NewLine), '~a ~s ~s', [TitleDox, Id,Title]). -% ( format( string(NewLine), '~s', [Title] ) ; NewLine = "======" ). -process("@cindex", _Line, _Rest, no , _Pos) :- !. -process("@caindex", _Line, _Rest, no, _Pos ) :- !. -process("@defindex", Line, _Rest, NewLine , _Pos) :- !, - gen_blank( Line, NewLine ). -process("@direntry", Line, _Rest, NewLine, _Pos ) :- !, - gen_comment( Line, NewLine ), - push(skip, "direntry" ). -process("@texinfo", Line, _Rest, NewLine, _Pos ) :- !, - gen_comment( Line, NewLine ), - push(skip, "texinfo" ). -process("@documentencoding", _Line, _Rest, "" , _Pos) :- !. - % jmp_blanks( Rest, NewString ), - % format( string( NewLine), '', [ NewString ] ). -% unbalanced end -process("@end", Line, _Rest, NewLine , _Pos) :- !, - gen_comment( Line, NewLine ). -process("@enumerate", _Line, _Rest, NewLine , _Pos) :- - list( "@enumerate", "@enumerate", NewLine, _Pos). -process("@example", _Line, _Rest, "" , _Pos). -process("@example", _Line, _Rest, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" , _Pos) :- !, - push( skip, verbatim). -process("@ifplaintext", _Line, _Rest, "" , _Pos) :- !, - push( skip, verbatim). -process("@pl_example", _Line, _Rest, "" , _Pos). -process("@pl_example", _Line, _Rest, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog}" , _Pos) :- !, - push( skip, verbatim). -process("@c_example", _Line, _Rest, "" , _Pos). -process("@c_example", _Line, _Rest, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}" , _Pos) :- !, - push( skip, verbatim). -process("@format", _Line, _Rest, "", _Pos ) :- !. -process("@alias", _Line, _Rest, "", _Pos ) :- !. -process("@dircategory", _Line, _Rest, "", _Pos ) :- !. -process("@smallexample", _Line, _Rest, "" , _Pos). -process("@smallexample", _Line, _Rest, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" , _Pos) :- !, - push( skip, verbatim). -process("@findexx", _Line, _Rest, "" , _Pos) :- !. -process("@ifnottex", _Line, _Rest, "\\htmlonly" , _Pos) :- !. -process("@itemize", _Line, Rest, NewLine , _Pos) :- !, - jmp_blanks( Rest, First ), - list( "@itemize", First, NewLine, _Pos). -process("@menu", _Line, _Rest, "" , _Pos) :- !, - push(skip, "menu" ). -process("@node", Line, Rest, NewLine, Pos ) :- !, - jmp_blanks( Rest, First ), - string_codes( First, S ), - argument(AL, 0', , 0', , S, _), - string_codes(SF, AL), - retractall(last_node(_,_)), - assert( last_node( SF, Pos ) ), - gen_blank( Line, NewLine ). -process("@page", _Line, _Rest, "", _Pos ) :- !. -process("@contents", _Line, _Rest, "" , _Pos) :- !. -process("@itemx", _Line, Rest, NewLine, _Pos ) :- !, - process("@item", _Line, Rest, NewLine, _Pos ). -process("@saindex", _Line, Rest, NewLine, _Pos ) :- !, - get_second( Rest, NewLine ). -process("@snindex", _Line, _Rest, "", _Pos ) :- !. -process("@syindex", _Line, _Rest, "" , _Pos) :- !. -process("@section", _Line, Rest, NewLine, Pos ) :- !, - jmp_blanks( Rest, Title ), - run( NewTitle, Title ), - nb_setval( level, 2 ), -% format(string(NewLine), '# ~s #', [NewTitle]). - title( '@section', _, TitleDox ), - title_from_words(NewTitle, Id, Pos), - format(string(NewLine), '~a ~s ~s', [TitleDox,Id,NewTitle]). -% format(string(NewLine), '# ~s #', [NewTitle]). -process("@appendix", _Line, Rest, NewLine, _Pos ) :- !, - jmp_blanks( Rest, Title ), - run( NewTitle, Title ), - format(string(NewLine), '~n~n~s~n-------------------------~n~n', [NewTitle]). -process("@subsection", _Line, Rest, NewLine, _Pos ) :- !, - jmp_blanks( Rest, Title ), - run( NewTitle, Title ), - nb_setval( level, 3 ), - title( '@subsection', _, TitleDox ), - title_from_words(NewTitle, Id, _Pos), - format(string(NewLine), '~a ~s ~s', [TitleDox,Id,NewTitle]). -% format(string(NewLine), '## ~s ##', [NewTitle]). -process("@unnumberedsubsubsec", _Line, Rest, NewLine, _Pos ) :- !, - nb_setval( level, 4 ), - process("@subsubsection", _Line, Rest, NewLine, _Pos ). -process("@subsubsection", _Line, Rest, NewLine, _Pos ) :- !, - nb_setval( level, 4 ), - jmp_blanks( Rest, Title ), - run( NewTitle, Title ), - title( '@subsubsection', _, TitleDox ), - title_from_words(NewTitle, Id, _Pos), - format(string(NewLine), '~a ~s', [TitleDox,Id,NewTitle]). -% format(string(NewLine), '### ~s ###', [NewTitle]). -process("@set", _Line, Rest, NewLine , _Pos) :- !, - first_word( Rest, V, SecC), - jmp_blanks( SecC, Valu ), - assert( val( V, Valu ) ), - format(string(Assign), '~s=~s', [V, Valu]), - gen_comment( Assign, NewLine ). -process("@noindent", _Line, Rest, NewLine, _Pos ) :- !, - ( Rest = "" - -> - NewLine = no - ; - run(NewLine, Rest ) - ). -process("@setcontentsaftertitlepage", Line, _Rest, NewLine, _Pos ) :- !, - gen_comment( Line, NewLine ). -process("@setchapternewpage", Line, _Rest, NewLine, _Pos ) :- !, - gen_comment( Line, NewLine ). -process("@setfilename", Line, _Rest, NewLine, _Pos ) :- !, - gen_comment( Line, NewLine ). -process("@settitle", _Line, _Rest, "" , _Pos) :- !. -process("@subtitle", _Line, _Rest, "", _Pos ) :- !. -process("@include", _Line, _Rest, "", _Pos ) :- !. -process("@table", _Line, Rest, NewLine , _Pos) :- !, - jmp_blanks( Rest, First ), - nb_getval( level, N1 ), - N is N1+1, - nb_setval( level, N ), - list( "@table", First, NewLine, _Pos). -process("@title", _Line, _Rest, "" , _Pos) :- !. -process("@titlepage", _Line, _Rest, "", _Pos ) :- !. -process("@top", _Line, _Rest, "" , _Pos) :- !. -process("@unnumbered", _Line, Rest, NewLine , _Pos) :- !, - jmp_blanks( Rest, Title ), - run( NewTitle, Title ), - format(string(NewLine), '## ~s ##', [NewTitle]). -process("@vskip", _Line, _Rest, "" , _Pos) :- !. -process("\\input", Line, _Rest, NewLine , _Pos) :- !, - gen_comment( Line, NewLine ). - -% html style comments -% pandoc compatible. -gen_comment( _Line, "" ). %NewLine ) :- -% format( string( NewLine ) , '', [_Line] ). - - -get_second( Rest, Title ) :- - first_word( Rest, _V, Rest2 ), - jmp_blanks( Rest2, First2 ), - run( Title, First2 ). - - -% -% clear the buffer first. -% -list( Env, Line, New, _Pos) :- - first_word( Line, V, Rest), - jmp_blanks( Rest, End ), - ( - speek( list, it(_, _, _Pos, _) ) -> - Pos1 is 0 % Pos + 4 - ; - Pos1 = 0 %4 - ), - push( list, it( Env, V, Pos1, 1 ) ), - % b_getval( pos, _Pos ), - % writeln(add:_Pos:Env:Pos1:End), - % listing(stack), - run( New, End). -list( Env, _Line, NewLine, _Pos) :- - ( Env = "@enumerate" -> - NewLine = "
    " - ; - NewLine = "
      " - ). - -item_type("@bullet", _, "-" ). -item_type("@code", _, "-" ). -item_type("@option", _, "+" ). -item_type("@i", _, "-" ). -item_type("", _, "-" ). -item_type("@enumerate", 1, "1." ). -item_type("@enumerate", 2, "2." ). -item_type("@enumerate", 3, "3." ). -item_type("@enumerate", 4, "4." ). -item_type("@enumerate", 5, "5." ). -item_type("@enumerate", 6, "6." ). -item_type("@enumerate", 7, "7." ). -item_type("@enumerate", 8, "8." ). -item_type("@enumerate", 9, "9." ). - -offset( 0 ) :- - pop( indent, done ), !. -offset( 0 ) :- - speek( skip, verbatim ), !. -offset( Pos ) :- - speek( list, it(_, _,Pos,_) ), !. -offset( 0 ). - -gen_blank( _Line, "" ). - -jmp_blanks(SpacesNewFile, NewString) :- - strip_blanks( SpacesNewFile, 1, NonBlank1 ), - NonBlank is NonBlank1 - 1, - sub_string(SpacesNewFile, NonBlank, _, 0, NewString), !. - -title_from_words(_Title, Id, F:Pos) :- - last_node( Lab, F:Pos1), - Pos1 < Pos, - Pos < Pos1+3, !, - from_word( Lab, Id ). -title_from_words(Title, Id, _Pos) :- - from_word( Title, Id ). - -from_word( Line, Id ) :- - jmp_blanks( Line, Line2 ), - string_codes( Line2, C0 ), - simplify( C1, C0, []), - string_codes( Id, C1 ). - -simplify( [0'_|L]) --> " ", !, %' - simplify(L). -simplify( [0's,0'T|L]) --> "*", !, %' - simplify(L). -simplify( [0'a,0'A|L]) --> "@", !, - simplify(L). -simplify( [0'b,0'A|L]) --> "'", !, - simplify(L). -simplify( [0'b,0'B|L]) --> "(", !, - simplify(L). -simplify( [0'b,0'Q|L]) --> "\\", !, - simplify(L). -simplify( [0'b,0'C|L]) --> ")", !, - simplify(L). -simplify( [0'c,0'C|L]) --> ":", !, - simplify(L). -simplify( [0'c,0'O|L]) --> ",", !, - simplify(L). -simplify( [0'c,0'U|L]) --> "[", !, - simplify(L). -simplify( [0'c,0'R|L]) --> "]", !, - simplify(L). -simplify( [0'd,0'O|L]) --> ".", !, - simplify(L). -simplify( [0'd,0'Q|L]) --> "\"", !, - simplify(L). -simplify( [0'e,0'E|L]) --> "&", !, - simplify(L). -simplify( [0'e,0'X|L]) --> "!", !, - simplify(L). -simplify( [0'g,0'G|L]) --> ">", !, - simplify(L). -simplify( [0'h,0'Y|L]) --> "-", !, - simplify(L). -simplify( [0'm,0'M|L]) --> ";", !, - simplify(L). -simplify( [0'q,0'Q|L]) --> "=", !, - simplify(L). -simplify( [0'q,0'U|L]) --> "?", !, - simplify(L). -simplify( [] ) --> "/", - number, !. -simplify( [0's,0'S|L]) --> "<", !, - simplify(L). -simplify( [0'u,0'U|L]) --> "\v", !, - simplify(L). -simplify( [0'v,0'V|L]) --> "|", !, - simplify(L). -simplify( [0'y,0'Y|L]) --> "{", !, - simplify(L). -simplify( [0'z,0'Z|L]) --> "}", !, - simplify(L). -simplify( [0'_|L]) --> "\t", !, - simplify(L). -simplify( [0'_|L]) --> "_", !, - simplify(L). -simplify( [C|L]) --> [C], { C >= "0", C =< "9"}, !, - simplify(L). -simplify( [C|L]) --> [C], { C >= "a", C =< "z"}, !, - simplify(L). -simplify( [C|L]) --> [C], { C >= "A", C =< "Z"}, !, % {CN is C+"a"-"A"}, - simplify(L). -simplify( L) --> [_], !, - simplify(L). -simplify( []) --> []. - -number --> []. -number --> [C], - { C >= "0" , C =< "9" }, - number. - - -first_word(Line, Word, Rest) :- - jmp_blanks( Line, Line2 ), - got_to_blanks_and_brackets(Line2, 1, N1), - sub_string( Line2, 0, N1, _R, Word), - sub_string( Line2, N1, _, 0, Rest). - -first_text(Line, Word, Rest) :- - jmp_blanks( Line, Line2 ), - got_to_blanks(Line2, 1, N1), - sub_string( Line2, 0, N1, _R, Word), - sub_string( Line2, N1, _, 0, Rest). - -strip_blanks( Word, I0, I ) :- - get_string_code(I0, Word, Code ), - ( Code =:= " " -> ! ; - Code =:= " " -> ! - ), - I1 is I0+1, - strip_blanks( Word, I1, I ). -strip_blanks( _Word, I0, I0 ). - - -got_to_blanks_and_brackets( Word, I0, I ) :- - get_string_code(I0, Word, Code ), !, - ( Code =:= " " -> I is I0-1 ; - Code =:= " " -> I is I0-1 ; - Code =:= "(" -> I is I0-1 ; - Code =:= "{" -> I is I0-1 ; - Code =:= "[" -> I is I0-1 ; - - I1 is I0+1, - got_to_blanks_and_brackets( Word, I1, I ) ). -got_to_blanks_and_brackets( _Word, I0, I ) :- - I is I0-1. - -got_to_blanks( Word, I0, I ) :- - get_string_code(I0, Word, Code ), !, - ( Code =:= " " -> I is I0-1 ; - Code =:= " " -> I is I0-1 ; - I1 is I0+1, - got_to_blanks_and_brackets( Word, I1, I ) ). -got_to_blanks( _Word, I0, I ) :- - I is I0-1. - - -:- dynamic stack/2. - -pop(Type, Val) :- - stack(T, V), !, - T = Type, - V = Val, - once( retract(stack(T,V)) ). - -push(Type, Val) :- - asserta(stack(Type,Val)). - -speek(Type, Val) :- - stack(Type, V), !, - V = Val. - -run(N, S) :- - string( S ), !, - string_codes(S, SL), - run(NL, SL, []), - string_codes(N, NL). -run(N, SL) :- - run(NL, SL, []), - string_codes(N, NL). - -run( L) --> "@code{", !, - argument(AL, 0'{, 0'} ), - { - atom_codes( Word, AL ), - pred( Word, Key, _ , _) - -> - format( codes( L, R ), '[~a](@ref ~a)', [Word, Key]) - ; - format(codes(L, R), '`~s`', [AL] ) - }, - run(R). -run( [C|L]) --> "@", escaped(C), !, - run( L ). -run( [0'.,0'.,0'.|L]) --> "@dots", !, - run( L ). -run( [0'\t|L]) --> "@tab", !, - run( L ). -run( L) --> "@samp{", !, %' - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format(codes(L, R), '`~s`' , [AL1] ) }, %' - run(R). -run( L) --> "@option{", !, %' - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format(codes(L, R), '`~s`' , [AL1] ) }, %' - run(R). -run( L) --> "@env{", !, %' - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format(codes(L, R), '`~s`' , [AL1] ) }, %' - run(R). -run( L) --> "@key{", !, %' - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format(codes(L, R), '`~s`' , [AL1] ) }, %' - run(R). -run( L) --> "@command{", !, %' - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format(codes(L, R), '`~s`' , [AL1] ) }, %' - run(R). -run( L) --> "@value{", !, - argument(AL, 0'{, 0'}), - { string_codes( S, AL), - val( S, V ), - string_codes(V, VS) }, - { append(VS, R, L) }, - run(R). -run( L) --> "@pxref{", !, - argument(AL, 0'{, 0'}), - { - string_codes(S, AL), - from_word(S, Id), - format(codes(L, R), ' (see [~s](@ref ~s))', [AL,Id] ) }, %' % - run(R). -run( L) --> "@ref{", !, - argument(AL, 0'{, 0'}), - { - string_codes(S, AL), - from_word(S, Id), - format(codes(L, R), '[~s](@ref ~s)', [AL,Id] ) }, %' - run(R). -run( L) --> "@strong{", !, - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format( codes(L, R), ' *~s*' ,[AL1]) }, %' % - run(R). -run( L) --> "@noindent", !, - run( L ). -run( L) --> "@t{", !, - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format( codes(L, R), '~s' ,[AL1]) }, %' - run(R). -run( L) --> "@i{", !, - argument(AL, 0'{, 0'}), - { run(AL1, AL), - format( codes(L, R), '\\a ~s' ,[AL1]) }, %'@code - run(R). -run( L) --> "@var{", !, - argument(AL, 0'{, 0'}), - { - format( codes(L, R), ' _~s_' ,[AL]) }, %' % - run(R). -run( L) --> "@*", !, run(L). -run( L) --> "@file{", - argument(AL, 0'{, 0'}), !, - { format( codes(L, R), '~s' ,[AL]) }, - run(R). -run( L) --> "@email{", - argument(AL, 0'{, 0'}), !, - { format( codes(L, R), '<~s>' ,[AL]) }, - run(R). -run( L) --> "@url{", - argument(AL, 0'{, 0'}), !, - { format( codes(L, R), '<~s>' ,[AL]) }, - run(R). -run( L) --> "@uref{", - argument(AL, 0'{, 0'}), !, % - { format( codes(L, R), '<~s>' ,[AL]) }, - run(R). -run(L) --> "@emph{" , - argument(AL, 0'{, 0'}), !, % - !, - { format( codes(L, R), '~s' ,[AL]) }, - run(R). -run(L) --> "@cite{" , - !, - argument(AL, 0'{, 0'}), !, - { format( codes(L, R), '@cite ~s ' ,[AL]) }, - run(R). -run([0'©|L]) --> "@copyright{" , !, spaces, "}", run(L). %' -run([0'\\,C|L]) --> [C], %' - { md_escaped(C) }, !, - run(L). -run([C|L]) --> [C], run(L). -run([]) --> []. - -escapes( New, Old ) :- - string_codes(Old, Cs), - escapes( NCs, Cs, [] ), - string_codes(New, NCs). - -escapes([0'@|L]) --> "@@", !, %' - escapes(L). -escapes([0'{|L]) --> "@{", !, %' - escapes(L). -escapes([0'}|L]) --> "@}", !, %' - escapes(L). -/* - escapes([0'\\,0'\\|L]) --> "\\", !, - escapes(L). -escapes([0'\\,0'&|L]) --> "&", !, - escapes(L). -escapes([0'\\,0'<|L]) --> "<", !, - escapes(L). -escapes([0'\\,0'>|L]) --> ">", !, - escapes(L). -escapes([0'\\,0'"|L]) --> "\"", !, %" - escapes(L). -*/ -escapes([C|L]) --> [C], !, - escapes(L). -escapes([]) --> []. - - -text(End, C, End) --> [C], !. -text([D|L], C, End ) --> [D], !, - text( L, C, End). - -argument(L, C0, C) --> - argument0(L0, 0, C0, C), !, - { run(L, L0, []) }. -argument(L, _C0, _C, L, []) :- - b_getval( line, Line), - format(user_error, 'Line ~w :-~n argument ~c~s~c does not close in same line.~n', [Line, _C0, L, _C]). - -argument0([], 0, _, C ) --> [C], !. -argument0([C|L], I0, C0, C ) --> [C], !, - { I0 > 0, I is I0-1 }, - argument0( L, I, C0, C). -argument0([C0|L], I0, C0, C ) --> [C0], !, - { I is I0+1 }, - argument0( L, I, C0, C). - -% follow escaped characters. -argument0([0'@,Escaped|L], I, C0, C) --> - [0'@], - escaped(Escaped), !, - argument0( L, I, C0, C). -argument0([D|L], I, C0, C) --> [D], !, - argument0( L, I, C0, C). - - -spaces --> " ", !, - spaces. -spaces --> " ", !, spaces. -spaces --> []. - -escaped(0'@) --> "@". %' -escaped(0'{) --> "{". %' -escaped(0'}) --> "}". %' - -md_escaped(0'\\). %' -%md_escaped(0'_). %' -md_escaped(0'&). %' -md_escaped(0'<). %' -md_escaped(0'>). %' -md_escaped(0'*). %' - -cvt_slash( F0, Key ) :- - from_word( F0, Key ). - -:- dynamic i/1. - -i(0). - -id(X) :- - retract(i(X)), - X1 is X+100, - assert(i(X1)). - -title(TexTitle, Level, DoxTitle) :- - title( Level, TexTitle), -% Level1 is Level + 1, - title( Level, DoxTitle ), !. - -title(1, '@page' ). -title(1, '@chapter' ). -title(2, '@section' ). -title(3, '@subsection' ). -title(4, '@subsubsection' ). -title(5, '@paragraph' ). -title(6, '@paragraph' ). - -%:- spy title_from_words. - diff --git a/docs/theme.css b/docs/theme.css deleted file mode 100644 index b7c8d4cd2..000000000 --- a/docs/theme.css +++ /dev/null @@ -1,18 +0,0 @@ -body { - padding-top: 70px; - padding-bottom: 30px; -} - -.theme-dropdown .dropdown-menu { - position: static; - display: block; - margin-bottom: 20px; -} - -.theme-showcase > p > .btn { - margin: 5px 0; -} - -.theme-showcase .navbar .container { - width: auto; -} diff --git a/docs/yap.bib b/docs/yap.bib deleted file mode 100644 index cdad9b711..000000000 --- a/docs/yap.bib +++ /dev/null @@ -1,62 +0,0 @@ -@book{TheArtOfProlog, - Author = "Sterling, Leon and Shapiro, Ehud", - Title = "The Art of Prolog", - Publisher = "MIT Press", - Year = "1986" } - -@Book{ProgrammingInProlog, - Author ="William F. Clocksin and Christopher S. Mellish", - Title ={Programming in Prolog}, - Publisher ={Springer-Verlag}, - Year =1986 -} - -@inproceedings{DBLP:conf/cl/GrasH00, - author = {Daniel Cabeza Gras and - Manuel V. Hermenegildo}, - title = {A New Module System for Prolog}, - booktitle = {Computational Logic - {CL} 2000, First International Conference, London, - UK, 24-28 July, 2000, Proceedings}, - pages = {131--148}, - year = {2000}, - crossref = {DBLP:conf/cl/2000}, - url = {http://dx.doi.org/10.1007/3-540-44957-4_9}, - doi = {10.1007/3-540-44957-4_9}, - timestamp = {Tue, 21 Jun 2011 16:38:43 +0200}, - biburl = {http://dblp.uni-trier.de/rec/bib/conf/cl/GrasH00}, - bibsource = {dblp computer science bibliography, http://dblp.org} -} -@proceedings{DBLP:conf/cl/2000, - editor = {John W. Lloyd and - Ver{\'{o}}nica Dahl and - Ulrich Furbach and - Manfred Kerber and - Kung{-}Kiu Lau and - Catuscia Palamidessi and - Lu{\'{\i}}s Moniz Pereira and - Yehoshua Sagiv and - Peter J. Stuckey}, - title = {Computational Logic - {CL} 2000, First International Conference, London, - UK, 24-28 July, 2000, Proceedings}, - series = {Lecture Notes in Computer Science}, - volume = {1861}, - publisher = {Springer}, - year = {2000}, - isbn = {3-540-67797-6}, - timestamp = {Thu, 03 Jan 2002 11:55:20 +0100}, - biburl = {http://dblp.uni-trier.de/rec/bib/conf/cl/2000}, - bibsource = {dblp computer science bibliography, http://dblp.org} -} - - -@Manual{quintus, - title = {Quintus {P}rolog v3 User's Manual}, - author = {{Swedish Institute of Computer Science}}, - url = {http://www.sics.se/isl/quintus/html/quintus/index.html}, - organization = {The Intelligent Systems Laboratory}, - address = {PO Box 1263, S-164 28 Kista, Sweden}, - year = 2003, - bibauthor = {haemmerl -- Feb 20, 2006} -} - - diff --git a/docs/yap.css b/docs/yap.css deleted file mode 100644 index ec3c4d9c2..000000000 --- a/docs/yap.css +++ /dev/null @@ -1,8 +0,0 @@ -body { padding-top: 100px; } - -/* set a max-width for horizontal fluid layout and make it centered */ -.container-fluid { - margin-right: auto; - margin-left: auto; - max-width: 1600px; /* or 950px */ -} \ No newline at end of file diff --git a/docs/yap.md b/docs/yap.md deleted file mode 100644 index bb7be91e5..000000000 --- a/docs/yap.md +++ /dev/null @@ -1,1143 +0,0 @@ - YAP 6-3.4 Manual {#mainpage} -==================== - - -This file documents the YAP Prolog System version 6.3.4, a high-performance Prolog compiler developed at LIACC, Universidade do Porto. YAP is based on David H. D. Warren's WAM (Warren Abstract Machine), with several optimizations for better performance. YAP follows the Edinburgh tradition, and is largely compatible with DEC-10 Prolog, Quintus Prolog, and especially with C-Prolog. - -+ @ref download - -+ @ref install - -+ @ref run - -+ @ref consult - -+ @ref builtins - -+ @ref extensions - -+ @ref library - -+ @ref packages - -+ @ref swi - -+ @ref YAPProgramming - -+ @ref fli - - - -\author Vitor Santos Costa, -\author Luís Damas, -\author Rogério Reis -\author Rúben Azevedo - - -© 1989-2014 L. Damas, V. Santos Costa and Universidade -do Porto. -Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. -Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. -Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions. - -
      -![The YAP Logo](yap_256x256x32.png) -
      - -This file contains extracts of the SWI-Prolog manual, as written by Jan -Wielemaker. Our thanks to the author for his kind permission in allowing -us to include his text in this document. - - -## Introduction - -This document provides User information on version 6.3.4 of -YAP (Yet Another Prolog). The YAP Prolog System is a -high-performance Prolog compiler developed at LIACC, Universidade do -Porto. YAP provides several important features: - -+ Speed: YAP is widely considered one of the fastest - available Prolog systems. - -+ Functionality: it supports stream Input/Output, sockets, modules, - exceptions, Prolog debugger, C-interface, dynamic code, internal - database, DCGs, saved states, co-routining, arrays, threads. - -+ We explicitly allow both commercial and non-commercial use of YAP. - - -YAP is based on the David H. D. Warren's WAM (Warren Abstract Machine), -with several optimizations for better performance. YAP follows the -Edinburgh tradition, and was originally designed to be largely -compatible with DEC-10 Prolog, Quintus Prolog, and especially with -C-Prolog. - -YAP implements most of the ISO-Prolog standard. We are striving at -full compatibility, and the manual describes what is still -missing. The manual also includes a (largely incomplete) comparison -with SICStus Prolog. - -The document is intended neither as an introduction to Prolog nor to the -implementation aspects of the compiler. A good introduction to -programming in Prolog is the book @cite TheArtOfProlog , by -L. Sterling and E. Shapiro, published by "The MIT Press, Cambridge -MA". Other references should include the classical @cite ProgrammingInProlog , by W.F. Clocksin and C.S. Mellish, published by -Springer-Verlag. - -YAP 4.3 is known to build with many versions of gcc (\<= gcc-2.7.2, \>= -gcc-2.8.1, \>= egcs-1.0.1, gcc-2.95.\*) and on a variety of Unixen: -SunOS 4.1, Solaris 2.\*, Irix 5.2, HP-UX 10, Dec Alpha Unix, Linux 1.2 -and Linux 2.\* (RedHat 4.0 thru 5.2, Debian 2.\*) in both the x86 and -alpha platforms. It has been built on Windows NT 4.0 using Cygwin from -Cygnus Solutions (see README.nt) and using Visual C++ 6.0. - -The overall copyright and permission notice for YAP4.3 can be found in -the Artistic file in this directory. YAP follows the Perl Artistic -license, and it is thus non-copylefted freeware. - -If you have a question about this software, desire to add code, found a -bug, want to request a feature, or wonder how to get further assistance, -please send e-mail to . To -subscribe to the mailing list, visit the page -. - -On-line documentation is available for YAP at: - - - -Recent versions of YAP, including both source and selected binaries, -can be found from this same URL. - -This manual was written by Vítor Santos Costa, -Luís Damas, Rogério Reis, and Rúben Azevedo. The -manual is largely based on the DECsystem-10 Prolog User's Manual by -D.L. Bowen, L. Byrd, F. C. N. Pereira, L. M. Pereira, and -D. H. D. Warren. We have used comments from the Edinburgh Prolog -library written by R. O'Keefe. Documentation from many built-ins is -originally from the SWI-Prolog manual, with the gracious uathorization -from -Jan Wielemaker. We would also like to gratefully -acknowledge the contributions from Ashwin Srinivasian. - -We are happy to include in YAP several excellent packages developed -under separate licenses. Our thanks to the authors for their kind -authorization to include these packages. - -The packages are, in alphabetical order: - -+ The CHR package developed by Tom Schrijvers, -Christian Holzbaur, and Jan Wielemaker. - -+ The CLP(BN) package and Horus toolkit developed by Tiago Gomes, and Vítor Santos Costa. - -+ The CLP(R) package developed by Leslie De Koninck, Bart Demoen, Tom -Schrijvers, and Jan Wielemaker, based on the CLP(Q,R) implementation -by Christian Holzbaur. - -+ The CPLint package developed by Fabrizio Riguzzi's research -laboratory at the University of Ferrara. Please see - - - -+ The CUDA interface package developed by Carlos Martínez, Jorge -Buenabad, Inês Dutra and Vítor Santos Costa. - -+ The GECODE interface package developed by Denys Duchier and Vítor Santos Costa. - -+ The JPL (Java-Prolog Library) package developed by . - -+ The Logtalk Object-Oriented system is developed at the University - of Beira Interior, Portugal, by Paulo Moura: - - - - Logtalk is no longer distributed with YAP. Please use the Logtalk standalone - installer for a smooth integration with YAP. - -+ The minisat SAT solver interface developed by Michael Codish, - Vitaly Lagoon, and Peter J. Stuckey. - -+ The MYDDAS relational data-base interface developed at the - Universidade do Porto by Tiago Soares, Michel Ferreira, and Ricardo Rocha. - -+ The PRISM logic-based -programming system for statistical modeling developed at the Sato -Research Laboratory, TITECH, Japan. - -+ The ProbLog 1 system developed by the ProbLog team in the -DTAI group of KULeuven. For general information on ProbLog 1 and 2, please see - - - -+ The `real` R interface package developed by Nicos Angelopoulos, -Vítor Santos Costa, João Azevedo, Jan Wielemaker, and Rui Camacho. - -+ YAP includes the `yap2swi` library that ports to YAP code from - of SWI's PL interface. This includes the Input/Output Layer, the SWI - Foreign Language Interface, and the RDF, archive, clib, http, odbc, plunit, - semweb, sgml, and zlib packages written by Jan Wielemaker. - -Downloading YAP {#download} -============== - -The latest development version of Yap-6 is yap-6.3.4 and can be -obtained from the repositories - - - -and - - - -Several packages are shared with SWI-Prolog and need to be obtained -from separate repositories. Proceed as follows: - -~~~~~~ -cd yap-6.3 -git submodule init -git submodule update -~~~~~~ - -Most of these repositories are basically copies of the original -repositories at the SWI-Prolog site. YAP-6 will work either with or -without these packages. - -Installing YAP {#install} -============== - -YAP is a `configure` based system. We discuss how to use `configure` -to install YAP, and what are the major options. - -Compiling YAP {#CompilingYAP} -------------- - - -To compile YAP it should be sufficient to: - -1 `autoconf`. Recent versions of YAP try to follow GNU - conventions on where to place software. - - + The main executable is placed at _$BINDIR_. This executa§ble is - actually a script that calls the Prolog engine, stored at _$LIBDIR_. - - + _$LIBDIR_ is the directory where libraries are stored. YAPLIBDIR is a - subdirectory that contains the Prolog engine and a Prolog library. - - + _$INCLUDEDIR_ is used if you want to use YAP as a library. - - + _$INFODIR_ is where to store `info` files. Usually /usr/local/info, /usr/info, or /usr/share/info. - -2 `make`. - -3 If the compilation succeeds, try `./yap`. - -4 If you feel satisfied with the result, do `make install`. - -5 In most systems you will need to be superuser in order to do - `make install` and `make info` on the standard directories. - -Tuning the Functionality of YAP -------------------------------- - -Compiling YAP with the standard options give you a plain vanilla -Prolog. You can tune YAP to include extra functionality by calling -`configure` with the appropriate options: - - + `--enable-rational-trees=yes` gives you support for infinite - rational trees. - - + `--enable-coroutining=yes` gives you support for coroutining, - including freezing of goals, attributed variables, and -constraints. This will also enable support for infinite rational -trees. - - + `--enable-depth-limit=yes` allows depth limited evaluation, say for -implementing iterative deepening. - - + `--enable-low-level-tracer=yes` allows support for tracing all calls, -retries, and backtracks in the system. This can help in debugging your -application, but results in performance loss. - - + `--enable-wam-profile=yes` allows profiling of abstract machine -instructions. This is useful when developing YAP, should not be so -useful for normal users. - - + `--enable-condor=yes` allows using the Condor system that -support High Throughput Computing (HTC) on large collections of -distributively owned computing resources. - - + `--enable-tabling=yes` allows tabling support. This option -is still experimental. - - + `--enable-parallelism={env-copy,sba,a-cow}` allows -or-parallelism supported by one of these three forms. This option is -still highly experimental. - - + `--with-max-workers` allows definition of the maximum -number of parallel processes (its value can be consulted at runtime -using the flag `max_workers`). - - + `--with-gmp[=DIR]` give a path to where one can find the -`GMP` library if not installed in the default path. - - + `--enable-threads` allows using of the multi-threading -predicates provided by YAP. Depending on the operating system, the -option `--enable-pthread-locking` may also need to be used. - - + `--with-max-threads` allows definition of the maximum -number of threads (the default value is 1024; its value can be consulted -at runtime using the flag [max_threads](@ref max_threads)). - - - -Next section discusses machine dependent details. - -Tuning YAP for a Particular Machine and Compiler {#Machine_Options} ------------------------------------------------- - -The default options should give you best performance under -`GCC`. Although the system is tuned for this compiler -we have been able to compile versions of YAP under lcc in Linux, -Sun's cc compiler, IBM's xlc, SGI's cc, and Microsoft's Visual C++ -6.0. - -### Tuning YAP for `GCC`. {#Tuning_for_GCC} - -YAP has been developed to take advantage of `GCC` (but not to -depend on it). The major advantage of `GCC` is threaded code and -explicit register reservation. - -YAP is set by default to compile with the best compilation flags we -know. Even so, a few specific options reduce portability. The option - - + `--enable-max-performance=yes` will try to support the best -available flags for a specific architectural model. Currently, the option -assumes a recent version of `GCC`. - + `--enable-debug-yap` compiles YAP so that it can be debugged -by tools such as `dbx` or `gdb`. - - -Here follow a few hints: - -On x86 machines the flags: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -YAP_EXTRAS= ... -DBP_FREE=1 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -tells us to use the `%bp` register (frame-pointer) as the emulator's -program counter. This seems to be stable and is now default. - -On Sparc/Solaris2 use: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -YAP_EXTRAS= ... -mno-app-regs -DOPTIMISE_ALL_REGS_FOR_SPARC=1 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -and YAP will get two extra registers! This trick does not work on -SunOS 4 machines. - -Note that versions of GCC can be tweaked to recognize different -processors within the same instruction set, e.g. 486, Pentium, and -PentiumPro for the x86; or Ultrasparc, and Supersparc for -Sparc. Unfortunately, some of these tweaks do may make YAP run slower or -not at all in other machines with the same instruction set, so they -cannot be made default. - -Last, the best options also depends on the version of GCC you are using, and -it is a good idea to consult the GCC manual under the menus "Invoking -GCC"/"Submodel Options". Specifically, you should check -`-march=XXX` for recent versions of GCC/EGCS. In the case of -`GCC2.7` and other recent versions of `GCC` you can check: - - + 486: -In order to take advantage of 486 specific optimizations in GCC 2.7.\*: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -YAP_EXTRAS= ... -m486 -DBP_FREE=1 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + Pentium: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -YAP_EXTRAS= ... -m486 -malign-loops=2 -malign-jumps=2 \ - -malign-functions=2 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + PentiumPro and other recent Intel and AMD machines: -PentiumPros are known not to require alignment. Check your version of -`GCC` for the best `-march` option. - - + Super and UltraSparcs: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -YAP_EXTRAS= ... -msupersparc -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + MIPS: if have a recent machine and you need a 64 bit wide address -space you can use the abi 64 bits or eabi option, as in: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -CC="gcc -mabi=64" ./configure --... -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Be careful. At least for some versions of `GCC`, compiling with -`-g` seems to result in broken code. - -### Compiling Under MINGW's GCC {#Compiling_under_mingw} - - -AT the time of this writing (Nov 2014), YAP uses the mkwin script to -compile in WIN32. The script requires either a WIN32 environment, or a -cross-compiler/emulator package. - -YAP has been known to compile under VISUAL C++, and should compile and -work under cygwin, but the favorite approach is to use a native -msys/mingw environment. This approach has two key advantages: - - + it does not need an interface layer and a DLL, like cygwin. - - + it enables cross-compilation. - -YAP uses rge `mkwin` script to generate a new YAP installer. The script is -controlled by a set of of variables that should be defined early on in -the text. It executes by first calling `configure`, next running `make`, and -last (if all went well) executing `nsys`. - -In more detail, the following mingw based environments have been -tested to develop YAP: - - * MSYS 1 and mingw32/64: most WIN32 development did occur in this - native environment. Best results were achieved with - MSYS-1.0.* and TDM-GCC: - - mingw: http://www.mingw.org/ - original msys: http://www.mingw.org/wiki/MSYS - mingw64: http://mingw-w64.sourceforge.net/ - TDM-GCC: http://tdm-gcc.tdragon.net/ - - * This distribution was compiled with the MSYS2 integrated - development, that supports 32 and 64 bit compilation. Setting up - MSYS2 should be done with care, but it is worth it as the - distribution works nicely in MINGW32 and MINGW64 mode. A third - compilation mode, MSYS mode, has problems with compiling sockets. - - msys2: http://sourceforge.net/projects/msys2/ - - * cygwin and cygwin64 now can generate native applications - - cygwin: https://www.cygwin.com/ - - * Linux has a nice cross-compilation environment, with some of the best - work done for Fedora. - - fedora mingw cross-compiler: http://fedoraproject.org/wiki/MinGW/CrossCompilerFramework - - One problem is that this environment requires emulation of WIN32 - executables to generate the initial saved state and to compile - `chr`. `wine` sometimes does the task, but it sometimes fails. - - * OSX has the `mxe` package, a port of mingw that is in active - development. - - mxe: http://mxe.cc/ - - Note that OSX has technical limitations that preclude porting - wine64. wine32 is distributed with package managers such as ports - and brew. - -### Setting up WIN32 compilation - -Compiling WIN32 packages depends on a number of parameters: chosen compiler, -packages to install, directory setup. You may have to change these ones that -control the `mkwin` script: - - * `VER`: major/minor number - * `PATCHID`: third digit - * `SRC`: directory containing yap sources, in the local environment notation. - * `SRC_WIN`: same, but in WIN32 standard notation. - * `THREADS`: yes or no? controllable from the command line. - * `ABI`: "32" or "64", controllable from the command line. - * `NSIS`: installer generator, usually "/c/Program Files (x86)/NSIS/makensis". - * `DOCS_DIR`: where you have the doxygen output. - * `GCC_DIR`: root of gcc seup. - * `HOST`: argument to `--host` configure command. - * `BUILD`: build directory - * `GMP`: multi-precision package; yes, no, or the installation directory; usually in the distribution. - * `CUDD`: BDD package, usually in the distribution. - * `JAVA`: Java sdk directory, usually in the distribution. - * `PYTHON`: Python package, usually in the distribution. - * `R`: R environment package, usually in the distribution. - * `GECODE`: constraint solver package, usually not in the WIN32 distribution. - -### Compiling Under Visual C++ {#Compiling_Under_Visual_C} - -YAP used to compile cleanly under Microsoft's Visual C++ release 6.0. We next -give a step-by-step review on how the core YAP compiled manually using this -environment. Newer versions of YAP will use cmake for this purpose. - -First, it is a good idea to build YAP as a DLL: - - + create a project named yapdll using File.New. The project will be a -DLL project, initially empty. - -Notice that either the project is named yapdll or you must replace the -preprocessors variable _$YAPDLL_EXPORTS_ to match your project names -in the files YAPInterface.h and `c_interface.c`. - - + add all .c files in the $YAPSRC/C directory and in the -$YAPSRC\\OPTYAP directory to the Project's `Source Files` (use -FileView). - - + add all .h files in the _$YAPSRC/H_ directory, - _$YAPSRC\\include_ directory and in the _$YAPSRC\\OPTYAP_ -subdirectory to the Project's `Header Files`. - - + Ideally, you should now use `m4` to generate extra .h from .m4 files and use -`configure` to create a `config.h`. Or, you can be lazy, and -fetch these files from _$YAPSRC\\VC\\include_. - - + You may want to go to `Build.Set Active Configuration` and -set `Project Type` to `Release` - - + To use YAP's own include directories you have to set the Project -option `Project.Project Settings.C/C++.Preprocessor.Additional Include Directories` to include the directories _$YAPSRC\\H_, - _$YAPSRC\\VC\\include_, _$YAPSRC\\OPTYAP_ and - _$YAPSRC\\include_. The syntax is: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -$YAPSRC\H, $YAPSRC\VC\include, $YAPSRC\OPTYAP, $YAPSRC\include -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + Build: the system should generate an yapdll.dll and an yapdll.lib. - - + Copy the file yapdll.dll to your path. The file - yapdll.lib should also be copied to a location where the linker can find it. - - -Now you are ready to create a console interface for YAP: - -
        -
      1. create a second project say `wyap` with `File.New`. The project will be a -WIN32 console project, initially empty. - - + add _$YAPSRC\\console\\yap.c_ to the `Source Files`. - - + add _$YAPSRC\\VC\\include\\config.h_ and the files in _$YAPSRC\\include_ to -the `Header Files`. - - + You may want to go to `Build.Set Active Configuration` and set -`Project Type` to `Release`. - - + you will eventually need to bootstrap the system by booting from -`boot.yap`, so write: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -b $YAPSRC\pl\boot.yap -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -in `Project.Project Settings.Debug.Program Arguments`. - - + You need the sockets and yap libraries. Add - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -ws2_32.lib yapdll.lib -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -to `Project.Project Settings.Link.Object/Library Modules` - -You may also need to set the `Link Path` so that VC++ will find `yapdll.lib`. - - + set `Project.Project Settings.C/C++.Preprocessor.Additional Include Directories` to include the - _$YAPSRC/VC/include_ and - _$YAPSRC/include_. - -The syntax is: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -$YAPSRC\VC\include, $YAPSRC\include -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + Build the system. - - + Use `Build.Start Debug` to boot the system, and then create the saved state with - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -['$YAPSRC\\pl\\init']. -qsave_program('startup.yss'). -^Z -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -That's it, you've got YAP and the saved state! -
      2. -
      - -Loading and Organising YAP Programs {#consult} -=================================== - - @ingroup main - - Next, we present the main predicates and directives available to load - files and to control the Prolog environment. - - + \subpage YAPConsulting - - + \subpage YAPModules - - + \subpage YAPSaving - - - This chapter describes the predicates for controlling the execution of - Prolog programs. - - In the description of the arguments of functors the following notation - will be used: - - + a preceding plus sign will denote an argument as an "input - argument" - it cannot be a free variable at the time of the call; - + a preceding minus sign will denote an "output argument"; - + an argument with no preceding symbol can be used in both ways. - -Running YAP {#run} -=========== - -We next describe how to invoke YAP in Unix systems. - -Running YAP Interactively -------------------------- - -Most often you will want to use YAP in interactive mode. Assuming that -YAP is in the user's search path, the top-level can be invoked under -Unix with the following command: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -yap [-s n] [-h n] [-a n] [-c IP_HOST port ] [filename] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -All the arguments and flags are optional and have the following meaning: - -+ -? -print a short error message. -+ -s _Size_ -allocate _Size_ KBytes for local and global stacks. The user may -specify M bytes. -+ -h _Size_ -allocate _Size_ KBytes for heap and auxiliary stacks -+ -t _Size_ -allocate _Size_ KBytes for the trail stack -+ -L _Size_ -SWI-compatible option to allocate _Size_ K bytes for local and global stacks, the local stack -cannot be expanded. To avoid confusion with the load option, _Size_ -must immediately follow the letter `L`. -+ -G _Size_ -SWI-compatible option to allocate _Size_ K bytes for local and global stacks; the global -stack cannot be expanded -+ -T _Size_ -SWI-compatible option to allocate _Size_ K bytes for the trail stack; the trail cannot be expanded. -+ -l _YAP_FILE_ -compile the Prolog file _YAP_FILE_ before entering the top-level. -+ -L _YAP_FILE_ -compile the Prolog file _YAP_FILE_ and then halt. This option is -useful for implementing scripts. -+ -g _Goal_ -run the goal _Goal_ before top-level. The goal is converted from -an atom to a Prolog term. -+ -z _Goal_ -run the goal _Goal_ as top-level. The goal is converted from -an atom to a Prolog term. -+ -b _BOOT_FILE_ -boot code is in Prolog file _BOOT_FILE_. The filename must define -the predicate `'$live'/0`. -+ -c IP_HOST port -connect standard streams to host IP_HOST at port port -+ filename -restore state saved in the given file -+ -f -do not consult initial files -+ -q -do not print informational messages -+ -- -separator for arguments to Prolog code. These arguments are visible -through the unix/1 built-in predicate. - - -Note that YAP will output an error message on the following conditions: - -+ -a file name was given but the file does not exist or is not a saved -YAP state; - -+ -the necessary amount of memory could not be allocated; - -+ -the allocated memory is not enough to restore the state. - - - When restoring a saved state, YAP will allocate the -same amount of memory as that in use when the state was saved, unless a -different amount is specified by flags in the command line. By default, -YAP restores the file startup.yss from the current directory or from -the YAP library. - -+ -YAP usually boots from a saved state. The saved state will use the default -installation directory to search for the YAP binary unless you define -the environment variable YAPBINDIR. - -+ -YAP always tries to find saved states from the current directory - first. If it cannot it will use the environment variable YAPLIBDIR, if - defined, or search the default library directory. - -+ -YAP will try to find library files from the YAPSHAREDIR/library -directory. - - -Prolog Scripts --------------- - -YAP can also be used to run Prolog files as scripts, at least in -Unix-like environments. A simple example is shown next (do not forget -that the shell comments are very important): - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -#!/usr/local/bin/yap -L -- -# -# Hello World script file using YAP -# -# put a dot because of syntax errors . - -:- write('Hello World'), nl. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The `#!` characters specify that the script should call the binary -file YAP. Notice that many systems will require the complete path to the -YAP binary. The `-L` flag indicates that YAP should consult the -current file when booting and then halt. The remaining arguments are -then passed to YAP. Note that YAP will skip the first lines if they -start with `#` (the comment sign for Unix's shell). YAP will -consult the file and execute any commands. - -A slightly more sophisticated example is: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -#!/usr/bin/yap -L -- -# -# Hello World script file using YAP -# . - -:- initialization(main). - -main :- write('Hello World'), nl. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The `initialization` directive tells YAP to execute the goal main -after consulting the file. Source code is thus compiled and `main` -executed at the end. The `.` is useful while debugging the script -as a Prolog program: it guarantees that the syntax error will not -propagate to the Prolog code. - -Notice that the `--` is required so that the shell passes the extra -arguments to YAP. As an example, consider the following script -`dump_args`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -#!/usr/bin/yap -L -- -#. - -main( [] ). -main( [H|T] ) :- - write( H ), nl, - main( T ). - -:- unix( argv(AllArgs) ), main( AllArgs ). - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If you this run this script with the arguments: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -./dump_args -s 10000 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -the script will start an YAP process with stack size `10MB`, and -the list of arguments to the process will be empty. - -Often one wants to run the script as any other program, and for this it -is convenient to ignore arguments to YAP. This is possible by using -`L --` as in the next version of `dump_args`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -#!/usr/bin/yap -L -- - -main( [] ). -main( [H|T] ) :- - write( H ), nl, - main( T ). - -:- unix( argv(AllArgs) ), main( AllArgs ). - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The `--` indicates the next arguments are not for YAP. Instead, -they must be sent directly to the argv built-in. Hence, running - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -./dump_args test -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -will write `test` on the standard output. - -YAP Built-ins {#builtins} -============= - - + @ref YAPControl - - + @ref arithmetic - - + @ref YAPChars - - + @ref YAP_Terms - - + @ref InputOutput - - + @ref YAPOS - - + @ref Internal_Database - - + @ref Sets - -Extensions to core Prolog. {#extensions} -========================== - -YAP includes a number of extensions over the original Prolog -language. Next, we discuss how to use the most important ones. - - + @ref Rational_Trees - - + @ref CohYroutining - - + @ref Attributed_Variables - - + @ref DepthLimited - - + @ref Tabling - - + @ref Threads - - + @ref Profiling - - + @ref YAPArrays - - + @ref Parallelism - -The YAP Library {#library} -=============== - - Library files reside in the library_directory path (set by the - `LIBDIR` variable in the Makefile for YAP). Several files in the - library are originally from the public-domain Edinburgh Prolog library. - - + @ref maplist - - + @ref Apply Apply Macros - - + @ref Association_Lists - - + @ref AVL_Trees - - + @ref Exo_Intervals - - + @ref Heaps - - + @ref Lists - - + @ref LineUtilities - - + @ref matrix - - + @ref NonhYBacktrackable_Data_Structures - - + @ref Ordered_Sets - - + @ref Pseudo_Random - - + @ref Queues Queues - - + @ref PseudoRandom - - + @ref rbtrees - - + @ref RegExp - - + @ref Splay_Trees - - + @ref System - - + @ref Terms - - + @ref Tries - - + @ref Cleanup - - + @ref Timeout - - + @ref Trees - - + @ref UGraphs - - + @ref DGraphs - - + @ref UnDGraphs - - + @ref DBUsage - - + @ref lambda - - + @ref clpfd - - + @ref Block_Diagram - -The YAP Packages {#packages} -================ - -+ @ref real - -+ @ref BDDs - -+ @ref Gecode - -+ @ref MYDDAS - -+ @ref PFL - -+ @ref ProbLog1 - -+ @ref python - -+ @ref YAPRaptor - -+ @ref YAP-LBFGS - -+ @subpage yap-udi-indexers - -Leuven packages ported from SWI-Prolog: - -+ @subpage chr - -+ @subpage clpqr - - -Compatibility {#swi} -============= - -YAP has been designed to be as compatible as possible with other -Prolog systems, originally with C-Prolog\cite x and SICStus -Prolog~\cite x . More recent work on YAP has striven at making YAP -compatible with the ISO-Prolog standard\cite x , and with Jan -Wielemaker's SWI-Prolog\cite x . - -SWI-Prolog and YAP have collaborated at improved compatibility \cite x . This -resulted in Prolog extensions such as the `dialect` feature. YAP -currently supports most of the SWI-Prolog foreign interface, -integrates the SWI I/O code and WIN32 console, and uses several SWI -libraries and packages: - - + @ref aggregate - + @ref base64 - + @ref broadcast - + @ref ctypes - + @ref date - + @ref prolog_debug - + @ref prolog_edit - + @ref error - + @ref nb_set - + @ref prolog_operator - + @ref swi_option - + @ref pairs - + @ref pio - + @ref predicate_options, - + @ref predopts - + @ref prolog_clause - + @ref prolog_colour - + @ref prolog_source - + @ref prolog_xref - + @ref pure_input - + @ref quasi_quotations - + @ref read_util - + @ref record - + @ref settings - + @ref shlib - + @ref thread_pool - + @ref url - + @ref utf8 - + @ref win_menu - + @ref www_browser - -The following SWI packages are made available in the SWI distribution: - - + @ref archive - + @ref CHR - + @ref clib - + @ref clpqr - + @ref http - + @ref jpl - + @ref odbc - + @ref prosqlite - + @ref zlib - -Note that in general SWI code may be from an earlier version than the -one available with SWI-Prolog. SWI-Prolog are obviously not -responsible for any incompatibilities and/or bugs in the YAP port. - -Please do refer to the SWI-Prolog home page: - - - -for more information on SWI-Prolog and the SWI packages. - -Compatibility with the C-Prolog interpreter {#ChYProlog} -------------------------------------------- - -YAP was designed so that most C-Prolog programs should run under YAP -without changes. -The most important difference between YAP and C-Prolog is that, being -YAP a compiler, some changes should be made if predicates such as -assert/1, clause/1 and retract/1 are used. First -predicates which will change during execution should be declared as -`dynamic` by using commands like: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- dynamic f/n. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - where `f` is the predicate name and n is the arity of the -predicate. Note that several such predicates can be declared in a -single command: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :- dynamic f/2, ..., g/1. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Primitive predicates such as `retract` apply only to dynamic -predicates. Finally note that not all the C-Prolog primitive predicates -are implemented in YAP. They can easily be detected using the -`unknown` system predicate provided by YAP. - -Last, by default YAP enables character escapes in strings. You can -disable the special interpretation for the escape character by using: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- yap_flag(character_escapes,off). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -or by using: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- yap_flag(language,cprolog). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -Compatibility with the Quintus and SICStus Prolog systems ---------------------------------------------------------- - -The Quintus Prolog system was the first Prolog compiler to use Warren's -Abstract Machine. This system was very influential in the Prolog -community. Quintus Prolog implemented compilation into an abstract -machine code, which was then emulated. Quintus Prolog also included -several new built-ins, an extensive library, and in later releases a -garbage collector. The SICStus Prolog system, developed at SICS (Swedish -Institute of Computer Science), is an emulator based Prolog system -largely compatible with Quintus Prolog. SICStus Prolog has evolved -through several versions. The current version includes several -extensions, such as an object implementation, co-routining, and -constraints. - -Both YAP and SICStus Prolog obey the Edinburgh Syntax and are based on -the WAM. Even so, there are major important differences: - - + Differently from SICStus Prolog, both consulted and dynamic code in YAP - are compiled, not interpreted. All code in YAP is compiled. - - + The following SICStus Prolog v3 built-ins are not (currently) -implemented in YAP (note that this is only a partial list): -stream_interrupt/3, reinitialize/0, help/0, help/1, -trimcore/0, and require/1. - - + The consult/1 predicate in YAP follows C-Prolog -semantics. That is, it adds clauses to the data base, even for -preexisting procedures. This is different from consult/1 in -SICStus Prolog or SWI-Prolog. - - + This list is incomplete. - -Compatibility with the ISO Prolog standard ------------------------------------------- - -The Prolog standard was developed by ISO/IEC JTC1/SC22/WG17, the -international standardization working group for the programming language -Prolog. The book "Prolog: The Standard" by Deransart, Ed-Dbali and -Cervoni gives a complete description of this standard. Development in -YAP from YAP4.1.6 onwards have striven at making YAP -compatible with ISO Prolog. As such: - - + YAP now supports all of the built-ins required by the -ISO-standard, and, - + Error-handling is as required by the standard. - - -YAP by default is not fully ISO standard compliant. You can set the -language flag to `iso` to obtain better -compatibility. Setting this flag changes the following: - - - + By default, YAP implements the -atom_chars/2 (see Testing Terms), and -number_chars/2, (see Testing Terms), -built-ins as per the original Quintus Prolog definition, and -not as per the ISO definition. - -Calling `set_prolog_flag(to_chars_mode,iso)` will switch -YAP to use the ISO definition for -atom_chars/2 and number_chars/2. - - + By default, YAP allows executable goals in directives. In ISO mode -most directives can only be called from top level (the exceptions are -set_prolog_flag/2 and op/3). - - + Error checking for meta-calls under ISO Prolog mode is stricter -than by default. - - + The strict_iso flag automatically enables the ISO Prolog -standard. This feature should disable all features not present in the -standard. - -The following incompatibilities between YAP and the ISO standard are -known to still exist (please check Ulrich Neumerkel's page for more details): - -
        - -
      • Currently, YAP does not handle overflow errors in integer -operations, and handles floating-point errors only in some -architectures. Otherwise, YAP follows IEEE arithmetic. - -Please inform the authors on other incompatibilities that may still -exist. - -Foreign Language interface for YAP {#fli} -================================== - -YAP provides the user with three facilities for writing -predicates in a language other than Prolog. Under Unix systems, -most language implementations were linkable to `C`, and the first interface exported the YAP machinery to the C language. YAP also implements most of the SWI-Prolog foreign language interface. -This gives portability with a number of SWI-Prolog packages and avoids garnage collection by using @ref slotInterface. Last, a new C++ based interface is -being designed to work with the swig (www.swig.orgv) interface compiler. - -+ The @ref c-interface exports the YAP engine. - -+ The @ref swi-c-interface emulates Jan Wielemaker's SWI foreign language interface. - -+ The @ref yap-cplus-interface is desiged to interface with the SWI ackage \cite x Object-Oriented systems. - - diff --git a/docs/yap.tex b/docs/yap.tex deleted file mode 100644 index f5794cd37..000000000 --- a/docs/yap.tex +++ /dev/null @@ -1,11025 +0,0 @@ -\input texinfo @c -*- mode: texinfo; coding: utf-8; -*- - -@documentencoding UTF-8 - -@c %**start of header -@setfilename yap.info -@setcontentsaftertitlepage -@settitle YAP Prolog User's Manual -@c For double-sided printing, uncomment: -@c @setchapternewpage odd -@c %**end of header - -@set VERSION 6.3.4 -@set EDITION 4.2.9 -@set UPDATED Oct 2010 - -@c Index for C-Prolog compatible predicate -@defindex cy -@c Index for predicates not in C-Prolog -@defindex cn -@c Index for predicates sort of (almost) in C-Prolog -@defindex ca - -@c Index for SICStus Prolog compatible predicate -@defindex sy -@c Index for predicates not in SICStus Prolog -@defindex sn -@c Index for predicates sort of (almost) in SICStus Prolog -@defindex sa - -@alias pl_example=example -@alias c_example=example - -@setchapternewpage odd -@c @smallbook -@comment %** end of header - -@ifnottex -@format -@dircategory The YAP Prolog System -@direntry -* YAP: (yap). YAP Prolog User's Manual. -@end direntry -@end format -@end ifnottex - -@titlepage -@title YAP User's Manual -@subtitle Version @value{VERSION} -@author Vitor Santos Costa, -@author Luís Damas, -@author Rogério Reis -@author Rúben Azevedo -@page -@vskip 2pc -@copyright{} 1989-2014 L. Damas, V. Santos Costa and Universidade -do Porto. - -Permission is granted to make and distribute verbatim copies of -this manual provided the copyright notice and this permission notice -are preserved on all copies. - -Permission is granted to copy and distribute modified versions of this -manual under the conditions for verbatim copying, provided that the entire -resulting derived work is distributed under the terms of a permission -notice identical to this one. - -Permission is granted to copy and distribute translations of this manual -into another language, under the above conditions for modified versions. - -@end titlepage - -@ifnottex -@node Top, , , (dir) -@top YAP Prolog - -This file documents the YAP Prolog System version @value{VERSION}, a -high-performance Prolog compiler developed at LIACC, Universidade do -Porto. YAP is based on David H. D. Warren's WAM (Warren Abstract -Machine), with several optimizations for better performance. YAP follows -the Edinburgh tradition, and is largely compatible with DEC-10 Prolog, -Quintus Prolog, and especially with C-Prolog. - - -@ifplaintext - - - + @subpage Install discusses how to download, compile and install YAP for your platform. - - + @subpage Syntax describes the syntax of YAP. - - + @subpage Run describes how to invoke YAP - - + @subpage Syntax describe the syntax of YAP. - - + @subpage Loading_Programs presents the main predicates and - directives available to load files and to control the Prolog environment. - - + @subpage abs_file_name explains how to find a file full path. - - + Built-Ins describes predicates providing core YAP functionality: - + @subpage page_arithmetic describes how arithmetic works in YAP. - - + @subpage Control describes the predicates for controlling the execution of Prolog programs. - - + @subpage Testing_Terms describes the main predicates on terms - - + @subpage Input_Output goes into Input/Ouput. - - + @subpage Database discusses the clausal data-base - - + @subpage Grammars presents Grammar rules in Prolog that are - both a convenient way to express definite clause grammars and - an extension of the well known context-free grammars. - - + @subpage OS discusses access to Operating System functionality - - + Libraries - - + @ref maplist introduces macros to apply an operation over - all elements of a list - - -@end ifplaintext - - -This file contains extracts of the SWI-Prolog manual, as written by Jan -Wielemaker. Our thanks to the author for his kind permission in allowing -us to include his text in this document. - -@menu -* Intro:: Introduction -* Install:: Installation -* Run:: Running YAP -* Syntax:: The syntax of YAP -* Loading Programs:: Loading Prolog programs -* Modules:: Using Modules in YAP -* Built-ins:: Built In Predicates -* Library:: Library Predicates -* SWI-Prolog:: SWI-Prolog emulation -* Global Variables :: Global Variables for Prolog -* Extensions:: Extensions to Standard YAP -* Rational Trees:: Working with Rational Trees -* Co-routining:: Changing the Execution of Goals -* Attributed Variables:: Using attributed Variables -* CLPR:: The CLP(R) System -* CHR:: The CHR System -* Logtalk:: The Logtalk Object-Oriented System -* MYDDAS:: The YAP Database Interface -* Threads:: Thread Library -* Parallelism:: Running in Or-Parallel -* Tabling:: Storing Intermediate Solutions of programs -* Low Level Profiling:: Profiling Abstract Machine Instructions -* Low Level Tracing:: Tracing at Abstract Machine Level -* Debugging:: Using the Debugger -* Efficiency:: Efficiency Considerations -* C-Interface:: Interfacing predicates written in C -* YAPLibrary:: Using YAP as a library in other programs -* Compatibility:: Compatibility with other Prolog systems -* Predicate Index:: An item for each predicate -* Concept Index:: An item for each concept - -Built In Predicates -* Control:: Controlling the execution of Prolog programs -* Undefined Procedures:: Handling calls to Undefined Procedures -* Messages:: Message Handling in YAP -* Testing Terms:: Predicates on Terms -* Predicates on Atoms:: Manipulating Atoms -* Predicates on Characters:: Manipulating Characters -* Comparing Terms:: Comparison of Terms -* Arithmetic:: Arithmetic in YAP -* Input/Output:: Input/Output with YAP -* Database:: Modifying Prolog's Database -* Sets:: Finding All Possible Solutions -* Grammars:: Grammar Rules -* Preds:: Predicate Information -* OS:: Access to Operating System Functionality -* Term Modification:: Updating Prolog Terms -* Global Variables:: Manipulating Global Variables -* Profiling:: Profiling Prolog Execution -* Call Counting:: Limiting the Maximum Number of Reductions -* Arrays:: Supporting Global and Local Arrays -* Preds:: Information on Predicates -* Misc:: Miscellaneous Predicates - - -Subnodes of Running -* Running YAP Interactively:: Interacting with YAP -* Running Prolog Files:: Running Prolog files as scripts - -Subnodes of Syntax -* Formal Syntax:: Syntax of Terms -* Tokens:: Syntax of Prolog tokens -* Encoding:: How characters are encoded and Wide Character Support - -Subnodes of Tokens -* Numbers:: Integer and Floating-Point Numbers -* Strings:: Sequences of Characters -* Atoms:: Atomic Constants -* Variables:: Logical Variables -* Punctuation Tokens:: Tokens that separate other tokens -* Layout:: Comments and Other Layout Rules - -Subnodes of Numbers -* Integers:: How Integers are read and represented -* Floats:: Floating Point Numbers - -Subnodes of Encoding -* Stream Encoding:: How Prolog Streams can be coded -* BOM:: The Byte Order Mark - -Subnodes of Loading Programs -* Compiling:: Program Loading and Updating -* Setting the Compiler:: Changing the compiler's parameters -* Conditional Compilation:: Compiling program fragments -* Saving:: Saving and Restoring Programs - -Subnodes of Modules -* Module Concepts:: The Key Ideas in Modules -* Defining Modules:: How To Define a New Module -* Using Modules:: How to Use a Module -* Meta-Predicates in Modules:: How to Handle New Meta-Predicates -* Re-Exporting Modules:: How to Re-export Predicates From Other Modules - -Subnodes of Input/Output -* Streams and Files:: Handling Streams and Files -* C-Prolog File Handling:: C-Prolog Compatible File Handling -* Input/Output of Terms:: Input/Output of terms -* Input/Output of Characters:: Input/Output of Characters -* Input/Output for Streams:: Input/Output using Streams -* C-Prolog to Terminal:: C-Prolog compatible Character Input/Output to terminal -* Input/Output Control:: Controlling your Input/Output -* Sockets:: Using Sockets from YAP - -Subnodes of Database -* Modifying the Database:: Asserting and Retracting -* Looking at the Database:: Finding out what is in the Data Base -* Database References:: Using Data Base References -* Internal Database:: YAP's Internal Database -* BlackBoard:: Storing and Fetching Terms in the BlackBoard - -Subnodes of Library -* Aggregate :: SWI and SICStus compatible aggregate library -* Apply:: SWI-Compatible Apply library. -* Association Lists:: Binary Tree Implementation of Association Lists. -* AVL Trees:: Predicates to add and lookup balanced binary trees. -* BDDs:: Predicates to manipulate BDDs using the CUDD libraries -* Exo Intervals:: Play with the UDI and exo-compilation -* Gecode:: Interface to the gecode constraint library -* Heaps:: Labelled binary tree where the key of each node is less - than or equal to the keys of its children. -* Lambda:: Ulrich Neumerkel's Lambda Library -* DBUsage:: Information bout data base usage. -* LineUtilities:: Line Manipulation Utilities -* Lists:: List Manipulation -* MapArgs:: Apply on Arguments of Compound Terms. -* MapList:: SWI-Compatible Apply library. -* matrix:: Matrix Objects -* MATLAB:: Matlab Interface -* Non-Backtrackable Data Structures:: Queues, Heaps, and Beams. -* Ordered Sets:: Ordered Set Manipulation -* Pseudo Random:: Pseudo Random Numbers -* Queues:: Queue Manipulation -* Random:: Random Numbers -* Read Utilities:: SWI inspired utilities for fast stream scanning. -* Red-Black Trees:: Predicates to add, lookup and delete in red-black binary trees. -* RegExp:: Regular Expression Manipulation -* shlib:: SWI Prolog shlib library -* Splay Trees:: Splay Trees -* String Input/Output:: Writing To and Reading From Strings -* System:: System Utilities -* Terms:: Utilities on Terms -* Cleanup:: Call With registered Cleanup Calls -* Timeout:: Call With Timeout -* Trees:: Updatable Binary Trees -* Tries:: Trie Data Structure -* UGraphs:: Unweighted Graphs -* DGraphs:: Directed Graphs Implemented With Red-Black Trees -* UnDGraphs:: Undirected Graphs Using DGraphs -* LAM:: LAM MPI -* Block Diagram:: Block Diagrams of Prolog code - - -Subnodes of Debugging -* Deb Preds:: Debugging Predicates -* Deb Interaction:: Interacting with the debugger - -Subnodes of Compatibility -* C-Prolog:: Compatibility with the C-Prolog interpreter -* SICStus Prolog:: Compatibility with the Quintus and SICStus Prolog systems -* ISO Prolog:: Compatibility with the ISO Prolog standard - -Subnodes of Attributes -* Attribute Declarations:: Declaring New Attributes -* Attribute Manipulation:: Setting and Reading Attributes -* Attributed Unification:: Tuning the Unification Algorithm -* Displaying Attributes:: Displaying Attributes in User-Readable Form -* Projecting Attributes:: Obtaining the Attributes of Interest -* Attribute Examples:: Two Simple Examples of how to use Attributes. - -Subnodes of SWI-Prolog -* Invoking Predicates on all Members of a List :: maplist and friends -* SWI-Prolog Global Variables :: Emulating SWI-like attributed variables - -Subnodes of Gecode -* The Gecode Interface:: calling gecode from YAP -* Gecode and ClP(FD) :: using gecode in a CLP(FD) style - -@c Subnodes of CLP(Q,R) -@c * Introduction to CLPQ:: The CLP(Q,R) System -@c * Referencing CLPQR:: How to Reference CLP(Q,R) -@c * CLPQR Acknowledgments:: Acknowledgments for CLP(Q,R) -@c * Solver Interface:: Using the CLP(Q,R) System -@c * Notational Conventions:: The CLP(Q,R) Notation -@c * Solver Predicates:: The CLP(Q,R) Interface Predicates -@c * Unification:: Unification and CLP(Q,R) -@c * Feedback and Bindings:: Information flow in CLP(Q,R) -@c * Linearity and Nonlinear Residues:: Linear and Nonlinear Constraints -@c * How Nonlinear Residues are made to disappear:: Handling Nonlinear Residues -@c * Isolation Axioms:: Isolating the Variable to be Solved -@c * Numerical Precision and Rationals:: Reals and Rationals -@c * Projection and Redundancy Elimination:: Presenting Bindings for Query Variables -@c * Variable Ordering:: Linear Relationships between Variables -@c * Turning Answers into Terms:: using @code{call_residue/2} -@c * Projecting Inequalities:: How to project linear inequations -@c * Why Disequations:: Using Disequations in CLP(Q,R) -@c * Syntactic Sugar:: An easier syntax -@c * Monash Examples:: The Monash Library -@c * Compatibility Notes:: CLP(Q,R) and the clp(R) interpreter -@c * A Mixed Integer Linear Optimization Example:: MIP models -@c * Implementation Architecture:: CLP(Q,R) Components -@c * Fragments and Bits:: Final Last Words on CLP(Q,R) -@c * CLPQR Bugs:: Bugs in CLP(Q,R) -@c * CLPQR References:: References for CLP(Q,R) - -Subnodes of CLPR -* CLPR Solver Predicates:: -* CLPR Syntax:: -* CLPR Unification:: -* CLPR Non-linear Constraints:: - -Subnodes of CHR -* CHR Introduction:: -* CHR Syntax and Semantics:: -* CHR in YAP Programs:: -* CHR Debugging:: -* CHR Examples:: -* CHR Compatibility:: -* CHR Guidelines:: - -Subnodes of C-Interface -* Manipulating Terms:: Primitives available to the C programmer -* Manipulating Terms:: Primitives available to the C programmer -* Unifying Terms:: How to Unify Two Prolog Terms -* Manipulating Strings:: From character arrays to Lists of codes and back -* Memory Allocation:: Stealing Memory From YAP -* Controlling Streams:: Control How YAP sees Streams -* Utility Functions:: From character arrays to Lists of codes and back -* Calling YAP From C:: From C to YAP to C to YAP -* Module Manipulation in C:: Create and Test Modules from within C -* Miscellaneous C-Functions:: Other Helpful Interface Functions -* Writing C:: Writing Predicates in C -* Loading Objects:: Loading Object Files -* Save&Rest:: Saving and Restoring -* YAP4 Notes:: Changes in Foreign Predicates Interface - -Subnodes of C-Prolog -* Major Differences with C-Prolog:: Major Differences between YAP and C-Prolog -* Fully C-Prolog Compatible:: YAP predicates fully compatible with -C-Prolog -* Not Strictly C-Prolog Compatible:: YAP predicates not strictly as C-Prolog -* Not in C-Prolog:: YAP predicates not available in C-Prolog -* Not in YAP:: C-Prolog predicates not available in YAP - -Subnodes of SICStus Prolog -* Major Differences with SICStus:: Major Differences between YAP and SICStus Prolog -* Fully SICStus Compatible:: YAP predicates fully compatible with -SICStus Prolog -* Not Strictly SICStus Compatible:: YAP predicates not strictly as -SICStus Prolog -* Not in SICStus Prolog:: YAP predicates not available in SICStus Prolog - - -Tables -* Operators:: Predefined operators - -@end menu - -@end ifnottex - -@node Intro, Install, , Top -@section Introduction - -This document provides User information on version @value{VERSION} of -YAP (@emph{Yet Another Prolog}). The YAP Prolog System is a -high-performance Prolog compiler developed at LIACC, Universidade do -Porto. YAP provides several important features: - -@itemize @bullet - @item Speed: YAP is widely considered one of the fastest available -Prolog systems. - - @item Functionality: it supports stream Input/Output, sockets, modules, -exceptions, Prolog debugger, C-interface, dynamic code, internal -database, DCGs, saved states, co-routining, arrays, threads. - - @item We explicitly allow both commercial and non-commercial use of YAP. -@end itemize - -YAP is based on the David H. D. Warren's WAM (Warren Abstract Machine), -with several optimizations for better performance. YAP follows the -Edinburgh tradition, and was originally designed to be largely -compatible with DEC-10 Prolog, Quintus Prolog, and especially with -C-Prolog. - -YAP implements most of the ISO-Prolog standard. We are striving at -full compatibility, and the manual describes what is still -missing. The manual also includes a (largely incomplete) comparison -with SICStus Prolog. - -The document is intended neither as an introduction to Prolog nor to the -implementation aspects of the compiler. A good introduction to -programming in Prolog is the book @cite{TheArtOfProlog}, by -L. Sterling and E. Shapiro, published by "The MIT Press, Cambridge -MA". Other references should include the classical @cite{ProgrammingInProlog}, by W.F. Clocksin and C.S. Mellish, published by -Springer-Verlag. - -YAP 4.3 is known to build with many versions of gcc (<= gcc-2.7.2, >= -gcc-2.8.1, >= egcs-1.0.1, gcc-2.95.*) and on a variety of Unixen: -SunOS 4.1, Solaris 2.*, Irix 5.2, HP-UX 10, Dec Alpha Unix, Linux 1.2 -and Linux 2.* (RedHat 4.0 thru 5.2, Debian 2.*) in both the x86 and -alpha platforms. It has been built on Windows NT 4.0 using Cygwin from -Cygnus Solutions (see @file{README.nt}) and using Visual C++ 6.0. - -The overall copyright and permission notice for YAP4.3 can be found in -the Artistic file in this directory. YAP follows the Perl Artistic -license, and it is thus non-copylefted freeware. - -If you have a question about this software, desire to add code, found a -bug, want to request a feature, or wonder how to get further assistance, -please send e-mail to @email{yap-users AT lists.sourceforge.net}. To -subscribe to the mailing list, visit the page -@url{https://lists.sourceforge.net/lists/listinfo/yap-users}. - -On-line documentation is available for YAP at: - - @url{http://www.ncc.up.pt/~vsc/YAP/} - -Recent versions of YAP, including both source and selected binaries, -can be found from this same URL. - -This manual was written by Vítor Santos Costa, -Luís Damas, Rogério Reis, and Rúben Azevedo. The -manual is largely based on the DECsystem-10 Prolog User's Manual by -D.L. Bowen, L. Byrd, F. C. N. Pereira, L. M. Pereira, and -D. H. D. Warren. We have also used comments from the Edinburgh Prolog -library written by R. O'Keefe and from the SWI-Prolog manual written by -Jan Wielemaker. We would also like to gratefully -acknowledge the contributions from Ashwin Srinivasian. - -We are happy to include in YAP several excellent packages developed -under separate licenses. Our thanks to the authors for their kind -authorization to include these packages. - -The packages are, in alphabetical order: - -@itemize @bullet -@item The CHR package developed by Tom Schrijvers, -Christian Holzbaur, and Jan Wielemaker. - -@item The CLP(R) package developed by Leslie De Koninck, Bart Demoen, Tom -Schrijvers, and Jan Wielemaker, based on the CLP(Q,R) implementation -by Christian Holzbaur. - -@item The Logtalk Object-Oriented system is developed at the University -of Beira Interior, Portugal, by Paulo Moura: - -@url{http://logtalk.org/} - -Logtalk is no longer distributed with YAP. Please use the Logtalk standalone -installer for a smooth integration with YAP. - -@item The Pillow WEB library developed at Universidad Politecnica de -Madrid by the CLIP group. This package is distributed under the FSF's -LGPL. Documentation on this package is distributed separately from -yap.tex. - -@item The @file{yap2swi} library implements some of the functionality of -SWI's PL interface. Please do refer to the SWI-Prolog home page: - -@url{http://www.swi-prolog.org} - -for more information on SWI-Prolog and for a detailed description of its -foreign language interface. - -@end itemize - -@include install.tex - -@include run.tex - -@include syntax.tex - -@include load.tex - -@include builtins.tex - -@node Library, SWI-Prolog, Built-ins, Top - -@chapter Library Predicates - -Library files reside in the library_directory path (set by the -@code{LIBDIR} variable in the Makefile for YAP). Currently, -most files in the library are from the Edinburgh Prolog library. - -@menu - -Library, Extensions, Built-ins, Top -* Aggregate :: SWI and SICStus compatible aggregate library -* Apply:: SWI-Compatible Apply library. -* Association Lists:: Binary Tree Implementation of Association Lists. -* AVL Trees:: Predicates to add and lookup balanced binary trees. -* BDDs:: Predicates to manipulate BDDs using the CUDD libraries -* Block Diagram:: Block Diagrams of Prolog code -* Cleanup:: Call With registered Cleanup Calls -* DGraphs:: Directed Graphs Implemented With Red-Black Trees -* Exo Intervals:: Play with the UDI and exo-compilation -* Gecode:: Interface to the gecode constraint library -* Heaps:: Labelled binary tree where the key of each node is less - than or equal to the keys of its children. -* LAM:: LAM MPI -* Lambda:: Ulrich Neumerkel's Lambda Library -* DBUsage:: Information bout data base usage. -* Lists:: List Manipulation -* LineUtilities:: Line Manipulation Utilities -* MapArgs:: Apply on Arguments of Compound Terms. -* MapList:: SWI-Compatible Apply library. -* matrix:: Matrix Objects -* MATLAB:: Matlab Interface -* Non-Backtrackable Data Structures:: Queues, Heaps, and Beams. -* Ordered Sets:: Ordered Set Manipulation -* Pseudo Random:: Pseudo Random Numbers -* Queues:: Queue Manipulation -* Random:: Random Numbers -* Read Utilities:: SWI inspired utilities for fast stream scanning. -* Red-Black Trees:: Predicates to add, lookup and delete in red-black binary trees. -* RegExp:: Regular Expression Manipulation -* shlib:: SWI Prolog shlib library -* Splay Trees:: Splay Trees -* String Input/Output:: Writing To and Reading From Strings -* System:: System Utilities -* Terms:: Utilities on Terms -* Timeout:: Call With Timeout -* Trees:: Updatable Binary Trees -* Tries:: Trie Data Structure -* UGraphs:: Unweighted Graphs -* UnDGraphs:: Undirected Graphs Using DGraphs - - -@end menu - - -@node Aggregate, Apply, , Library -@section Aggregate -@cindex aggregate -This is the SWI-Prolog library based on the Quintus and SICStus 4 -library. @c To be done - Analysing the aggregation template -@c and compiling a predicate for the list aggregation can be done at -@c compile time. - aggregate_all/3 can be rewritten to run in constant -@c space using non-backtrackable assignment on a term. - -This library provides aggregating operators over the solutions of a -predicate. The operations are a generalisation of the @code{bagof/3}, -@code{setof/3} and @code{findall/3} built-in predicates. The defined -aggregation operations are counting, computing the sum, minimum, -maximum, a bag of solutions and a set of solutions. We first give a -simple example, computing the country with the smallest area: - -@pl_example -smallest_country(Name, Area) :- - aggregate(min(A, N), country(N, A), min(Area, Name)). -@end pl_example - -There are four aggregation predicates, distinguished on two properties. - -@table @code - -@item aggregate vs. aggregate_all - The aggregate predicates use setof/3 (aggregate/4) or bagof/3 - (aggregate/3), dealing with existential qualified variables - (@var{Var}/\@var{Goal}) and providing multiple solutions for the - remaining free variables in @var{Goal}. The aggregate_all/3 - predicate uses findall/3, implicitly qualifying all free variables - and providing exactly one solution, while aggregate_all/4 uses - sort/2 over solutions and Distinguish (see below) generated using - findall/3. -@item The @var{Distinguish} argument - The versions with 4 arguments provide a @var{Distinguish} argument - that allow for keeping duplicate bindings of a variable in the - result. For example, if we wish to compute the total population of - all countries we do not want to lose results because two countries - have the same population. Therefore we use: - -@pl_example - aggregate(sum(P), Name, country(Name, P), Total) -@end pl_example - -@end table - -All aggregation predicates support the following operator below in -@var{Template}. In addition, they allow for an arbitrary named compound -term where each of the arguments is a term from the list below. I.e. the -term @code{r(min(X), max(X))} computes both the minimum and maximum -binding for @var{X}. - -@table @code - -@item count - Count number of solutions. Same as @code{sum(1)}. -@item sum(@var{Expr}) - Sum of @var{Expr} for all solutions. -@item min(@var{Expr}) - Minimum of @var{Expr} for all solutions. -@item min(@var{Expr}, @var{Witness}) - A term min(@var{Min}, @var{Witness}), where @var{Min} is the minimal version of @var{Expr} - over all Solution and @var{Witness} is any other template applied to - Solution that produced @var{Min}. If multiple solutions provide the same - minimum, @var{Witness} corresponds to the first solution. -@item max(@var{Expr}) - Maximum of @var{Expr} for all solutions. -@item max(@var{Expr}, @var{Witness}) - As min(@var{Expr}, @var{Witness}), but producing the maximum result. -@item set(@var{X}) - An ordered set with all solutions for @var{X}. -@item bag(@var{X}) - A list of all solutions for @var{X}. -@end table - -The predicates are: -@table @code - -@item [nondet]aggregate(+@var{Template}, :@var{Goal}, -@var{Result}) -@findex aggregate/3 -@syindex aggregate/3 -@cnindex aggregate/3 - Aggregate bindings in @var{Goal} according to @var{Template}. The - aggregate/3 version performs bagof/3 on @var{Goal}. -@item [nondet]aggregate(+@var{Template}, +@var{Discriminator}, :@var{Goal}, -@var{Result}) -@findex aggregate/4 -@syindex aggregate/4 -@cnindex aggregate/4 - Aggregate bindings in @var{Goal} according to @var{Template}. The - aggregate/3 version performs setof/3 on @var{Goal}. -@item [semidet]aggregate_all(+@var{Template}, :@var{Goal}, -@var{Result}) -@findex aggregate_all/3 -@syindex aggregate_all/3 -@cnindex aggregate_all/3 - Aggregate bindings in @var{Goal} according to @var{Template}. The - aggregate_all/3 version performs findall/3 on @var{Goal}. -@item [semidet]aggregate_all(+@var{Template}, +@var{Discriminator}, :@var{Goal}, -@var{Result}) -@findex aggregate_all/4 -@syindex aggregate_all/4 -@cnindex aggregate_all/4 - Aggregate bindings in @var{Goal} according to @var{Template}. The - aggregate_all/3 version performs findall/3 followed by sort/2 on - @var{Goal}. -@item foreach(:Generator, :@var{Goal}) -@findex foreach/2 -@syindex foreach/2 -@cnindex foreach/2 - True if the conjunction of instances of @var{Goal} using the - bindings from Generator is true. Unlike forall/2, which runs a - failure-driven loop that proves @var{Goal} for each solution of - Generator, foreach creates a conjunction. Each member of the - conjunction is a copy of @var{Goal}, where the variables it shares - with Generator are filled with the values from the corresponding - solution. - - The implementation executes forall/2 if @var{Goal} does not contain - any variables that are not shared with Generator. - - Here is an example: -@pl_example - ?- foreach(between(1,4,X), dif(X,Y)), Y = 5. - Y = 5 - ?- foreach(between(1,4,X), dif(X,Y)), Y = 3. - No -@end pl_example - - Notice that @var{Goal} is copied repeatedly, which may cause - problems if attributed variables are involved. - -@item [det]free_variables(:Generator, +@var{Template}, +VarList0, -VarList) -@findex free_variables/4 -@syindex free_variables/4 -@cnindex free_variables/4 - In order to handle variables properly, we have to find all the universally quantified variables in the Generator. All variables as yet unbound are universally quantified, unless - -@enumerate -@item they occur in the template -@item they are bound by X/\P, setof, or bagof -@end enumerate - - @code{free_variables(Generator, Template, OldList, NewList)} finds this set, using OldList as an accumulator. -@end table - -The original author of this code was Richard O'Keefe. Jan Wielemaker - made some SWI-Prolog enhancements, sponsored by SecuritEase, - http://www.securitease.com. The code is public domain (from DEC10 library). - @c To be done - @c - Distinguish between control-structures and data terms. - @c - Exploit our built-in term_variables/2 at some places? - - - -@node Apply, Association Lists, Aggregate, Library -@section Apply Macros -@cindex apply - -This library provides a SWI-compatible set of utilities for applying a -predicate to all elements of a list. The library just forwards -definitions from the @code{maplist} library. - - - -@node Association Lists, AVL Trees, Apply, Library -@section Association Lists -@cindex association list - -The following association list manipulation predicates are available -once included with the @code{use_module(library(assoc))} command. The -original library used Richard O'Keefe's implementation, on top of -unbalanced binary trees. The current code utilises code from the -red-black trees library and emulates the SICStus Prolog interface. - -@table @code -@item assoc_to_list(+@var{Assoc},?@var{List}) -@findex assoc_to_list/2 -@syindex assoc_to_list/2 -@cnindex assoc_to_list/2 -Given an association list @var{Assoc} unify @var{List} with a list of -the form @var{Key-Val}, where the elements @var{Key} are in ascending -order. - -@item del_assoc(+@var{Key}, +@var{Assoc}, ?@var{Val}, ?@var{NewAssoc}) -@findex del_assoc/4 -@syindex del_assoc/4 -@cnindex del_assoc/4 -Succeeds if @var{NewAssoc} is an association list, obtained by removing -the element with @var{Key} and @var{Val} from the list @var{Assoc}. - -@item del_max_assoc(+@var{Assoc}, ?@var{Key}, ?@var{Val}, ?@var{NewAssoc}) -@findex del_max_assoc/4 -@syindex del_max_assoc/4 -@cnindex del_max_assoc/4 -Succeeds if @var{NewAssoc} is an association list, obtained by removing -the largest element of the list, with @var{Key} and @var{Val} from the -list @var{Assoc}. - -@item del_min_assoc(+@var{Assoc}, ?@var{Key}, ?@var{Val}, ?@var{NewAssoc}) -@findex del_min_assoc/4 -@syindex del_min_assoc/4 -@cnindex del_min_assoc/4 -Succeeds if @var{NewAssoc} is an association list, obtained by removing -the smallest element of the list, with @var{Key} and @var{Val} -from the list @var{Assoc}. - -@item empty_assoc(+@var{Assoc}) -@findex empty_assoc/1 -@syindex empty_assoc/1 -@cnindex empty_assoc/1 -Succeeds if association list @var{Assoc} is empty. - -@item gen_assoc(+@var{Assoc},?@var{Key},?@var{Value}) -@findex gen_assoc/3 -@syindex gen_assoc/3 -@cnindex gen_assoc/3 -Given the association list @var{Assoc}, unify @var{Key} and @var{Value} -with two associated elements. It can be used to enumerate all elements -in the association list. - -@item get_assoc(+@var{Key},+@var{Assoc},?@var{Value}) -@findex get_next_assoc/4 -@syindex get_next_assoc/4 -@cnindex get_next_assoc/4 -If @var{Key} is one of the elements in the association list @var{Assoc}, -return the associated value. - -@item get_assoc(+@var{Key},+@var{Assoc},?@var{Value},+@var{NAssoc},?@var{NValue}) -@findex get_assoc/5 -@syindex get_assoc/5 -@cnindex get_assoc/5 -If @var{Key} is one of the elements in the association list @var{Assoc}, -return the associated value @var{Value} and a new association list -@var{NAssoc} where @var{Key} is associated with @var{NValue}. - -@item get_prev_assoc(+@var{Key},+@var{Assoc},?@var{Next},?@var{Value}) -@findex get_prev_assoc/4 -@syindex get_prev_assoc/4 -@cnindex get_prev_assoc/4 -If @var{Key} is one of the elements in the association list @var{Assoc}, -return the previous key, @var{Next}, and its value, @var{Value}. - -@item get_next_assoc(+@var{Key},+@var{Assoc},?@var{Next},?@var{Value}) -@findex get_assoc/3 -@syindex get_assoc/3 -@cnindex get_assoc/3 -If @var{Key} is one of the elements in the association list @var{Assoc}, -return the next key, @var{Next}, and its value, @var{Value}. - -@item is_assoc(+@var{Assoc}) -@findex is_assoc/1 -@syindex is_assoc/1 -@cnindex is_assoc/1 -Succeeds if @var{Assoc} is an association list, that is, if it is a -red-black tree. - -@item list_to_assoc(+@var{List},?@var{Assoc}) -@findex list_to_assoc/2 -@syindex list_to_assoc/2 -@cnindex list_to_assoc/2 -Given a list @var{List} such that each element of @var{List} is of the -form @var{Key-Val}, and all the @var{Keys} are unique, @var{Assoc} is -the corresponding association list. - -@item map_assoc(+@var{Pred},+@var{Assoc}) -@findex map_assoc/2 -@syindex map_assoc/2 -@cnindex map_assoc/2 -Succeeds if the unary predicate name @var{Pred}(@var{Val}) holds for every -element in the association list. - -@item map_assoc(+@var{Pred},+@var{Assoc},?@var{New}) -@findex map_assoc/3 -@syindex map_assoc/3 -@cnindex map_assoc/3 -Given the binary predicate name @var{Pred} and the association list -@var{Assoc}, @var{New} in an association list with keys in @var{Assoc}, -and such that if @var{Key-Val} is in @var{Assoc}, and @var{Key-Ans} is in -@var{New}, then @var{Pred}(@var{Val},@var{Ans}) holds. - -@item max_assoc(+@var{Assoc},-@var{Key},?@var{Value}) -@findex max_assoc/3 -@syindex max_assoc/3 -@cnindex max_assoc/3 -Given the association list -@var{Assoc}, @var{Key} in the largest key in the list, and @var{Value} -the associated value. - -@item min_assoc(+@var{Assoc},-@var{Key},?@var{Value}) -@findex min_assoc/3 -@syindex min_assoc/3 -@cnindex min_assoc/3 -Given the association list -@var{Assoc}, @var{Key} in the smallest key in the list, and @var{Value} -the associated value. - -@item ord_list_to_assoc(+@var{List},?@var{Assoc}) -@findex ord_list_to_assoc/2 -@syindex ord_list_to_assoc/2 -@cnindex ord_list_to_assoc/2 -Given an ordered list @var{List} such that each element of @var{List} is -of the form @var{Key-Val}, and all the @var{Keys} are unique, @var{Assoc} is -the corresponding association list. - -@item put_assoc(+@var{Key},+@var{Assoc},+@var{Val},+@var{New}) -@findex put_assoc/4 -@syindex put_assoc/4 -@cnindex put_assoc/4 -The association list @var{New} includes and element of association -@var{key} with @var{Val}, and all elements of @var{Assoc} that did not -have key @var{Key}. - -@end table - -@node AVL Trees, Exo Intervals, Association Lists, Library -@section AVL Trees -@cindex AVL trees - -AVL trees are balanced search binary trees. They are named after their -inventors, Adelson-Velskii and Landis, and they were the first -dynamically balanced trees to be proposed. The YAP AVL tree manipulation -predicates library uses code originally written by Martin van Emdem and -published in the Logic Programming Newsletter, Autumn 1981. A bug in -this code was fixed by Philip Vasey, in the Logic Programming -Newsletter, Summer 1982. The library currently only includes routines to -insert and lookup elements in the tree. Please try red-black trees if -you need deletion. - -@table @code -@item avl_new(+@var{T}) -@findex avl_new/1 -@snindex avl_new/1 -@cnindex avl_new/1 -Create a new tree. - -@item avl_insert(+@var{Key},?@var{Value},+@var{T0},-@var{TF}) -@findex avl_insert/4 -@snindex avl_insert/4 -@cnindex avl_insert/4 -Add an element with key @var{Key} and @var{Value} to the AVL tree -@var{T0} creating a new AVL tree @var{TF}. Duplicated elements are -allowed. - -@item avl_lookup(+@var{Key},-@var{Value},+@var{T}) -@findex avl_lookup/3 -@snindex avl_lookup/3 -@cnindex avl_lookup/3 -Lookup an element with key @var{Key} in the AVL tree -@var{T}, returning the value @var{Value}. - -@end table - -@node Exo Intervals, Gecode, AVL Trees, Library -@section Exo Intervals -@cindex Indexing Numeric Intervals in Exo-predicates -This package assumes you use exo-compilation, that is, that you loaded -the pedicate using the @code{exo} option to @code{load_files/2}, In this -case, YAP includes a package for improved search on intervals of -integers. - -The package is activated by @code{udi} declarations that state what is -the argument of interest: -@pl_example -:- udi(diagnoses(exo_interval,?,?)). - -:- load_files(db, [consult(exo)]). -@end pl_example -It is designed to optimise the following type of queries: -@pl_example -?- max(X, diagnoses(X, 9, Y), X). - -?- min(X, diagnoses(X, 9, 36211117), X). - -?- X #< Y, min(X, diagnoses(X, 9, 36211117), X ), diagnoses(Y, 9, _). -@end pl_example -The first argument gives the time, the second the patient, and the -third the condition code. The first query should find the last time -the patient 9 had any code reported, the second looks for the first -report of code 36211117, and the last searches for reports after this -one. All queries run in constant or log(n) time. - -@node Gecode, Heaps, Exo Intervals, Library -@section Gecode Interface -@cindex gecode - -The gecode library intreface was designed and implemented by Denis -Duchier, with recent work by Vítor Santos Costa to port it to version 4 -of gecode and to have an higher level interface, - -@menu -* The Gecode Interface:: calling gecode from YAP -* Gecode and ClP(FD) :: using gecode in a CLP(FD) style -@end menu - -@node The Gecode Interface, ,Gecode and ClP(FD), Gecode -@subsection The Gecode Interface - -This text is due to Denys Duchier. The gecode interface requires -@pl_example -:- use_module(library(gecode)). -@end pl_example -Several example programs are available with the distribution. - -@table @code -@item CREATING A SPACE - -A space is gecodes data representation for a store of constraints: -@pl_example - Space := space -@end pl_example - - -@item CREATING VARIABLES - -Unlike in Gecode, variable objects are not bound to a specific Space. Each one -actually contains an index with which it is possible to access a Space-bound -Gecode variable. Variables can be created using the following expressions: - -@pl_example - IVar := intvar(Space,SPEC...) - BVar := boolvar(Space) - SVar := setvar(Space,SPEC...) -@end pl_example - -where SPEC... is the same as in Gecode. For creating lists of variables use -the following variants: - -@pl_example - IVars := intvars(Space,N,SPEC...) - BVars := boolvars(Space,N,SPEC...) - SVars := setvars(Space,N,SPEC...) -@end pl_example - -where N is the number of variables to create (just like for XXXVarArray in -Gecode). Sometimes an IntSet is necessary: - -@pl_example - ISet := intset([SPEC...]) -@end pl_example - -where each SPEC is either an integer or a pair (I,J) of integers. An IntSet -describes a set of ints by providing either intervals, or integers (which stand -for an interval of themselves). It might be tempting to simply represent an -IntSet as a list of specs, but this would be ambiguous with IntArgs which, -here, are represented as lists of ints. - -@pl_example - Space += keep(Var) - Space += keep(Vars) -@end pl_example - -Variables can be marked as "kept". In this case, only such variables will be -explicitly copied during search. This could bring substantial benefits in -memory usage. Of course, in a solution, you can then only look at variables -that have been "kept". If no variable is marked as "kept", then they are all -kept. Thus marking variables as "kept" is purely an optimization. - - -@item CONSTRAINTS AND BRANCHINGS - -all constraint and branching posting functions are available just like in -Gecode. Wherever a XXXArgs or YYYSharedArray is expected, simply use a list. -At present, there is no support for minimodel-like constraint posting. -Constraints and branchings are added to a space using: - -@pl_example - Space += CONSTRAINT - Space += BRANCHING -@end pl_example - -For example: - -@pl_example - Space += rel(X,'IRT_EQ',Y) -@end pl_example - - -arrays of variables are represented by lists of variables, and constants are -represented by atoms with the same name as the Gecode constant -(e.g. 'INT_VAR_SIZE_MIN'). - -@item SEARCHING FOR SOLUTIONS - -@pl_example - SolSpace := search(Space) -@end pl_example - - -This is a backtrackable predicate that enumerates all solution spaces -(SolSpace). It may also take options: - -@pl_example - SolSpace := search(Space,Options) -@end pl_example - - -Options is a list whose elements maybe: - -@table @code -@item restart - to select the Restart search engine -@item threads=N - to activate the parallel search engine and control the number of - workers (see Gecode doc) -@item c_d=N - to set the commit distance for recomputation -@item a_d=N - to set the adaptive distance for recomputation - -@end table - -@item EXTRACTING INFO FROM A SOLUTION - -An advantage of non Space-bound variables, is that you can use them both to -post constraints in the original space AND to consult their values in -solutions. Below are methods for looking up information about variables. Each -of these methods can either take a variable as argument, or a list of -variables, and returns resp. either a value, or a list of values: - -@pl_example - Val := assigned(Space,X) - - Val := min(Space,X) - Val := max(Space,X) - Val := med(Space,X) - Val := val(Space,X) - Val := size(Space,X) - Val := width(Space,X) - Val := regret_min(Space,X) - Val := regret_max(Space,X) - - Val := glbSize(Space,V) - Val := lubSize(Space,V) - Val := unknownSize(Space,V) - Val := cardMin(Space,V) - Val := cardMax(Space,V) - Val := lubMin(Space,V) - Val := lubMax(Space,V) - Val := glbMin(Space,V) - Val := glbMax(Space,V) - Val := glb_ranges(Space,V) - Val := lub_ranges(Space,V) - Val := unknown_ranges(Space,V) - Val := glb_values(Space,V) - Val := lub_values(Space,V) - Val := unknown_values(Space,V) - @end pl_example - -@item DISJUNCTORS - - -Disjunctors provide support for disjunctions of clauses, where each clause is a -conjunction of constraints: - -@pl_example - C1 or C2 or ... or Cn -@end pl_example - - -Each clause is executed "speculatively": this means it does not affect the main -space. When a clause becomes failed, it is discarded. When only one clause -remains, it is committed: this means that it now affects the main space. - -Example: - -Consider the problem where either X=Y=0 or X=Y+(1 or 2) for variable X and Y -that take values in 0..3. - -@pl_example - Space := space, - [X,Y] := intvars(Space,2,0,3), -@end pl_example - -First, we must create a disjunctor as a manager for our 2 clauses: - -@pl_example - Disj := disjunctor(Space), -@end pl_example - -We can now create our first clause: - -@pl_example - C1 := clause(Disj), -@end pl_example - - -This clause wants to constrain X and Y to 0. However, since it must be -executed "speculatively", it must operate on new variables X1 and Y1 that -shadow X and Y: - -@pl_example - [X1,Y1] := intvars(C1,2,0,3), - C1 += forward([X,Y],[X1,Y1]), -@end pl_example - -The forward(...) stipulation indicates which global variable is shadowed by -which clause-local variable. Now we can post the speculative clause-local -constraints for X=Y=0: - -@pl_example - C1 += rel(X1,'IRT_EQ',0), - C1 += rel(Y1,'IRT_EQ',0), -@end pl_example - -We now create the second clause which uses X2 and Y2 to shadow X and Y: - -@pl_example - C2 := clause(Disj), - [X2,Y2] := intvars(C2,2,0,3), - C2 += forward([X,Y],[X2,Y2]), -@end pl_example - -However, this clause also needs a clause-local variable Z2 taking values 1 or -2 in order to post the clause-local constraint X2=Y2+Z2: - -@pl_example - Z2 := intvar(C2,1,2), - C2 += linear([-1,1,1],[X2,Y2,Z2],'IRT_EQ',0), -@end pl_example - -Finally, we can branch and search: - -@pl_example - Space += branch([X,Y],'INT_VAR_SIZE_MIN','INT_VAL_MIN'), - SolSpace := search(Space), -@end pl_example - -and lookup values of variables in each solution: - -@pl_example - [X_,Y_] := val(SolSpace,[X,Y]). -@end pl_example - -@end table - -@node Gecode and ClP(FD), The Gecode Interface, , Gecode -@subsection Programming Finite Domain Constraints in YAP/Gecode - -The gecode/clp(fd) interface is designed to use the GECODE functionality -in a more CLP like style. It requires -@pl_example -:- use_module(library(gecode/clpfd)). -@end pl_example -Several example programs are available with the distribution. - -Integer variables are declared as: -@table @code -@item @var{V} in @var{A}..@var{B} -declares an integer variable @var{V} with range @var{A} to @var{B}. -@item @var{Vs} ins @var{A}..@var{B} -declares a set of integer variabless @var{Vs} with range @var{A} to @var{B}. -@item boolvar(@var{V}) -declares a boolean variable. -@item boolvars(@var{Vs}) -declares a set of boolean variable. -@end table - - -Constraints supported are: -@table @code -@item @var{X} #= @var{Y} -equality -@item @var{X} #\= @var{Y} -disequality -@item @var{X} #> @var{Y} -larger -@item @var{X} #>= @var{Y} -larger or equal -@item @var{X} #=< @var{Y} -smaller -@item @var{X} #< @var{Y} -smaller or equal - -Arguments to this constraint may be an arithmetic expression with @t{+}, -@t{-}, @t{*}, integer division @t{/}, @t{min}, @t{max}, @t{sum}, -@t{count}, and -@t{abs}. Boolean variables support conjunction (/\), disjunction (\/), -implication (=>), equivalence (<=>), and xor. The @t{sum} constraint allows a two argument version using the -@code{where} conditional, in Zinc style. - -The send more money equation may be written as: -@pl_example - 1000*S + 100*E + 10*N + D + - 1000*M + 100*O + 10*R + E #= -10000*M + 1000*O + 100*N + 10*E + Y, -@end pl_example - -This example uses @code{where} to select from -column @var{I} the elements that have value under @var{M}: -@pl_example -OutFlow[I] #= sum(J in 1..N where D[J,I] -elements of @var{X} must be increasing -@item @var{X} #>= -elements of @var{X} must be increasinga or equal -@item @var{X} #=< -elements of @var{X} must be decreasing -@item @var{X} #< -elements of @var{X} must be decreasing or equal - - -@item @var{X} #<==> @var{B} -reified equivalence -@item @var{X} #==> @var{B} -reified implication -@item @var{X} #< @var{B} -reified implication - -As an example. consider finding out the people who wanted to sit -next to a friend and that are are actually sitting together: -@pl_example -preference_satisfied(X-Y, B) :- - abs(X - Y) #= 1 #<==> B. -@end pl_example -Note that not all constraints may be reifiable. - -@item element(@var{X}, @var{Vs} ) -@var{X} is an element of list @var{Vs} - -@item clause(@var{Type}, @var{Ps} , @var{Ns}, @var{V} ) -If @var{Type} is @code{and} it is the conjunction of boolean variables -@var{Ps} and the negation of boolean variables @var{Ns} and must have -result @var{V}. If @var{Type} is @code{or} it is a disjunction. - -@item DFA -the interface allows creating and manipulation deterministic finite -automata. A DFA has a set of states, represented as integers -and is initialised with an initial state, a set of transitions from the -first to the last argument emitting the middle argument, and a final -state. - -The swedish-drinkers protocol is represented as follows: -@pl_example - A = [X,Y,Z], - dfa( 0, [t(0,0,0),t(0,1,1),t(1,0,0),t(-1,0,0)], [0], C), - in_dfa( A, C ), -@end pl_example -This code will enumeratae the valid tuples of three emissions. - -@item extensional constraints -Constraints can also be represented as lists of tuples. - -The previous example -would be written as: -@pl_example - extensional_constraint([[0,0,0],[0,1,0],[1,0,0]], C), - in_relation( A, C ), -@end pl_example - -@item minimum(@var{X}, @var{Vs}) -@item min(@var{X}, @var{Vs}) -First Argument is the least element of a list. - -@item maximum(@var{X}, @var{Vs}) -@item max(@var{X}, @var{Vs}) -First Argument is the greatest element of a list. - -@item lex_order(@var{Vs}) -All elements must be ordered. - -@end table - -The following predicates control search: -@table @code -@item labeling(@var{Opts}, @var{Xs}) -performs labeling, several variable and value selection options are -available. The defaults are @code{min} and @code{min_step}. - -Variable selection options are as follows: -@table @code -@item leftmost -choose the first variable -@item min -choose one of the variables with smallest minimum value -@item max -choose one of the variables with greatest maximum value -@item ff -choose one of the most constrained variables, that is, with the smallest -domain. -@end table - -Given that we selected a variable, the values chosen for branching may -be: -@table @code -@item min_step -smallest value - @item max_step - largest value - @item bisect - median - @item enum - all value starting from the minimum. -@end table - - -@item maximize(@var{V}) -maximise variable @var{V} - -@item minimize(@t{V}) -minimise variable @var{V} - -@end table - - - -@node Heaps, Lists, Gecode, Library -@section Heaps -@cindex heap - -A heap is a labelled binary tree where the key of each node is less than -or equal to the keys of its sons. The point of a heap is that we can -keep on adding new elements to the heap and we can keep on taking out -the minimum element. If there are N elements total, the total time is -O(NlgN). If you know all the elements in advance, you are better off -doing a merge-sort, but this file is for when you want to do say a -best-first search, and have no idea when you start how many elements -there will be, let alone what they are. - -The following heap manipulation routines are available once included -with the @code{use_module(library(heaps))} command. - -@table @code - -@item add_to_heap(+@var{Heap},+@var{key},+@var{Datum},-@var{NewHeap}) -@findex add_to_heap/4 -@syindex add_to_heap/4 -@cnindex add_to_heap/4 -Inserts the new @var{Key-Datum} pair into the heap. The insertion is not -stable, that is, if you insert several pairs with the same @var{Key} it -is not defined which of them will come out first, and it is possible for -any of them to come out first depending on the history of the heap. - -@item empty_heap(?@var{Heap}) -@findex empty_heap/1 -@syindex empty_heap/1 -@cnindex empty_heap/1 -Succeeds if @var{Heap} is an empty heap. - -@item get_from_heap(+@var{Heap},-@var{key},-@var{Datum},-@var{Heap}) -@findex get_from_heap/4 -@syindex get_from_heap/4 -@cnindex get_from_heap/4 -Returns the @var{Key-Datum} pair in @var{OldHeap} with the smallest -@var{Key}, and also a @var{Heap} which is the @var{OldHeap} with that -pair deleted. - -@item heap_size(+@var{Heap}, -@var{Size}) -@findex heap_size/2 -@syindex heap_size/2 -@cnindex heap_size/2 -Reports the number of elements currently in the heap. - -@item heap_to_list(+@var{Heap}, -@var{List}) -@findex heap_to_list/2 -@syindex heap_to_list/2 -@cnindex heap_to_list/2 -Returns the current set of @var{Key-Datum} pairs in the @var{Heap} as a -@var{List}, sorted into ascending order of @var{Keys}. - -@item list_to_heap(+@var{List}, -@var{Heap}) -@findex list_to_heap/2 -@syindex list_to_heap/2 -@cnindex list_to_heap/2 -Takes a list of @var{Key-Datum} pairs (such as keysort could be used to sort) -and forms them into a heap. - -@item min_of_heap(+@var{Heap}, -@var{Key}, -@var{Datum}) -@findex min_of_heap/3 -@syindex min_of_heap/3 -@cnindex min_of_heap/3 -Returns the Key-Datum pair at the top of the heap (which is of course -the pair with the smallest Key), but does not remove it from the heap. - -@item min_of_heap(+@var{Heap}, -@var{Key1}, -@var{Datum1}, --@var{Key2}, -@var{Datum2}) -@findex min_of_heap/5 -@syindex min_of_heap/5 -@cnindex min_of_heap/5 -Returns the smallest (Key1) and second smallest (Key2) pairs in the -heap, without deleting them. -@end table - -@node Lists, LineUtilities, Heaps, Library -@section List Manipulation -@cindex list manipulation - -The following list manipulation routines are available once included -with the @code{use_module(library(lists))} command. - -@table @code - -@item append(?@var{Prefix},?@var{Suffix},?@var{Combined}) -@findex append/3 -@syindex append/3 -@cnindex append/3 -True when all three arguments are lists, and the members of -@var{Combined} are the members of @var{Prefix} followed by the members of @var{Suffix}. -It may be used to form @var{Combined} from a given @var{Prefix}, @var{Suffix} or to take -a given @var{Combined} apart. - -@item append(?@var{Lists},?@var{Combined}) -@findex append/2 -@syindex append/2 -@cnindex append/2 -Holds if the lists of @var{Lists} can be concatenated as a -@var{Combined} list. - -@item delete(+@var{List}, ?@var{Element}, ?@var{Residue}) -@findex delete/3 -@syindex delete/3 -@cnindex delete/3 -True when @var{List} is a list, in which @var{Element} may or may not -occur, and @var{Residue} is a copy of @var{List} with all elements -identical to @var{Element} deleted. - -@item flatten(+@var{List}, ?@var{FlattenedList}) -@findex flatten/2 -@syindex flatten/2 -@cnindex flatten/2 -Flatten a list of lists @var{List} into a single list -@var{FlattenedList}. - -@pl_example -?- flatten([[1],[2,3],[4,[5,6],7,8]],L). - -L = [1,2,3,4,5,6,7,8] ? ; - -no -@end pl_example - -@item last(+@var{List},?@var{Last}) -@findex last/2 -@syindex last/2 -@cnindex last/2 -True when @var{List} is a list and @var{Last} is identical to its last element. - -@item list_concat(+@var{Lists},?@var{List}) -@findex list_concat/2 -@snindex list_concat/2 -@cnindex list_concat/2 -True when @var{Lists} is a list of lists and @var{List} is the -concatenation of @var{Lists}. - -@item member(?@var{Element}, ?@var{Set}) -@findex member/2 -@syindex member/2 -@cnindex member/2 -True when @var{Set} is a list, and @var{Element} occurs in it. It may be used -to test for an element or to enumerate all the elements by backtracking. - -@item memberchk(+@var{Element}, +@var{Set}) -@findex memberchk/2 -@syindex memberchk/2 -@cnindex memberchk/2 -As @code{member/2}, but may only be used to test whether a known -@var{Element} occurs in a known Set. In return for this limited use, it -is more efficient when it is applicable. - -@item nth0(?@var{N}, ?@var{List}, ?@var{Elem}) -@findex nth0/3 -@syindex nth0/3 -@cnindex nth0/3 -True when @var{Elem} is the Nth member of @var{List}, -counting the first as element 0. (That is, throw away the first -N elements and unify @var{Elem} with the next.) It can only be used to -select a particular element given the list and index. For that -task it is more efficient than @code{member/2} - -@item nth1(?@var{N}, ?@var{List}, ?@var{Elem}) -@findex nth1/3 -@syindex nth1/3 -@cnindex nth1/3 -The same as @code{nth0/3}, except that it counts from -1, that is @code{nth(1, [H|_], H)}. - -@item nth(?@var{N}, ?@var{List}, ?@var{Elem}) -@findex nth/3 -@syindex nth/3 -@cnindex nth/3 -The same as @code{nth1/3}. - -@item nth0(?@var{N}, ?@var{List}, ?@var{Elem}, ?@var{Rest}) -@findex nth0/4 -@syindex nth0/4 -@cnindex nth0/4 -Unifies @var{Elem} with the Nth element of @var{List}, -counting from 0, and @var{Rest} with the other elements. It can be used -to select the Nth element of @var{List} (yielding @var{Elem} and @var{Rest}), or to -insert @var{Elem} before the Nth (counting from 1) element of @var{Rest}, when -it yields @var{List}, e.g. @code{nth0(2, List, c, [a,b,d,e])} unifies List with -@code{[a,b,c,d,e]}. @code{nth/4} is the same except that it counts from 1. @code{nth0/4} -can be used to insert @var{Elem} after the Nth element of @var{Rest}. - -@item nth1(?@var{N}, ?@var{List}, ?@var{Elem}, ?@var{Rest}) -@findex nth1/4 -@syindex nth1/4 -@cnindex nth1/4 -Unifies @var{Elem} with the Nth element of @var{List}, counting from 1, -and @var{Rest} with the other elements. It can be used to select the -Nth element of @var{List} (yielding @var{Elem} and @var{Rest}), or to -insert @var{Elem} before the Nth (counting from 1) element of -@var{Rest}, when it yields @var{List}, e.g. @code{nth(3, List, c, [a,b,d,e])} unifies List with @code{[a,b,c,d,e]}. @code{nth/4} -can be used to insert @var{Elem} after the Nth element of @var{Rest}. - -@item nth(?@var{N}, ?@var{List}, ?@var{Elem}, ?@var{Rest}) -@findex nth/4 -@syindex nth/4 -@cnindex nth/4 -Same as @code{nth1/4}. - -@item permutation(+@var{List},?@var{Perm}) -@findex permutation/2 -@syindex permutation/2 -@cnindex permutation/2 -True when @var{List} and @var{Perm} are permutations of each other. - -@item remove_duplicates(+@var{List}, ?@var{Pruned}) -@findex remove_duplicates/2 -@syindex remove_duplicates/2 -@cnindex remove_duplicates/2 -Removes duplicated elements from @var{List}. Beware: if the @var{List} has -non-ground elements, the result may surprise you. - -@item reverse(+@var{List}, ?@var{Reversed}) -@findex reverse/2 -@syindex reverse/2 -@cnindex reverse/2 -True when @var{List} and @var{Reversed} are lists with the same elements -but in opposite orders. - -@item same_length(?@var{List1}, ?@var{List2}) -@findex same_length/2 -@syindex same_length/2 -@cnindex same_length/2 -True when @var{List1} and @var{List2} are both lists and have the same number -of elements. No relation between the values of their elements is -implied. -Modes @code{same_length(-,+)} and @code{same_length(+,-)} generate either list given -the other; mode @code{same_length(-,-)} generates two lists of the same length, -in which case the arguments will be bound to lists of length 0, 1, 2, ... - -@item select(?@var{Element}, ?@var{List}, ?@var{Residue}) -@findex select/3 -@syindex select/3 -@cnindex select/3 -True when @var{Set} is a list, @var{Element} occurs in @var{List}, and -@var{Residue} is everything in @var{List} except @var{Element} (things -stay in the same order). - -@item selectchk(?@var{Element}, ?@var{List}, ?@var{Residue}) -@findex selectchk/3 -@snindex selectchk/3 -@cnindex selectchk/3 -Semi-deterministic selection from a list. Steadfast: defines as - -@pl_example -selectchk(Elem, List, Residue) :- - select(Elem, List, Rest0), !, - Rest = Rest0. -@end pl_example - - -@item sublist(?@var{Sublist}, ?@var{List}) -@findex sublist/2 -@syindex sublist/2 -@cnindex sublist/2 -True when both @code{append(_,Sublist,S)} and @code{append(S,_,List)} hold. - -@item suffix(?@var{Suffix}, ?@var{List}) -@findex suffix/2 -@syindex suffix/2 -@cnindex suffix/2 -Holds when @code{append(_,Suffix,List)} holds. - -@item sum_list(?@var{Numbers}, ?@var{Total}) -@findex sum_list/2 -@syindex sum_list/2 -@cnindex sum_list/2 -True when @var{Numbers} is a list of numbers, and @var{Total} is their sum. - -@item sum_list(?@var{Numbers}, +@var{SoFar}, ?@var{Total}) -@findex sum_list/3 -@syindex sum_list/3 -@cnindex sum_list/3 -True when @var{Numbers} is a list of numbers, and @var{Total} is the sum of their total plus @var{SoFar}. - -@item sumlist(?@var{Numbers}, ?@var{Total}) -@findex sumlist/2 -@syindex sumlist/2 -@cnindex sumlist/2 -True when @var{Numbers} is a list of integers, and @var{Total} is their -sum. The same as @code{sum_list/2}, please do use @code{sum_list/2} -instead. - -@item max_list(?@var{Numbers}, ?@var{Max}) -@findex max_list/2 -@syindex max_list/2 -@cnindex max_list/2 -True when @var{Numbers} is a list of numbers, and @var{Max} is the maximum. - -@item min_list(?@var{Numbers}, ?@var{Min}) -@findex min_list/2 -@syindex min_list/2 -@cnindex min_list/2 -True when @var{Numbers} is a list of numbers, and @var{Min} is the minimum. - -@item numlist(+@var{Low}, +@var{High}, +@var{List}) -@findex numlist/3 -@syindex numlist/3 -@cnindex numlist/3 -If @var{Low} and @var{High} are integers with @var{Low} =< -@var{High}, unify @var{List} to a list @code{[Low, Low+1, ...High]}. See -also @code{between/3}. - -@item intersection(+@var{Set1}, +@var{Set2}, +@var{Set3}) -@findex intersection/3 -@syindex intersection/3 -@cnindex intersection/3 -Succeeds if @var{Set3} unifies with the intersection of @var{Set1} and -@var{Set2}. @var{Set1} and @var{Set2} are lists without duplicates. They -need not be ordered. - -@item subtract(+@var{Set}, +@var{Delete}, ?@var{Result}) -@findex subtract/3 -@syindex subtract/3 -@cnindex subtract/3 -Delete all elements from @var{Set} that occur in @var{Delete} (a set) -and unify the result with @var{Result}. Deletion is based on -unification using @code{memberchk/2}. The complexity is -@code{|Delete|*|Set|}. - -See @code{ord_subtract/3}. -@end table - -@node LineUtilities, MapArgs, Lists, Library -@section Line Manipulation Utilities -@cindex Line Utilities Library - -This package provides a set of useful predicates to manipulate -sequences of characters codes, usually first read in as a line. It is -available by loading the library @code{library(lineutils)}. - -@table @code - -@item search_for(+@var{Char},+@var{Line}) -@findex search_for/2 -@snindex search_for/2 -@cnindex search_for/2 - -Search for a character @var{Char} in the list of codes @var{Line}. - -@item search_for(+@var{Char},+@var{Line},-@var{RestOfine}) -@findex search_for/3 -@snindex search_for/3 -@cnindex search_for/3 - -Search for a character @var{Char} in the list of codes @var{Line}, -@var{RestOfLine} has the line to the right. - -@item scan_natural(?@var{Nat},+@var{Line},+@var{RestOfLine}) -@findex scan_natural/3 -@snindex scan_natural/3 -@cnindex scan_natural/3 - -Scan the list of codes @var{Line} for a natural number @var{Nat}, zero -or a positive integer, and unify @var{RestOfLine} with the remainder -of the line. - -@item scan_integer(?@var{Int},+@var{Line},+@var{RestOfLine}) -@findex scan_integer/3 -@snindex scan_integer/3 -@cnindex scan_integer/3 - -Scan the list of codes @var{Line} for an integer @var{Nat}, either a -positive, zero, or negative integer, and unify @var{RestOfLine} with -the remainder of the line. - -@item split(+@var{Line},+@var{Separators},-@var{Split}) -@findex split/3 -@snindex split/3 -@cnindex split/3 - -Unify @var{Words} with a set of strings obtained from @var{Line} by -using the character codes in @var{Separators} as separators. As an -example, consider: -@pl_example -?- split("Hello * I am free"," *",S). - -S = ["Hello","I","am","free"] ? - -no -@end pl_example - -@item split(+@var{Line},-@var{Split}) -@findex split/2 -@snindex split/2 -@cnindex split/2 - -Unify @var{Words} with a set of strings obtained from @var{Line} by -using the blank characters as separators. - -@item fields(+@var{Line},+@var{Separators},-@var{Split}) -@findex fields/3 -@snindex fields/3 -@cnindex fields/3 - -Unify @var{Words} with a set of strings obtained from @var{Line} by -using the character codes in @var{Separators} as separators for -fields. If two separators occur in a row, the field is considered -empty. As an example, consider: -@pl_example -?- fields("Hello I am free"," *",S). - -S = ["Hello","","I","am","","free"] ? -@end pl_example - -@item fields(+@var{Line},-@var{Split}) -@findex fields/2 -@snindex fields/2 -@cnindex fields/2 - -Unify @var{Words} with a set of strings obtained from @var{Line} by -using the blank characters as field separators. - -@item glue(+@var{Words},+@var{Separator},-@var{Line}) -@findex glue/3 -@snindex glue/3 -@cnindex glue/3 - -Unify @var{Line} with string obtained by glueing @var{Words} with -the character code @var{Separator}. - -@item copy_line(+@var{StreamInput},+@var{StreamOutput}) -@findex copy_line/2 -@snindex copy_line/2 -@cnindex copy_line/2 - -Copy a line from @var{StreamInput} to @var{StreamOutput}. - -@item process(+@var{StreamInp}, +@var{Goal}) -@findex process/2 -@snindex process/2 -@cnindex process/2 - -For every line @var{LineIn} in stream @var{StreamInp}, call -@code{call(Goal,LineIn)}. - -@item filter(+@var{StreamInp}, +@var{StreamOut}, +@var{Goal}) -@findex filter/3 -@snindex filter/3 -@cnindex filter/3 - -For every line @var{LineIn} in stream @var{StreamInp}, execute -@code{call(Goal,LineIn,LineOut)}, and output @var{LineOut} to -stream @var{StreamOut}. - -@item file_filter(+@var{FileIn}, +@var{FileOut}, +@var{Goal}) -@findex file_filter/3 -@snindex file_filter/3 -@cnindex file_filter/3 - -For every line @var{LineIn} in file @var{FileIn}, execute -@code{call(Goal,LineIn,LineOut)}, and output @var{LineOut} to file -@var{FileOut}. - -@item file_filter(+@var{FileIn}, +@var{FileOut}, +@var{Goal}, -+@var{FormatCommand}, +@var{Arguments}) -@findex file_filter_with_init/5 -@snindex file_filter_with_init/5 -@cnindex file_filter_with_init/5 - -Same as @code{file_filter/3}, but before starting the filter execute -@code{format/3} on the output stream, using @var{FormatCommand} and -@var{Arguments}. - -@end table - - -@texinfo - - -@node MapArgs, MapList, LineUtilities, Library -@section Maplist -@cindex macros - -This library provides a set of utilities for applying a predicate to -all sub-terms of a term. They allow to -easily perform the most common do-loop constructs in Prolog. To avoid -performance degradation due to @code{apply/2}, each call creates an -equivalent Prolog program, without meta-calls, which is executed by -the Prolog engine instead. - -@table @code -@item mapargs(+@var{Pred}, +@var{TermIn}) -@findex mapargs/2 -@snindex mapargs/2 -@cnindex mapargs/2 - Applies the predicate @var{Pred} to all - arguments of @var{TermIn} - -@item mapargs(+@var{Pred}, +@var{TermIn}, ?@var{TermOut}) -@findex mapargs/3 -@snindex mapargs/3 -@cnindex mapargs/3 - Creates @var{TermOut} by applying the predicate @var{Pred} to all - arguments of @var{TermIn} - -@item mapargs(+@var{Pred}, +@var{TermIn}, ?@var{TermOut1}, ?@var{TermOut2}) -@findex mapargs/4 -@snindex mapargs/4 -@cnindex mapargs/4 - Creates @var{TermOut1} and @var{TermOut2} by applying the predicate @var{Pred} to all - arguments of @var{TermIn} - -@item mapargs(+@var{Pred}, +@var{TermIn}, ?@var{TermOut1}, ?@var{TermOut2}, ?@var{TermOut3}) -@findex mapargs/5 -@snindex mapargs/5 -@cnindex mapargs/5 - Creates @var{TermOut1}, @var{TermOut2} and @var{TermOut3} by applying the predicate @var{Pred} to all - arguments of @var{TermIn} - -@item mapargs(+@var{Pred}, +@var{TermIn}, ?@var{TermOut1}, ?@var{TermOut2}, ?@var{TermOut3}, ?@var{TermOut4}) -@findex mapargs/6 -@snindex mapargs/6 -@cnindex mapargs/6 - Creates @var{TermOut1}, @var{TermOut2}, @var{TermOut3} and @var{TermOut4} by applying the predicate @var{Pred} to all - arguments of @var{TermIn} - - -@item foldargs(+@var{Pred}, +@var{Term}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldargs/4 -@snindex foldargs/4 -@cnindex foldargs/4 - Calls the predicate @var{Pred} on all arguments of @var{Term} and -collects a result in @var{Accumulator} - -@item foldargs(+@var{Pred}, +@var{Term}, +@var{Term1}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldargs/5 -@snindex foldargs/5 -@cnindex foldargs/5 - Calls the predicate @var{Pred} on all arguments of @var{Term} and @var{Term1} and -collects a result in @var{Accumulator} - -@item foldargs(+@var{Pred}, +@var{Term}, +@var{Term1}, +@var{Term2}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldargs/6 -@snindex foldargs/6 -@cnindex foldargs/6 - Calls the predicate @var{Pred} on all arguments of @var{Term}, +@var{Term1} and @var{Term2} and -collects a result in @var{Accumulator} - -@item foldargs(+@var{Pred}, +@var{Term}, +@var{Term1}, +@var{Term2}, +@var{Term3}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldargs/7 -@snindex foldargs/7 -@cnindex foldargs/7 - Calls the predicate @var{Pred} on all arguments of @var{Term}, +@var{Term1}, +@var{Term2} and @var{Term3} and -collects a result in @var{Accumulator} - -@item sumargs(+@var{Pred}, +@var{Term}, ?@var{AccIn}, ?@var{AccOut}) -@findex sumargs/4 -@snindex sumargs/4 -@cnindex sumargs/4 - Calls the predicate @var{Pred} on all arguments of @var{Term} and -collects a result in @var{Accumulator} (uses reverse order than foldargs). - -@end table - -@texinfo - - -@node MapList, matrix, MapArgs, Library -@section Maplist -@cindex macros - -This library provides a set of utilities for applying a predicate to -all elements of a list or to all sub-terms of a term. They allow to -easily perform the most common do-loop constructs in Prolog. To avoid -performance degradation due to @code{apply/2}, each call creates an -equivalent Prolog program, without meta-calls, which is executed by -the Prolog engine instead. Note that if the equivalent Prolog program -already exists, it will be simply used. The library is based on code -by Joachim Schimpf and on code from SWI-Prolog. - -The following routines are available once included with the -@code{use_module(library(apply_macros))} command. - -@table @code -@item maplist(:@var{Pred}, ?@var{ListIn}, ?@var{ListOut}) -@findex maplist/3 -@snindex maplist/3 -@cnindex maplist/3 - Creates @var{ListOut} by applying the predicate @var{Pred} to all -elements of @var{ListIn}. - -@item maplist(:@var{Pred}, ?@var{ListIn}) -@findex maplist/2 -@snindex maplist/2 -@cnindex maplist/2 - Creates @var{ListOut} by applying the predicate @var{Pred} to all -elements of @var{ListIn}. - -@item maplist(:@var{Pred}, ?@var{L1}, ?@var{L2}, ?@var{L3}) -@findex maplist/4 -@snindex maplist/4 -@cnindex maplist/4 - @var{L1}, @var{L2}, and @var{L3} are such that - @code{call(@var{Pred},@var{A1},@var{A2},@var{A3})} holds for every - corresponding element in lists @var{L1}, @var{L2}, and @var{L3}. - -@item maplist(:@var{Pred}, ?@var{L1}, ?@var{L2}, ?@var{L3}, ?@var{L4}) -@findex maplist/5 -@snindex maplist/5 -@cnindex maplist/5 - @var{L1}, @var{L2}, @var{L3}, and @var{L4} are such that - @code{call(@var{Pred},@var{A1},@var{A2},@var{A3},@var{A4})} holds - for every corresponding element in lists @var{L1}, @var{L2}, @var{L3}, and - @var{L4}. - -@item checklist(:@var{Pred}, +@var{List}) -@findex checklist/2 -@snindex checklist/2 -@cnindex checklist/2 - Succeeds if the predicate @var{Pred} succeeds on all elements of @var{List}. - -@item selectlist(:@var{Pred}, +@var{ListIn}, ?@var{ListOut}) -@findex selectlist/3 -@snindex selectlist/3 -@cnindex selectlist/3 - Creates @var{ListOut} of all list elements of @var{ListIn} that pass a given test - -@item selectlist(:@var{Pred}, +@var{ListIn}, +@var{ListInAux}, ?@var{ListOut}) -@findex selectlist/4 -@snindex selectlist/4 -@cnindex selectlist/4 - Creates @var{ListOut} of all list elements of @var{ListIn} that - pass the given test @var{Pred} using +@var{ListInAux} as an - auxiliary element. - -@item convlist(:@var{Pred}, +@var{ListIn}, ?@var{ListOut}) -@findex convlist/3 -@snindex convlist/3 -@cnindex convlist/3 - A combination of @code{maplist} and @code{selectlist}: creates @var{ListOut} by -applying the predicate @var{Pred} to all list elements on which -@var{Pred} succeeds - -@item sumlist(:@var{Pred}, +@var{List}, ?@var{AccIn}, ?@var{AccOut}) -@findex sumlist/4 -@snindex sumlist/4 -@cnindex sumlist/4 - Calls @var{Pred} on all elements of List and collects a result in -@var{Accumulator}. Same as @code{foldl/4}. - -@item foldl(:@var{Pred}, +@var{List}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldl/4 -@snindex foldl/4 -@cnindex foldl/4 - Calls @var{Pred} on all elements of @code{List} and collects a result in -@var{Accumulator}. - -@item foldl(:@var{Pred}, +@var{List1}, +@var{List2}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldl/5 -@snindex foldl/5 -@cnindex foldl/5 - Calls @var{Pred} on all elements of @code{List1} and -@code{List2} and collects a result in @var{Accumulator}. Same as -@code{foldr/4}. - -@item foldl(:@var{Pred}, +@var{List1}, +@var{List2}, +@var{List3}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldl/6 -@snindex foldl/6 -@cnindex foldl/6 - Calls @var{Pred} on all elements of @code{List1}, @code{List2}, and -@code{List3} and collects a result in @var{Accumulator}. - -@item foldl(:@var{Pred}, +@var{List1}, +@var{List2}, +@var{List3}, +@var{List4}, ?@var{AccIn}, ?@var{AccOut}) -@findex foldl/7 -@snindex foldl/7 -@cnindex foldl/7 - Calls @var{Pred} on all elements of @code{List1}, @code{List2}, @code{List3}, and -@code{List4} and collects a result in @var{Accumulator}. - -@item foldl2(:@var{Pred}, +@var{List}, ?@var{X0}, ?@var{X}, ?@var{Y0}, ?@var{Y}) -@findex foldl2/6 -@snindex foldl2/6 -@cnindex foldl2/6 - Calls @var{Pred} on all elements of @code{List} and collects a result in -@var{X} and @var{Y}. - -@item foldl2(:@var{Pred}, +@var{List}, ?@var{List1}, ?@var{X0}, ?@var{X}, ?@var{Y0}, ?@var{Y}) -@findex foldl2/7 -@snindex foldl2/7 -@cnindex foldl2/7 - Calls @var{Pred} on all elements of @var{List} and @var{List1} and collects a result in -@var{X} and @var{Y}. - -@item foldl2(:@var{Pred}, +@var{List}, ?@var{List1}, ?@var{List2}, ?@var{X0}, ?@var{X}, ?@var{Y0}, ?@var{Y}) -@findex foldl2/8 -@snindex foldl2/8 -@cnindex foldl2/8 - Calls @var{Pred} on all elements of @var{List}, @var{List1} and @var{List2} and collects a result in -@var{X} and @var{Y}. - -@item foldl3(:@var{Pred}, +@var{List1}, ?@var{List2}, ?@var{X0}, ?@var{X}, ?@var{Y0}, ?@var{Y}, ?@var{Z0}, ?@var{Z}) - -@findex foldl3/6 -@snindex foldl3/6 -@cnindex foldl3/6 - Calls @var{Pred} on all elements of @code{List} and collects a -result in @var{X}, @var{Y} and @var{Z}. - -@item foldl4(:@var{Pred}, +@var{List1}, ?@var{List2}, ?@var{X0}, ?@var{X}, ?@var{Y0}, ?@var{Y}, ?@var{Z0}, ?@var{Z}, ?@var{W0}, ?@var{W}) - -@findex foldl4/8 -@snindex foldl4/8 -@cnindex foldl4/8 - Calls @var{Pred} on all elements of @code{List} and collects a -result in @var{X}, @var{Y}, @var{Z} and @var{W}. - -@item scanl(:@var{Pred}, +@var{List}, +@var{V0}, ?@var{Values}) -@findex scanl/4 -@snindex scanl/4 -@cnindex scanl/4 - Left scan of list. The scanl family of higher order list - operations is defined by: - -@pl_example - scanl(P, [X11,...,X1n], ..., [Xm1,...,Xmn], V0, [V0,V1,...,Vn]) :- - P(X11, ..., Xm1, V0, V1), - ... - P(X1n, ..., Xmn, Vn-1, Vn). -@end pl_example - - -@item scanl(:@var{Pred}, +@var{List1}, +@var{List2}, ?@var{V0}, ?@var{Vs}) -@findex scanl/5 -@snindex scanl/5 -@cnindex scanl/5 - Left scan of list. - -@item scanl(:@var{Pred}, +@var{List1}, +@var{List2}, +@var{List3}, ?@var{V0}, ?@var{Vs}) -@findex scanl/6 -@snindex scanl/6 -@cnindex scanl/6 - Left scan of list. - -@item scanl(:@var{Pred}, +@var{List1}, +@var{List2}, +@var{List3}, +@var{List4}, ?@var{V0}, ?@var{Vs}) -@findex scanl/7 -@snindex scanl/7 -@cnindex scanl/7 - Left scan of list. - -@item mapnodes(+@var{Pred}, +@var{TermIn}, ?@var{TermOut}) -@findex mapnodes/3 -@snindex mapnodes/3 -@cnindex mapnodes/3 - Creates @var{TermOut} by applying the predicate @var{Pred} - to all sub-terms of @var{TermIn} (depth-first and left-to-right order) - -@item checknodes(+@var{Pred}, +@var{Term}) -@findex checknodes/3 -@snindex checknodes/3 -@cnindex checknodes/3 - Succeeds if the predicate @var{Pred} succeeds on all sub-terms of - @var{Term} (depth-first and left-to-right order) - -@item sumnodes(+@var{Pred}, +@var{Term}, ?@var{AccIn}, ?@var{AccOut}) -@findex sumnodes/4 -@snindex sumnodes/4 -@cnindex sumnodes/4 - Calls the predicate @var{Pred} on all sub-terms of @var{Term} and -collect a result in @var{Accumulator} (depth-first and left-to-right -order) - -@item include(+@var{Pred}, +@var{ListIn}, ?@var{ListOut}) -@findex include/3 -@snindex include/3 -@cnindex include/3 - Same as @code{selectlist/3}. - -@item exclude(+@var{Goal}, +@var{List1}, ?@var{List2}) -@findex exclude/3 -@snindex exclude/3 -@cnindex exclude/3 -Filter elements for which @var{Goal} fails. True if @var{List2} contains - those elements @var{Xi} of @var{List1} for which @code{call(Goal, Xi)} fails. - -@item partition(+@var{Pred}, +@var{List1}, ?@var{Included}, ?@var{Excluded}) -@findex partition/4 -@snindex partition/4 -@cnindex partition/4 -Filter elements of @var{List} according to @var{Pred}. True if -@var{Included} contains all elements for which @code{call(Pred, X)} -succeeds and @var{Excluded} contains the remaining elements. - -@item partition(+@var{Pred}, +@var{List1}, ?@var{Lesser}, ?@var{Equal}, ?@var{Greater}) -@findex partition/5 -@snindex partition/5 -@cnindex partition/5 -Filter list according to @var{Pred} in three sets. For each element -@var{Xi} of @var{List}, its destination is determined by -@code{call(Pred, Xi, Place)}, where @var{Place} must be unified to one -of @code{<}, @code{=} or @code{>}. @code{Pred} must be deterministic. - -@end table - -Examples: - -@pl_example -%given -plus(X,Y,Z) :- Z is X + Y. -plus_if_pos(X,Y,Z) :- Y > 0, Z is X + Y. -vars(X, Y, [X|Y]) :- var(X), !. -vars(_, Y, Y). -trans(TermIn, TermOut) :- - nonvar(TermIn), - TermIn =.. [p|Args], - TermOut =..[q|Args], !. -trans(X,X). - -%success - -maplist(plus(1), [1,2,3,4], [2,3,4,5]). -checklist(var, [X,Y,Z]). -selectlist(<(0), [-1,0,1], [1]). -convlist(plus_if_pos(1), [-1,0,1], [2]). -sumlist(plus, [1,2,3,4], 1, 11). -mapargs(number_atom,s(1,2,3), s('1','2','3')). -sumargs(vars, s(1,X,2,Y), [], [Y,X]).m -apnodes(trans, p(a,p(b,a),c), q(a,q(b,a),c)). -checknodes(\==(T), p(X,p(Y,X),Z)). -sumnodes(vars, [c(X), p(X,Y), q(Y)], [], [Y,Y,X,X]). -% another one -maplist(mapargs(number_atom),[c(1),s(1,2,3)],[c('1'),s('1','2','3')]). -@end pl_example - -@end texinfo - - -@node matrix, MATLAB, MapList, Library -@section Matrix Library -@cindex Matrix Library - -This package provides a fast implementation of multi-dimensional -matrices of integers and floats. In contrast to dynamic arrays, these -matrices are multi-dimensional and compact. In contrast to static -arrays. these arrays are allocated in the stack. Matrices are available -by loading the library @code{library(matrix)}. They are multimensional -objects of type: -@itemize -@item @t{terms}: Prolog terms -@item @t{ints}: bounded integers, represented as an opaque term. The -maximum integer depends on hardware, but should be obtained from the -natural size of the machine. -@item @t{floats}: floating-poiny numbers, represented as an opaque term. -@end itemize - -Matrix elements can be accessed through the @code{matrix_get/2} -predicate or through an @t{R}-inspired access notation (that uses the ciao -style extension to @code{[]}. Examples include: - -@table @code -@item @var{E} <== @var{X}[2,3] -Access the second row, third column of matrix @t{X}. Indices start from -@code{0}, -@item @var{L} <== @var{X}[2,_] -Access all the second row, the output is a list ofe elements. -@item @var{L} <== @var{X}[2..4,_] -Access all the second, thrd and fourth rows, the output is a list of elements. -@item @var{L} <== @var{X}[2..4+3,_] -Access all the fifth, sixth and eight rows, the output is a list of elements. -@end table - -The matrix library also supports a B-Prolog/ECliPSe inspired @code{foreach} ITerator to iterate over -elements of a matrix: - -@table @code -@item foreach(I in 0..N1, X[I] <== Y[I]) -Copies a vector, element by element. -@item foreach([I in 0..N1, J in I..N1], Z[I,J] <== X[I,J] - X[I,J]) -The lower-triangular matrix @var{Z} is the difference between the -lower-triangular and upper-triangular parts of @var{X}. -@item foreach([I in 0..N1, J in 0..N1], plus(X[I,J]), 0, Sum) -Add all elements of a matrix by using @var{Sum} as an accumulator. -@end table - -Notice that the library does not support all known matrix operations. Please -contact the YAP maintainers if you require extra functionality. - -@table @code - -@item @var{X} = array[@var{Dim1},...,@var{Dimn}] of @var{Objects} -@findex of/2 -@snindex of/2 -@cnindex of/2 -The @code{of/2} operator can be used to create a new array of -@var{Objects}. The objects supported are: - -@table @code -@item Unbound Variable -create an array of free variables -@item ints -create an array of integers -@item floats -create an array of floating-point numbers -@item @var{I}:@var{J} -create an array with integers from @var{I} to @var{J} -@item [..] -create an array from the values in a list - @end table - -The dimensions can be given as an integer, and the matrix will be -indexed @code{C}-style from @code{0..(@var{Max}-1)}, or can be given -as an interval @code{@var{Base}..@var{Limit}}. In the latter case, -matrices of integers and of floating-point numbers should have the same -@var{Base} on every dimension. - -@item ?@var{LHS} <== @var{RHS} -@findex <==/2 -@snindex <==/2 -@cnindex <==/2 -General matrix assignment operation. It evaluates the right-hand side -and then acts different according to the -left-hand side and to the matrix: -@itemize @bullet -@item if @var{LHS} is part of an integer or floating-point matrix, -perform non-backtrackable assignment. -@item other unify left-hand side and right-hand size. -@end itemize - -The right-hand side supports the following operators: -@table @code -@item []/2 -written as @var{M}[@var{Offset}]: obtain an element or list of elements -of matrix @var{M} at offset @var{Offset}. -@item matrix/1 -create a vector from a list -@item matrix/2 -create a matrix from a list. Oprions are: -@table @code -@item dim= -a list of dimensiona -@item type= -integers, floating-point or terms -@item base= -a list of base offsets per dimension (all must be the same for arrays of -integers and floating-points -@end table -@item matrix/3 -create matrix giving two options -@item dim/1 -list with matrix dimensions -@item nrow/1 -number of rows in bi-dimensional matrix -@item ncol/1 -number of columns in bi-dimensional matrix -@item length/1 -size of a matrix -@item size/1 -size of a matrix -@item max/1 -maximum element of a numeric matrix -@item maxarg/1 -argument of maximum element of a numeric matrix -@item min/1 -minimum element of a numeric matrix -@item minarg/1 -argument of minimum element of a numeric matrix -@item list/1 -represent matrix as a list -@item lists/2 -represent matrix as list of embedded lists -@item ../2 -@var{I}..@var{J} generates a list with all integers from @var{I} to -@var{J}, included. -@item +/2 -add two numbers, add two matrices element-by-element, or add a number to -all elements of a matrix or list -@item -/2 -subtract two numbers, subtract two matrices or lists element-by-element, or subtract a number from -all elements of a matrix or list -@item * /2 -multiply two numbers, multiply two matrices or lists element-by-element, or multiply a number from -all elements of a matrix or list -@item log/1 -natural logarithm of a number, matrix or list -@item exp/1 -natural exponentiation of a number, matrix or list -@end table - -@item foreach(@var{Sequence}, @var{Goal}) -@findex foreach_matrix/2 -@snindex foreach_matrix/2 -@cnindex foreach_matrix/2 -Deterministic iterator. The ranges are given by @var{Sequence} that is -either @code{@var{I} in @var{M}..@var{N}}, or of the form -@code{[@var{I},@var{J}] ins @var{M}..@var{N}}, or a list of the above conditions. - -Variables in the goal are assumed to be global, ie, share a single value -in the execution. The exceptions are the iteration indices. Moreover, if -the goal is of the form @code{@var{Locals}^@var{G}} all variables -occurring in @var{Locals} are marked as local. As an example: -@pl_example -foreach([I,J] ins 1..N, A^(A <==M[I,J], N[I] <== N[I] + A*A) ) -@end pl_example -the variables @var{I}, @var{J} and @var{A} are duplicated for every -call (local), whereas the matrices @var{M} and @var{N} are shared -throughout the execution (global). - -@item foreach(@var{Sequence}, @var{Goal}, @var{Acc0}, @var{AccF}) -@findex foreach/4 -@snindex foreach/4 -@cnindex foreach/4 -Deterministic iterator with accumulator style arguments. - -@item matrix_new(+@var{Type},+@var{Dims},-@var{Matrix}) -@findex matrix_new/3 -@snindex matrix_new/3 -@cnindex matrix_new/3 - -Create a new matrix @var{Matrix} of type @var{Type}, which may be one of -@code{ints} or @code{floats}, and with a list of dimensions @var{Dims}. -The matrix will be initialised to zeros. - -@example -?- matrix_new(ints,[2,3],Matrix). - -Matrix = @{..@} -@end example -Notice that currently YAP will always write a matrix of numbers as @code{@{..@}}. - -@item matrix_new(+@var{Type},+@var{Dims},+@var{List},-@var{Matrix}) -@findex matrix_new/4 -@snindex matrix_new/4 -@cnindex matrix_new/4 - -Create a new matrix @var{Matrix} of type @var{Type}, which may be one of -@code{ints} or @code{floats}, with dimensions @var{Dims}, and -initialised from list @var{List}. - -@item matrix_new_set(?@var{Dims},+@var{OldMatrix},+@var{Value},-@var{NewMatrix}) -@findex matrix_new_set/4 -@snindex matrix_new_set/4 -@cnindex matrix_new_set/4 - -Create a new matrix @var{NewMatrix} of type @var{Type}, with dimensions -@var{Dims}. The elements of @var{NewMatrix} are set to @var{Value}. - -@item matrix_dims(+@var{Matrix},-@var{Dims}) -@findex matrix_dims/2 -@snindex matrix_dims/2 -@cnindex matrix_dims/2 - -Unify @var{Dims} with a list of dimensions for @var{Matrix}. - -@item matrix_ndims(+@var{Matrix},-@var{Dims}) -@findex matrix_ndims/2 -@snindex matrix_ndims/2 -@cnindex matrix_ndims/2 - -Unify @var{NDims} with the number of dimensions for @var{Matrix}. - -@item matrix_size(+@var{Matrix},-@var{NElems}) -@findex matrix_size/2 -@snindex matrix_size/2 -@cnindex matrix_size/2 - -Unify @var{NElems} with the number of elements for @var{Matrix}. - -@item matrix_type(+@var{Matrix},-@var{Type}) -@findex matrix_type/2 -@snindex matrix_type/2 -@cnindex matrix_type/2 - -Unify @var{NElems} with the type of the elements in @var{Matrix}. - -@item matrix_to_list(+@var{Matrix},-@var{Elems}) -@findex matrix_to_list/2 -@snindex matrix_to_list/2 -@cnindex matrix_to_list/2 - -Unify @var{Elems} with the list including all the elements in @var{Matrix}. - -@item matrix_get(+@var{Matrix},+@var{Position},-@var{Elem}) -@findex matrix_get/3 -@snindex matrix_get/3 -@cnindex matrix_get/3 - -Unify @var{Elem} with the element of @var{Matrix} at position -@var{Position}. - -@item matrix_get(+@var{Matrix}[+@var{Position}],-@var{Elem}) -@findex matrix_get/2 -@snindex matrix_get/2 -@cnindex matrix_get/2 - -Unify @var{Elem} with the element @var{Matrix}[@var{Position}]. - -@item matrix_set(+@var{Matrix},+@var{Position},+@var{Elem}) -@findex matrix_set/3 -@snindex matrix_set/3 -@cnindex matrix_set/3 - -Set the element of @var{Matrix} at position -@var{Position} to @var{Elem}. - -@item matrix_set(+@var{Matrix}[+@var{Position}],+@var{Elem}) -@findex matrix_set/2 -@snindex matrix_set/2 -@cnindex matrix_set/2 - -Set the element of @var{Matrix}[@var{Position}] to @var{Elem}. - -@item matrix_set_all(+@var{Matrix},+@var{Elem}) -@findex matrix_set_all/2 -@snindex matrix_set_all/2 -@cnindex matrix_set_all/2 - -Set all element of @var{Matrix} to @var{Elem}. - -@item matrix_add(+@var{Matrix},+@var{Position},+@var{Operand}) -@findex matrix_add/3 -@snindex matrix_add/3 -@cnindex matrix_add/3 - -Add @var{Operand} to the element of @var{Matrix} at position -@var{Position}. - -@item matrix_inc(+@var{Matrix},+@var{Position}) -@findex matrix_inc/2 -@snindex matrix_inc/2 -@cnindex matrix_inc/2 - -Increment the element of @var{Matrix} at position @var{Position}. - -@item matrix_inc(+@var{Matrix},+@var{Position},-@var{Element}) -@findex matrix_inc/3 -@snindex matrix_inc/3 -@cnindex matrix_inc/3 - -Increment the element of @var{Matrix} at position @var{Position} and -unify with @var{Element}. - -@item matrix_dec(+@var{Matrix},+@var{Position}) -@findex matrix_dec/2 -@snindex matrix_dec/2 -@cnindex matrix_dec/2 - -Decrement the element of @var{Matrix} at position @var{Position}. - -@item matrix_dec(+@var{Matrix},+@var{Position},-@var{Element}) -@findex matrix_dec/3 -@snindex matrix_dec/3 -@cnindex matrix_dec/3 - -Decrement the element of @var{Matrix} at position @var{Position} and -unify with @var{Element}. - -@item matrix_arg_to_offset(+@var{Matrix},+@var{Position},-@var{Offset}) -@findex matrix_arg_to_offset/3 -@snindex matrix_arg_to_offset/3 -@cnindex matrix_arg_to_offset/3 - -Given matrix @var{Matrix} return what is the numerical @var{Offset} of -the element at @var{Position}. - -@item matrix_offset_to_arg(+@var{Matrix},-@var{Offset},+@var{Position}) -@findex matrix_offset_to_arg/3 -@snindex matrix_offset_to_arg/3 -@cnindex matrix_offset_to_arg/3 - -Given a position @var{Position } for matrix @var{Matrix} return the -corresponding numerical @var{Offset} from the beginning of the matrix. - -@item matrix_max(+@var{Matrix},+@var{Max}) -@findex matrix_max/2 -@snindex matrix_max/2 -@cnindex matrix_max/2 - -Unify @var{Max} with the maximum in matrix @var{Matrix}. - -@item matrix_maxarg(+@var{Matrix},+@var{Maxarg}) -@findex matrix_maxarg/2 -@snindex matrix_maxarg/2 -@cnindex matrix_maxarg/2 - -Unify @var{Max} with the position of the maximum in matrix @var{Matrix}. - -@item matrix_min(+@var{Matrix},+@var{Min}) -@findex matrix_min/2 -@snindex matrix_min/2 -@cnindex matrix_min/2 - -Unify @var{Min} with the minimum in matrix @var{Matrix}. - -@item matrix_minarg(+@var{Matrix},+@var{Minarg}) -@findex matrix_minarg/2 -@snindex matrix_minarg/2 -@cnindex matrix_minarg/2 - -Unify @var{Min} with the position of the minimum in matrix @var{Matrix}. - -@item matrix_sum(+@var{Matrix},+@var{Sum}) -@findex matrix_sum/2 -@snindex matrix_sum/2 -@cnindex matrix_sum/2 - -Unify @var{Sum} with the sum of all elements in matrix @var{Matrix}. - -@c @item matrix_add_to_all(+@var{Matrix},+@var{Element}) -@c @findex matrix_add_to_all/2 -@c @snindex matrix_add_to_all/2 -@c @cnindex matrix_add_to_all/2 - -@c Add @var{Element} to all elements of matrix @var{Matrix}. - -@item matrix_agg_lines(+@var{Matrix},+@var{Aggregate}) -@findex matrix_agg_lines/2 -@snindex matrix_agg_lines/2 -@cnindex matrix_agg_lines/2 - -If @var{Matrix} is a n-dimensional matrix, unify @var{Aggregate} with -the n-1 dimensional matrix where each element is obtained by adding all -Matrix elements with same last n-1 index. - -@item matrix_agg_cols(+@var{Matrix},+@var{Aggregate}) -@findex matrix_agg_cols/2 -@snindex matrix_agg_cols/2 -@cnindex matrix_agg_cols/2 - -If @var{Matrix} is a n-dimensional matrix, unify @var{Aggregate} with -the one dimensional matrix where each element is obtained by adding all -Matrix elements with same first index. - -@item matrix_op(+@var{Matrix1},+@var{Matrix2},+@var{Op},-@var{Result}) -@findex matrix_op/4 -@snindex matrix_op/4 -@cnindex matrix_op/4 - -@var{Result} is the result of applying @var{Op} to matrix @var{Matrix1} -and @var{Matrix2}. Currently, only addition (@code{+}) is supported. - -@item matrix_op_to_all(+@var{Matrix1},+@var{Op},+@var{Operand},-@var{Result}) -@findex matrix_op_to_all/4 -@snindex matrix_op_to_all/4 -@cnindex matrix_op_to_all/4 - -@var{Result} is the result of applying @var{Op} to all elements of -@var{Matrix1}, with @var{Operand} as the second argument. Currently, -only addition (@code{+}), multiplication (@code{*}), and division -(@code{/}) are supported. - -@item matrix_op_to_lines(+@var{Matrix1},+@var{Lines},+@var{Op},-@var{Result}) -@findex matrix_op_to_lines/4 -@snindex matrix_op_to_lines/4 -@cnindex matrix_op_to_lines/4 - -@var{Result} is the result of applying @var{Op} to all elements of -@var{Matrix1}, with the corresponding element in @var{Lines} as the -second argument. Currently, only division (@code{/}) is supported. - -@item matrix_op_to_cols(+@var{Matrix1},+@var{Cols},+@var{Op},-@var{Result}) -@findex matrix_op_to_cols/4 -@snindex matrix_op_to_cols/4 -@cnindex matrix_op_to_cols/4 - -@var{Result} is the result of applying @var{Op} to all elements of -@var{Matrix1}, with the corresponding element in @var{Cols} as the -second argument. Currently, only addition (@code{+}) is -supported. Notice that @var{Cols} will have n-1 dimensions. - -@item matrix_shuffle(+@var{Matrix},+@var{NewOrder},-@var{Shuffle}) -@findex matrix_shuffle/3 -@snindex matrix_shuffle/3 -@cnindex matrix_shuffle/3 - -Shuffle the dimensions of matrix @var{Matrix} according to -@var{NewOrder}. The list @var{NewOrder} must have all the dimensions of -@var{Matrix}, starting from 0. - -@item matrix_transpose(+@var{Matrix},-@var{Transpose}) -@findex matrix_reorder/3 -@snindex matrix_reorder/3 -@cnindex matrix_reorder/3 - -Transpose matrix @var{Matrix} to @var{Transpose}. Equivalent to: -@example -matrix_transpose(Matrix,Transpose) :- - matrix_shuffle(Matrix,[1,0],Transpose). -@end example - -@item matrix_expand(+@var{Matrix},+@var{NewDimensions},-@var{New}) -@findex matrix_expand/3 -@snindex matrix_expand/3 -@cnindex matrix_expand/3 - -Expand @var{Matrix} to occupy new dimensions. The elements in -@var{NewDimensions} are either 0, for an existing dimension, or a -positive integer with the size of the new dimension. - -@item matrix_select(+@var{Matrix},+@var{Dimension},+@var{Index},-@var{New}) -@findex matrix_select/4 -@snindex matrix_select/4 -@cnindex matrix_select/4 - -Select from @var{Matrix} the elements who have @var{Index} at -@var{Dimension}. - -@item matrix_row(+@var{Matrix},+@var{Column},-@var{NewMatrix}) -@findex matrix_row/3 -@snindex matrix_row/3 -@cnindex matrix_row/3 - -Select from @var{Matrix} the row matching @var{Column} as new matrix @var{NewMatrix}. @var{Column} must have one less dimension than the original matrix. -@var{Dimension}. - -@end table - -@node MATLAB, Non-Backtrackable Data Structures, matrix, Library -@section MATLAB Package Interface -@cindex Matlab Interface - -The MathWorks MATLAB is a widely used package for array -processing. YAP now includes a straightforward interface to MATLAB. To -actually use it, you need to install YAP calling @code{configure} with -the @code{--with-matlab=DIR} option, and you need to call -@code{use_module(library(lists))} command. - -Accessing the matlab dynamic libraries can be complicated. In Linux -machines, to use this interface, you may have to set the environment -variable @t{LD_LIBRARY_PATH}. Next, follows an example using bash in a -64-bit Linux PC: -@example -export LD_LIBRARY_PATH=''$MATLAB_HOME"/sys/os/glnxa64:''$MATLAB_HOME"/bin/glnxa64:''$LD_LIBRARY_PATH" -@end example -where @code{MATLAB_HOME} is the directory where matlab is installed -at. Please replace @code{ax64} for @code{x86} on a 32-bit PC. - -@table @code - -@item start_matlab(+@var{Options}) -@findex start_matlab/1 -@snindex start_matlab/1 -@cnindex start_matlab/1 -Start a matlab session. The argument @var{Options} may either be the -empty string/atom or the command to call matlab. The command may fail. - -@item close_matlab -@findex close_matlab/0 -@snindex close_matlab/0 -@cnindex close_matlab/0 -Stop the current matlab session. - -@item matlab_on -@findex matlab_on/0 -@snindex matlab_on/0 -@cnindex matlab_on/0 -Holds if a matlab session is on. - -@item matlab_eval_string(+@var{Command}) -@findex matlab_eval_string/1 -@snindex matlab_eval_string/1 -@cnindex matlab_eval_string/1 -Holds if matlab evaluated successfully the command @var{Command}. - -@item matlab_eval_string(+@var{Command}, -@var{Answer}) -@findex matlab_eval_string/2 -@snindex matlab_eval_string/2 -@cnindex matlab_eval_string/2 -MATLAB will evaluate the command @var{Command} and unify @var{Answer} -with a string reporting the result. - - -@item matlab_cells(+@var{Size}, ?@var{Array}) -@findex matlab_cells/2 -@snindex matlab_cells/2 -@cnindex matlab_cells/2 -MATLAB will create an empty vector of cells of size @var{Size}, and if -@var{Array} is bound to an atom, store the array in the matlab -variable with name @var{Array}. Corresponds to the MATLAB command @code{cells}. - - -@item matlab_cells(+@var{SizeX}, +@var{SizeY}, ?@var{Array}) -@findex matlab_cells/3 -@snindex matlab_cells/3 -@cnindex matlab_cells/3 -MATLAB will create an empty array of cells of size @var{SizeX} and -@var{SizeY}, and if @var{Array} is bound to an atom, store the array -in the matlab variable with name @var{Array}. Corresponds to the -MATLAB command @code{cells}. - -@item matlab_initialized_cells(+@var{SizeX}, +@var{SizeY}, +@var{List}, ?@var{Array}) -@findex matlab_initialized_cells/4 -@snindex matlab_initialized_cells/4 -@cnindex matlab_initialized_cells/4 -MATLAB will create an array of cells of size @var{SizeX} and -@var{SizeY}, initialized from the list @var{List}, and if @var{Array} -is bound to an atom, store the array in the matlab variable with name -@var{Array}. - -@item matlab_matrix(+@var{SizeX}, +@var{SizeY}, +@var{List}, ?@var{Array}) -@findex matlab_matrix/4 -@snindex matlab_matrix/4 -@cnindex matlab_matrix/4 -MATLAB will create an array of floats of size @var{SizeX} and @var{SizeY}, -initialized from the list @var{List}, and if @var{Array} is bound to -an atom, store the array in the matlab variable with name @var{Array}. - -@item matlab_set(+@var{MatVar}, +@var{X}, +@var{Y}, +@var{Value}) -@findex matlab_set/4 -@snindex matlab_set/4 -@cnindex matlab_set/4 -Call MATLAB to set element @var{MatVar}(@var{X}, @var{Y}) to -@var{Value}. Notice that this command uses the MATLAB array access -convention. - -@item matlab_get_variable(+@var{MatVar}, -@var{List}) -@findex matlab_get_variable/2 -@snindex matlab_get_variable/2 -@cnindex matlab_get_variable/2 -Unify MATLAB variable @var{MatVar} with the List @var{List}. - -@item matlab_item(+@var{MatVar}, +@var{X}, ?@var{Val}) -@findex matlab_item/3 -@snindex matlab_item/3 -@cnindex matlab_item/3 -Read or set MATLAB @var{MatVar}(@var{X}) from/to @var{Val}. Use -@code{C} notation for matrix access (ie, starting from 0). - -@item matlab_item(+@var{MatVar}, +@var{X}, +@var{Y}, ?@var{Val}) -@findex matlab_item/4 -@snindex matlab_item/4 -@cnindex matlab_item/4 -Read or set MATLAB @var{MatVar}(@var{X},@var{Y}) from/to @var{Val}. Use -@code{C} notation for matrix access (ie, starting from 0). - -@item matlab_item1(+@var{MatVar}, +@var{X}, ?@var{Val}) -@findex matlab_item1/3 -@snindex matlab_item1/3 -@cnindex matlab_item1/3 -Read or set MATLAB @var{MatVar}(@var{X}) from/to @var{Val}. Use -MATLAB notation for matrix access (ie, starting from 1). - -@item matlab_item1(+@var{MatVar}, +@var{X}, +@var{Y}, ?@var{Val}) -@findex matlab_item1/4 -@snindex matlab_item1/4 -@cnindex matlab_item1/4 -Read or set MATLAB @var{MatVar}(@var{X},@var{Y}) from/to @var{Val}. Use -MATLAB notation for matrix access (ie, starting from 1). - -@item matlab_sequence(+@var{Min}, +@var{Max}, ?@var{Array}) -@findex matlab_sequence/3 -@snindex matlab_sequence/3 -@cnindex matlab_sequence/3 -MATLAB will create a sequence going from @var{Min} to @var{Max}, and -if @var{Array} is bound to an atom, store the sequence in the matlab -variable with name @var{Array}. - -@item matlab_vector(+@var{Size}, +@var{List}, ?@var{Array}) -@findex matlab_vector/4 -@snindex matlab_vector/4 -@cnindex matlab_vector/4 -MATLAB will create a vector of floats of size @var{Size}, initialized -from the list @var{List}, and if @var{Array} is bound to an atom, -store the array in the matlab variable with name @var{Array}. - -@item matlab_zeros(+@var{Size}, ?@var{Array}) -@findex matlab_zeros/2 -@snindex matlab_zeros/2 -@cnindex matlab_zeros/2 -MATLAB will create a vector of zeros of size @var{Size}, and if -@var{Array} is bound to an atom, store the array in the matlab -variable with name @var{Array}. Corresponds to the MATLAB command -@code{zeros}. - -@item matlab_zeros(+@var{SizeX}, +@var{SizeY}, ?@var{Array}) -@findex matlab_zeros/3 -@snindex matlab_zeros/3 -@cnindex matlab_zeros/3 -MATLAB will create an array of zeros of size @var{SizeX} and -@var{SizeY}, and if @var{Array} is bound to an atom, store the array -in the matlab variable with name @var{Array}. Corresponds to the -MATLAB command @code{zeros}. - - -@item matlab_zeros(+@var{SizeX}, +@var{SizeY}, +@var{SizeZ}, ?@var{Array}) -@findex matlab_zeros/4 -@snindex matlab_zeros/4 -@cnindex matlab_zeros/4 -MATLAB will create an array of zeros of size @var{SizeX}, @var{SizeY}, -and @var{SizeZ}. If @var{Array} is bound to an atom, store the array -in the matlab variable with name @var{Array}. Corresponds to the -MATLAB command @code{zeros}. - - - - -@end table - -@node Non-Backtrackable Data Structures, Ordered Sets, MATLAB, Library -@section Non-Backtrackable Data Structures - -The following routines implement well-known data-structures using global -non-backtrackable variables (implemented on the Prolog stack). The -data-structures currently supported are Queues, Heaps, and Beam for Beam -search. They are allowed through @code{library(nb)}. - -@table @code -@item nb_queue(-@var{Queue}) -@findex nb_queue/1 -@snindex nb_queue/1 -@cnindex nb_queue/1 -Create a @var{Queue}. - -@item nb_queue_close(+@var{Queue}, -@var{Head}, ?@var{Tail}) -@findex nb_queue_close/3 -@snindex nb_queue_close/3 -@cnindex nb_queue_close/3 -Unify the queue @var{Queue} with a difference list -@var{Head}-@var{Tail}. The queue will now be empty and no further -elements can be added. - -@item nb_queue_enqueue(+@var{Queue}, +@var{Element}) -@findex nb_queue_enqueue/2 -@snindex nb_queue_enqueue/2 -@cnindex nb_queue_enqueue/2 -Add @var{Element} to the front of the queue @var{Queue}. - -@item nb_queue_dequeue(+@var{Queue}, -@var{Element}) -@findex nb_queue_dequeue/2 -@snindex nb_queue_dequeue/2 -@cnindex nb_queue_dequeue/2 -Remove @var{Element} from the front of the queue @var{Queue}. Fail if -the queue is empty. - -@item nb_queue_peek(+@var{Queue}, -@var{Element}) -@findex nb_queue_peek/2 -@snindex nb_queue_peek/2 -@cnindex nb_queue_peek/2 -@var{Element} is the front of the queue @var{Queue}. Fail if -the queue is empty. - -@item nb_queue_size(+@var{Queue}, -@var{Size}) -@findex nb_queue_size/2 -@snindex nb_queue_size/2 -@cnindex nb_queue_size/2 -Unify @var{Size} with the number of elements in the queue @var{Queue}. - -@item nb_queue_empty(+@var{Queue}) -@findex nb_queue_empty/1 -@snindex nb_queue_empty/1 -@cnindex nb_queue_empty/1 -Succeeds if @var{Queue} is empty. - -@item nb_heap(+@var{DefaultSize},-@var{Heap}) -@findex nb_heap/1 -@snindex nb_heap/1 -@cnindex nb_heap/1 -Create a @var{Heap} with default size @var{DefaultSize}. Note that size -will expand as needed. - -@item nb_heap_close(+@var{Heap}) -@findex nb_heap_close/1 -@snindex nb_heap_close/1 -@cnindex nb_heap_close/1 -Close the heap @var{Heap}: no further elements can be added. - -@item nb_heap_add(+@var{Heap}, +@var{Key}, +@var{Value}) -@findex nb_heap_add/3 -@snindex nb_heap_add/3 -@cnindex nb_heap_add/3 -Add @var{Key}-@var{Value} to the heap @var{Heap}. The key is sorted on -@var{Key} only. - -@item nb_heap_del(+@var{Heap}, -@var{Key}, -@var{Value}) -@findex nb_heap_del/3 -@snindex nb_heap_del/3 -@cnindex nb_heap_del/3 -Remove element @var{Key}-@var{Value} with smallest @var{Value} in heap -@var{Heap}. Fail if the heap is empty. - -@item nb_heap_peek(+@var{Heap}, -@var{Key}, -@var{Value})) -@findex nb_heap_peek/3 -@snindex nb_heap_peek/3 -@cnindex nb_heap_peek/3 -@var{Key}-@var{Value} is the element with smallest @var{Key} in the heap -@var{Heap}. Fail if the heap is empty. - -@item nb_heap_size(+@var{Heap}, -@var{Size}) -@findex nb_heap_size/2 -@snindex nb_heap_size/2 -@cnindex nb_heap_size/2 -Unify @var{Size} with the number of elements in the heap @var{Heap}. - -@item nb_heap_empty(+@var{Heap}) -@findex nb_heap_empty/1 -@snindex nb_heap_empty/1 -@cnindex nb_heap_empty/1 -Succeeds if @var{Heap} is empty. - -@item nb_beam(+@var{DefaultSize},-@var{Beam}) -@findex nb_beam/1 -@snindex nb_beam/1 -@cnindex nb_beam/1 -Create a @var{Beam} with default size @var{DefaultSize}. Note that size -is fixed throughout. - -@item nb_beam_close(+@var{Beam}) -@findex nb_beam_close/1 -@snindex nb_beam_close/1 -@cnindex nb_beam_close/1 -Close the beam @var{Beam}: no further elements can be added. - -@item nb_beam_add(+@var{Beam}, +@var{Key}, +@var{Value}) -@findex nb_beam_add/3 -@snindex nb_beam_add/3 -@cnindex nb_beam_add/3 -Add @var{Key}-@var{Value} to the beam @var{Beam}. The key is sorted on -@var{Key} only. - -@item nb_beam_del(+@var{Beam}, -@var{Key}, -@var{Value}) -@findex nb_beam_del/3 -@snindex nb_beam_del/3 -@cnindex nb_beam_del/3 -Remove element @var{Key}-@var{Value} with smallest @var{Value} in beam -@var{Beam}. Fail if the beam is empty. - -@item nb_beam_peek(+@var{Beam}, -@var{Key}, -@var{Value})) -@findex nb_beam_peek/3 -@snindex nb_beam_peek/3 -@cnindex nb_beam_peek/3 -@var{Key}-@var{Value} is the element with smallest @var{Key} in the beam -@var{Beam}. Fail if the beam is empty. - -@item nb_beam_size(+@var{Beam}, -@var{Size}) -@findex nb_beam_size/2 -@snindex nb_beam_size/2 -@cnindex nb_beam_size/2 -Unify @var{Size} with the number of elements in the beam @var{Beam}. - -@item nb_beam_empty(+@var{Beam}) -@findex nb_beam_empty/1 -@snindex nb_beam_empty/1 -@cnindex nb_beam_empty/1 -Succeeds if @var{Beam} is empty. - -@end table - - -@node Ordered Sets, Pseudo Random, Non-Backtrackable Data Structures, Library -@section Ordered Sets -@cindex ordered set - -The following ordered set manipulation routines are available once -included with the @code{use_module(library(ordsets))} command. An -ordered set is represented by a list having unique and ordered -elements. Output arguments are guaranteed to be ordered sets, if the -relevant inputs are. This is a slightly patched version of Richard -O'Keefe's original library. - -@table @code -@item list_to_ord_set(+@var{List}, ?@var{Set}) -@findex list_to_ord_set/2 -@syindex list_to_ord_set/2 -@cnindex list_to_ord_set/2 -Holds when @var{Set} is the ordered representation of the set -represented by the unordered representation @var{List}. - -@item merge(+@var{List1}, +@var{List2}, -@var{Merged}) -@findex merge/3 -@syindex merge/3 -@cnindex merge/3 -Holds when @var{Merged} is the stable merge of the two given lists. - -Notice that @code{merge/3} will not remove duplicates, so merging -ordered sets will not necessarily result in an ordered set. Use -@code{ord_union/3} instead. - -@item ord_add_element(+@var{Set1}, +@var{Element}, ?@var{Set2}) -@findex ord_add_element/3 -@syindex ord_add_element/3 -@cnindex ord_add_element/3 -Inserting @var{Element} in @var{Set1} returns @var{Set2}. It should give -exactly the same result as @code{merge(Set1, [Element], Set2)}, but a -bit faster, and certainly more clearly. The same as @code{ord_insert/3}. - -@item ord_del_element(+@var{Set1}, +@var{Element}, ?@var{Set2}) -@findex ord_del_element/3 -@syindex ord_del_element/3 -@cnindex ord_del_element/3 -Removing @var{Element} from @var{Set1} returns @var{Set2}. - -@item ord_disjoint(+@var{Set1}, +@var{Set2}) -@findex ord_disjoint/2 -@syindex ord_disjoint/2 -@cnindex ord_disjoint/2 -Holds when the two ordered sets have no element in common. - -@item ord_member(+@var{Element}, +@var{Set}) -@findex ord_member/2 -@syindex ord_member/2 -@cnindex ord_member/2 -Holds when @var{Element} is a member of @var{Set}. - -@item ord_insert(+@var{Set1}, +@var{Element}, ?@var{Set2}) -@findex ord_insert/3 -@syindex ord_insert/3 -@cnindex ord_insert/3 -Inserting @var{Element} in @var{Set1} returns @var{Set2}. It should give -exactly the same result as @code{merge(Set1, [Element], Set2)}, but a -bit faster, and certainly more clearly. The same as @code{ord_add_element/3}. - -@item ord_intersect(+@var{Set1}, +@var{Set2}) -@findex ord_intersect/2 -@syindex ord_intersect/2 -@cnindex ord_intersect/2 -Holds when the two ordered sets have at least one element in common. - -@item ord_intersection(+@var{Set1}, +@var{Set2}, ?@var{Intersection}) -@findex ord_intersect/3 -@syindex ord_intersect/3 -@cnindex ord_intersect/3 -Holds when Intersection is the ordered representation of @var{Set1} -and @var{Set2}. - -@item ord_intersection(+@var{Set1}, +@var{Set2}, ?@var{Intersection}, ?@var{Diff}) -@findex ord_intersect/4 -@syindex ord_intersect/4 -@cnindex ord_intersect/4 -Holds when Intersection is the ordered representation of @var{Set1} -and @var{Set2}. @var{Diff} is the difference between @var{Set2} and @var{Set1}. - -@item ord_seteq(+@var{Set1}, +@var{Set2}) -@findex ord_seteq/2 -@syindex ord_seteq/2 -@cnindex ord_seteq/2 -Holds when the two arguments represent the same set. - -@item ord_setproduct(+@var{Set1}, +@var{Set2}, -@var{Set}) -@findex ord_setproduct/3 -@syindex ord_setproduct/3 -@cnindex ord_setproduct/3 -If Set1 and Set2 are ordered sets, Product will be an ordered -set of x1-x2 pairs. - -@item ord_subset(+@var{Set1}, +@var{Set2}) -@findex ordsubset/2 -@syindex ordsubset/2 -@cnindex ordsubset/2 -Holds when every element of the ordered set @var{Set1} appears in the -ordered set @var{Set2}. - -@item ord_subtract(+@var{Set1}, +@var{Set2}, ?@var{Difference}) -@findex ord_subtract/3 -@syindex ord_subtract/3 -@cnindex ord_subtract/3 -Holds when @var{Difference} contains all and only the elements of @var{Set1} -which are not also in @var{Set2}. - -@item ord_symdiff(+@var{Set1}, +@var{Set2}, ?@var{Difference}) -@findex ord_symdiff/3 -@syindex ord_symdiff/3 -@cnindex ord_symdiff/3 -Holds when @var{Difference} is the symmetric difference of @var{Set1} -and @var{Set2}. - -@item ord_union(+@var{Sets}, ?@var{Union}) -@findex ord_union/2 -@syindex ord_union/2 -@cnindex ord_union/2 -Holds when @var{Union} is the union of the lists @var{Sets}. - -@item ord_union(+@var{Set1}, +@var{Set2}, ?@var{Union}) -@findex ord_union/3 -@syindex ord_union/3 -@cnindex ord_union/3 -Holds when @var{Union} is the union of @var{Set1} and @var{Set2}. - -@item ord_union(+@var{Set1}, +@var{Set2}, ?@var{Union}, ?@var{Diff}) -@findex ord_union/4 -@syindex ord_union/4 -@cnindex ord_union/4 -Holds when @var{Union} is the union of @var{Set1} and @var{Set2} and -@var{Diff} is the difference. - -@end table - -@node Pseudo Random, Queues, Ordered Sets, Library -@section Pseudo Random Number Integer Generator -@cindex pseudo random - -The following routines produce random non-negative integers in the range -0 .. 2^(w-1) -1, where w is the word size available for integers, e.g. -32 for Intel machines and 64 for Alpha machines. Note that the numbers -generated by this random number generator are repeatable. This generator -was originally written by Allen Van Gelder and is based on Knuth Vol 2. - -@table @code -@item rannum(-@var{I}) -@findex rannum/1 -@snindex rannum/1 -@cnindex rannum/1 -Produces a random non-negative integer @var{I} whose low bits are not -all that random, so it should be scaled to a smaller range in general. -The integer @var{I} is in the range 0 .. 2^(w-1) - 1. You can use: -@example -rannum(X) :- yap_flag(max_integer,MI), rannum(R), X is R/MI. -@end example -to obtain a floating point number uniformly distributed between 0 and 1. - -@item ranstart -@findex ranstart/0 -@snindex ranstart/0 -@cnindex ranstart/0 -Initialize the random number generator using a built-in seed. The -@code{ranstart/0} built-in is always called by the system when loading -the package. - -@item ranstart(+@var{Seed}) -@findex ranstart/1 -@snindex ranstart/1 -@cnindex ranstart/1 -Initialize the random number generator with user-defined @var{Seed}. The -same @var{Seed} always produces the same sequence of numbers. - -@item ranunif(+@var{Range},-@var{I}) -@findex ranunif/2 -@snindex ranunif/2 -@cnindex ranunif/2 -@code{ranunif/2} produces a uniformly distributed non-negative random -integer @var{I} over a caller-specified range @var{R}. If range is @var{R}, -the result is in 0 .. @var{R}-1. - -@end table - -@node Queues, Random, Pseudo Random, Library -@section Queues -@cindex queue - -The following queue manipulation routines are available once -included with the @code{use_module(library(queues))} command. Queues are -implemented with difference lists. - -@table @code - -@item make_queue(+@var{Queue}) -@findex make_queue/1 -@syindex make_queue/1 -@cnindex make_queue/1 -Creates a new empty queue. It should only be used to create a new queue. - -@item join_queue(+@var{Element}, +@var{OldQueue}, -@var{NewQueue}) -@findex join_queue/3 -@syindex join_queue/3 -@cnindex join_queue/3 -Adds the new element at the end of the queue. - -@item list_join_queue(+@var{List}, +@var{OldQueue}, -@var{NewQueue}) -@findex list_join_queue/3 -@syindex list_join_queue/3 -@cnindex list_join_queue/3 -Ads the new elements at the end of the queue. - -@item jump_queue(+@var{Element}, +@var{OldQueue}, -@var{NewQueue}) -@findex jump_queue/3 -@syindex jump_queue/3 -@cnindex jump_queue/3 -Adds the new element at the front of the list. - -@item list_jump_queue(+@var{List}, +@var{OldQueue}, +@var{NewQueue}) -@findex list_jump_queue/3 -@syindex list_jump_queue/3 -@cnindex list_jump_queue/3 -Adds all the elements of @var{List} at the front of the queue. - -@item head_queue(+@var{Queue}, ?@var{Head}) -@findex head_queue/2 -@syindex head_queue/2 -@cnindex head_queue/2 -Unifies Head with the first element of the queue. - -@item serve_queue(+@var{OldQueue}, +@var{Head}, -@var{NewQueue}) -@findex serve_queue/3 -@syindex serve_queue/3 -@cnindex serve_queue/3 -Removes the first element of the queue for service. - -@item empty_queue(+@var{Queue}) -@findex empty_queue/1 -@syindex empty_queue/1 -@cnindex empty_queue/1 -Tests whether the queue is empty. - -@item length_queue(+@var{Queue}, -@var{Length}) -@findex length_queue/2 -@syindex length_queue/2 -@cnindex length_queue/2 -Counts the number of elements currently in the queue. - -@item list_to_queue(+@var{List}, -@var{Queue}) -@findex list_to_queue/2 -@syindex list_to_queue/2 -@cnindex list_to_queue/2 -Creates a new queue with the same elements as @var{List.} - -@item queue_to_list(+@var{Queue}, -@var{List}) -@findex queue_to_list/2 -@syindex queue_to_list/2 -@cnindex queue_to_list/2 -Creates a new list with the same elements as @var{Queue}. - -@end table - - -@node Random, Read Utilities, Queues, Library -@section Random Number Generator -@cindex random - -The following random number operations are included with the -@code{use_module(library(random))} command. Since YAP-4.3.19 YAP uses -the O'Keefe public-domain algorithm, based on the "Applied Statistics" -algorithm AS183. - -@table @code - -@item getrand(-@var{Key}) -@findex getrand/1 -@syindex getrand/1 -@cnindex getrand/1 -Unify @var{Key} with a term of the form @code{rand(X,Y,Z)} describing the -current state of the random number generator. - -@item random(-@var{Number}) -@findex random/1 -@syindex random/1 -@cnindex random/1 -Unify @var{Number} with a floating-point number in the range @code{[0...1)}. - -@item random(+@var{LOW}, +@var{HIGH}, -@var{NUMBER}) -@findex random/3 -@syindex random/3 -@cnindex random/3 -Unify @var{Number} with a number in the range -@code{[LOW...HIGH)}. If both @var{LOW} and @var{HIGH} are -integers then @var{NUMBER} will also be an integer, otherwise -@var{NUMBER} will be a floating-point number. - -@item randseq(+@var{LENGTH}, +@var{MAX}, -@var{Numbers}) -@findex randseq/3 -@syindex randseq/3 -@cnindex randseq/3 -Unify @var{Numbers} with a list of @var{LENGTH} unique random integers -in the range @code{[1...@var{MAX})}. - -@item randset(+@var{LENGTH}, +@var{MAX}, -@var{Numbers}) -@findex randset/3 -@syindex randset/3 -@cnindex randset/3 -Unify @var{Numbers} with an ordered list of @var{LENGTH} unique random -integers in the range @code{[1...@var{MAX})}. - -@item setrand(+@var{Key}) -@findex setrand/1 -@syindex setrand/1 -@cnindex setrand/1 -Use a term of the form @code{rand(X,Y,Z)} to set a new state for the -random number generator. The integer @code{X} must be in the range -@code{[1...30269)}, the integer @code{Y} must be in the range -@code{[1...30307)}, and the integer @code{Z} must be in the range -@code{[1...30323)}. - -@end table - -@node Read Utilities, Red-Black Trees, Random, Library -@section Read Utilities - -The @code{readutil} library contains primitives to read lines, files, -multiple terms, etc. - -@table @code -@item read_line_to_codes(+@var{Stream}, -@var{Codes}) -@findex read_line_to_codes/2 -@snindex read_line_to_codes/2 -@cnindex read_line_to_codes/2 - -Read the next line of input from @var{Stream} and unify the result with -@var{Codes} @emph{after} the line has been read. A line is ended by a -newline character or end-of-file. Unlike @code{read_line_to_codes/3}, -this predicate removes trailing newline character. - -On end-of-file the atom @code{end_of_file} is returned. See also -@code{at_end_of_stream/[0,1]}. - -@item read_line_to_codes(+@var{Stream}, -@var{Codes}, ?@var{Tail}) -@findex read_line_to_codes/3 -@snindex read_line_to_codes/3 -@cnindex read_line_to_codes/3 -Difference-list version to read an input line to a list of character -codes. Reading stops at the newline or end-of-file character, but -unlike @code{read_line_to_codes/2}, the newline is retained in the -output. This predicate is especially useful for reading a block of -lines upto some delimiter. The following example reads an HTTP header -ended by a blank line: - -@example -read_header_data(Stream, Header) :- - read_line_to_codes(Stream, Header, Tail), - read_header_data(Header, Stream, Tail). - -read_header_data("\r\n", _, _) :- !. -read_header_data("\n", _, _) :- !. -read_header_data("", _, _) :- !. -read_header_data(_, Stream, Tail) :- - read_line_to_codes(Stream, Tail, NewTail), - read_header_data(Tail, Stream, NewTail). -@end example - -@item read_stream_to_codes(+@var{Stream}, -@var{Codes}) -@findex read_stream_to_codes/2 -@snindex read_stream_to_codes/2 -@cnindex read_stream_to_codes/2 -Read all input until end-of-file and unify the result to @var{Codes}. - -@item read_stream_to_codes(+@var{Stream}, -@var{Codes}, ?@var{Tail}) -@findex read_stream_to_codes/3 -@snindex read_stream_to_codes/3 -@cnindex read_stream_to_codes/3 -Difference-list version of @code{read_stream_to_codes/2}. - -@item read_file_to_codes(+@var{Spec}, -@var{Codes}, +@var{Options}) -@findex read_file_to_codes/3 -@snindex read_file_to_codes/3 -@cnindex read_file_to_codes/3 -Read a file to a list of character codes. Currently ignores -@var{Options}. - -@c @var{Spec} is a -@c file-specification for absolute_file_name/3. @var{Codes} is the -@c resulting code-list. @var{Options} is a list of options for -@c absolute_file_name/3 and open/4. In addition, the option -@c \term{tail}{Tail} is defined, forming a difference-list. - -@item read_file_to_terms(+@var{Spec}, -@var{Terms}, +@var{Options}) -@findex read_file_to_terms/3 -@snindex read_file_to_terms/3 -@cnindex read_file_to_terms/3 -Read a file to a list of Prolog terms (see read/1). @c @var{Spec} is a -@c file-specification for absolute_file_name/3. @var{Terms} is the -@c resulting list of Prolog terms. @var{Options} is a list of options for -@c absolute_file_name/3 and open/4. In addition, the option -@c \term{tail}{Tail} is defined, forming a difference-list. -@c \end{description} - -@end table - - - -@node Red-Black Trees, RegExp, Read Utilities, Library -@section Red-Black Trees -@cindex Red-Black Trees - -Red-Black trees are balanced search binary trees. They are named because -nodes can be classified as either red or black. The code we include is -based on "Introduction to Algorithms", second edition, by Cormen, -Leiserson, Rivest and Stein. The library includes routines to insert, -lookup and delete elements in the tree. - -@table @code -@item rb_new(?@var{T}) -@findex rb_new/1 -@snindex rb_new/1 -@cnindex rb_new/1 -Create a new tree. - -@item rb_empty(?@var{T}) -@findex rb_empty/1 -@snindex rb_empty/1 -@cnindex rb_empty/1 -Succeeds if tree @var{T} is empty. - -@item is_rbtree(+@var{T}) -@findex is_rbtree/1 -@snindex is_rbtree/1 -@cnindex is_rbtree/1 -Check whether @var{T} is a valid red-black tree. - -@item rb_insert(+@var{T0},+@var{Key},?@var{Value},+@var{TF}) -@findex rb_insert/4 -@snindex rb_insert/4 -@cnindex rb_insert/4 -Add an element with key @var{Key} and @var{Value} to the tree -@var{T0} creating a new red-black tree @var{TF}. Duplicated elements are not -allowed. - -@snindex rb_insert_new/4 -@cnindex rb_insert_new/4 -Add a new element with key @var{Key} and @var{Value} to the tree -@var{T0} creating a new red-black tree @var{TF}. Fails is an element -with @var{Key} exists in the tree. - -@item rb_lookup(+@var{Key},-@var{Value},+@var{T}) -@findex rb_lookup/3 -@snindex rb_lookup/3 -@cnindex rb_lookup/3 -Backtrack through all elements with key @var{Key} in the red-black tree -@var{T}, returning for each the value @var{Value}. - -@item rb_lookupall(+@var{Key},-@var{Value},+@var{T}) -@findex rb_lookupall/3 -@snindex rb_lookupall/3 -@cnindex rb_lookupall/3 -Lookup all elements with key @var{Key} in the red-black tree -@var{T}, returning the value @var{Value}. - -@item rb_delete(+@var{T},+@var{Key},-@var{TN}) -@findex rb_delete/3 -@snindex rb_delete/3 -@cnindex rb_delete/3 -Delete element with key @var{Key} from the tree @var{T}, returning a new -tree @var{TN}. - -@item rb_delete(+@var{T},+@var{Key},-@var{Val},-@var{TN}) -@findex rb_delete/4 -@snindex rb_delete/4 -@cnindex rb_delete/4 -Delete element with key @var{Key} from the tree @var{T}, returning the -value @var{Val} associated with the key and a new tree @var{TN}. - -@item rb_del_min(+@var{T},-@var{Key},-@var{Val},-@var{TN}) -@findex rb_del_min/4 -@snindex rb_del_min/4 -@cnindex rb_del_min/4 -Delete the least element from the tree @var{T}, returning the key -@var{Key}, the value @var{Val} associated with the key and a new tree -@var{TN}. - -@item rb_del_max(+@var{T},-@var{Key},-@var{Val},-@var{TN}) -@findex rb_del_max/4 -@snindex rb_del_max/4 -@cnindex rb_del_max/4 -Delete the largest element from the tree @var{T}, returning the key -@var{Key}, the value @var{Val} associated with the key and a new tree -@var{TN}. - -@item rb_update(+@var{T},+@var{Key},+@var{NewVal},-@var{TN}) -@findex rb_update/4 -@snindex rb_update/4 -@cnindex rb_update/4 -Tree @var{TN} is tree @var{T}, but with value for @var{Key} associated -with @var{NewVal}. Fails if it cannot find @var{Key} in @var{T}. - -@item rb_apply(+@var{T},+@var{Key},+@var{G},-@var{TN}) -@findex rb_apply/4 -@snindex rb_apply/4 -@cnindex rb_apply/4 -If the value associated with key @var{Key} is @var{Val0} in @var{T}, and -if @code{call(G,Val0,ValF)} holds, then @var{TN} differs from -@var{T} only in that @var{Key} is associated with value @var{ValF} in -tree @var{TN}. Fails if it cannot find @var{Key} in @var{T}, or if -@code{call(G,Val0,ValF)} is not satisfiable. - -@item rb_visit(+@var{T},-@var{Pairs}) -@findex rb_visit/2 -@snindex rb_visit/2 -@cnindex rb_visit/2 -@var{Pairs} is an infix visit of tree @var{T}, where each element of -@var{Pairs} is of the form @var{K}-@var{Val}. - -@item rb_size(+@var{T},-@var{Size}) -@findex rb_size/2 -@snindex rb_size/2 -@cnindex rb_size/2 -@var{Size} is the number of elements in @var{T}. - -@item rb_keys(+@var{T},+@var{Keys}) -@findex rb_keys/2 -@snindex rb_keys/2 -@cnindex rb_keys/2 -@var{Keys} is an infix visit with all keys in tree @var{T}. Keys will be -sorted, but may be duplicate. - -@item rb_map(+@var{T},+@var{G},-@var{TN}) -@findex rb_map/3 -@snindex rb_map/3 -@cnindex rb_map/3 -For all nodes @var{Key} in the tree @var{T}, if the value associated with -key @var{Key} is @var{Val0} in tree @var{T}, and if -@code{call(G,Val0,ValF)} holds, then the value associated with @var{Key} -in @var{TN} is @var{ValF}. Fails if or if @code{call(G,Val0,ValF)} is not -satisfiable for all @var{Var0}. - -@item rb_partial_map(+@var{T},+@var{Keys},+@var{G},-@var{TN}) -@findex rb_partial_map/4 -@snindex rb_partial_map/4 -@cnindex rb_partial_map/4 -For all nodes @var{Key} in @var{Keys}, if the value associated with key -@var{Key} is @var{Val0} in tree @var{T}, and if @code{call(G,Val0,ValF)} -holds, then the value associated with @var{Key} in @var{TN} is -@var{ValF}. Fails if or if @code{call(G,Val0,ValF)} is not satisfiable -for all @var{Var0}. Assumes keys are not repeated. - -@item rb_fold(+@var{T},+@var{G},+@var{Acc0}, -@var{AccF}) -@findex rb_fold/4 -@snindex rb_fold/4 -@cnindex rb_fold/4 - For all nodes @var{Key} in the tree @var{T}, if the value -associated with key @var{Key} is @var{V} in tree @var{T}, if -@code{call(G,V,Acc1,Acc2)} holds, then if @var{VL} is value of the -previous node in inorder, @code{call(G,VL,_,Acc0)} must hold, and if -@var{VR} is the value of the next node in inorder, -@code{call(G,VR,Acc1,_)} must hold. - -@item rb_key_fold(+@var{T},+@var{G},+@var{Acc0}, -@var{AccF}) -@findex rb_key_fold/4 -@snindex rb_key_fold/4 -@cnindex rb_key_fold/4 - For all nodes @var{Key} in the tree @var{T}, if the value -associated with key @var{Key} is @var{V} in tree @var{T}, if -@code{call(G,Key,V,Acc1,Acc2)} holds, then if @var{VL} is value of the -previous node in inorder, @code{call(G,KeyL,VL,_,Acc0)} must hold, and if -@var{VR} is the value of the next node in inorder, -@code{call(G,KeyR,VR,Acc1,_)} must hold. - -@item rb_clone(+@var{T},+@var{NT},+@var{Nodes}) -@findex rb_clone/3 -@snindex rb_clone/3 -@cnindex rb_clone/3 -``Clone'' the red-back tree into a new tree with the same keys as the -original but with all values set to unbound values. Nodes is a list -containing all new nodes as pairs @var{K-V}. - -@item rb_min(+@var{T},-@var{Key},-@var{Value}) -@findex rb_min/3 -@snindex rb_min/3 -@cnindex rb_min/3 -@var{Key} is the minimum key in @var{T}, and is associated with @var{Val}. - -@item rb_max(+@var{T},-@var{Key},-@var{Value}) -@findex rb_max/3 -@snindex rb_max/3 -@cnindex rb_max/3 -@var{Key} is the maximal key in @var{T}, and is associated with @var{Val}. - -@item rb_next(+@var{T}, +@var{Key},-@var{Next},-@var{Value}) -@findex rb_next/4 -@snindex rb_next/4 -@cnindex rb_next/4 -@var{Next} is the next element after @var{Key} in @var{T}, and is -associated with @var{Val}. - -@item rb_previous(+@var{T}, +@var{Key},-@var{Previous},-@var{Value}) -@findex rb_previous/4 -@snindex rb_previous/4 -@cnindex rb_previous/4 -@var{Previous} is the previous element after @var{Key} in @var{T}, and is -associated with @var{Val}. - -@item ord_list_to_rbtree(+@var{L}, -@var{T}) -@findex list_to_rbtree/2 -@snindex list_to_rbtree/2 -@cnindex list_to_rbtree/2 -@var{T} is the red-black tree corresponding to the mapping in ordered -list @var{L}. -@end table - -@node RegExp, shlib, Red-Black Trees, Library -@section Regular Expressions -@cindex regular expressions - -This library includes routines to determine whether a regular expression -matches part or all of a string. The routines can also return which -parts parts of the string matched the expression or subexpressions of -it. This library relies on Henry Spencer's @code{C}-package and is only -available in operating systems that support dynamic loading. The -@code{C}-code has been obtained from the sources of FreeBSD-4.0 and is -protected by copyright from Henry Spencer and from the Regents of the -University of California (see the file library/regex/COPYRIGHT for -further details). - -Much of the description of regular expressions below is copied verbatim -from Henry Spencer's manual page. - -A regular expression is zero or more branches, separated by ``|''. It -matches anything that matches one of the branches. - -A branch is zero or more pieces, concatenated. It matches a match for -the first, followed by a match for the second, etc. - -A piece is an atom possibly followed by ``*'', ``+'', or ``?''. An atom -followed by ``*'' matches a sequence of 0 or more matches of the atom. -An atom followed by ``+'' matches a sequence of 1 or more matches of the -atom. An atom followed by ``?'' matches a match of the atom, or the -null string. - -An atom is a regular expression in parentheses (matching a match for the -regular expression), a range (see below), ``.'' (matching any single -character), ``^'' (matching the null string at the beginning of the -input string), ``$'' (matching the null string at the end of the input -string), a ``\'' followed by a single character (matching that -character), or a single character with no other significance (matching -that character). - -A range is a sequence of characters enclosed in ``[]''. It normally -matches any single character from the sequence. If the sequence begins -with ``^'', it matches any single character not from the rest of the -sequence. If two characters in the sequence are separated by ``-'', -this is shorthand for the full list of ASCII characters between them -(e.g. ``[0-9]'' matches any decimal digit). To include a literal ``]'' -in the sequence, make it the first character (following a possible -``^''). To include a literal ``-'', make it the first or last -character. - -@table @code - -@item regexp(+@var{RegExp},+@var{String},+@var{Opts}) -@findex regexp/3 -@snindex regexp/3 -@cnindex regexp/3 - -Match regular expression @var{RegExp} to input string @var{String} -according to options @var{Opts}. The options may be: -@itemize @bullet -@item @code{nocase}: Causes upper-case characters in @var{String} to - be treated as lower case during the matching process. -@end itemize - -@item regexp(+@var{RegExp},+@var{String},+@var{Opts},?@var{SubMatchVars}) -@findex regexp/4 -@snindex regexp/4 -@cnindex regexp/4 - -Match regular expression @var{RegExp} to input string @var{String} -according to options @var{Opts}. The variable @var{SubMatchVars} should -be originally unbound or a list of unbound variables all will contain a -sequence of matches, that is, the head of @var{SubMatchVars} will -contain the characters in @var{String} that matched the leftmost -parenthesized subexpression within @var{RegExp}, the next head of list -will contain the characters that matched the next parenthesized -subexpression to the right in @var{RegExp}, and so on. - -The options may be: -@itemize @bullet -@item @code{nocase}: Causes upper-case characters in @var{String} to - be treated as lower case during the matching process. -@item @code{indices}: Changes what is stored in -@var{SubMatchVars}. Instead of storing the matching characters from -@var{String}, each variable will contain a term of the form @var{IO-IF} -giving the indices in @var{String} of the first and last characters in -the matching range of characters. - -@end itemize - -In general there may be more than one way to match a regular expression -to an input string. For example, consider the command -@example - regexp("(a*)b*","aabaaabb", [], [X,Y]) -@end example -Considering only the rules given so far, @var{X} and @var{Y} could end up -with the values @code{"aabb"} and @code{"aa"}, @code{"aaab"} and -@code{"aaa"}, @code{"ab"} and @code{"a"}, or any of several other -combinations. To resolve this potential ambiguity @code{regexp} chooses among -alternatives using the rule ``first then longest''. In other words, it -considers the possible matches in order working from left to right -across the input string and the pattern, and it attempts to match longer -pieces of the input string before shorter ones. More specifically, the -following rules apply in decreasing order of priority: - - -@enumerate -@item If a regular expression could match two different parts of an -input string then it will match the one that begins earliest. - -@item If a regular expression contains "|" operators then the leftmost matching sub-expression is chosen. - -@item In *, +, and ? constructs, longer matches are chosen in preference to shorter ones. - -@item In sequences of expression components the components are considered from left to right. -@end enumerate - -In the example from above, @code{"(a*)b*"} matches @code{"aab"}: the -@code{"(a*)"} portion of the pattern is matched first and it consumes -the leading @code{"aa"}; then the @code{"b*"} portion of the pattern -consumes the next @code{"b"}. Or, consider the following example: -@example - regexp("(ab|a)(b*)c", "abc", [], [X,Y,Z]) -@end example - -After this command @var{X} will be @code{"abc"}, @var{Y} will be -@code{"ab"}, and @var{Z} will be an empty string. Rule 4 specifies that -@code{"(ab|a)"} gets first shot at the input string and Rule 2 specifies -that the @code{"ab"} sub-expression is checked before the @code{"a"} -sub-expression. Thus the @code{"b"} has already been claimed before the -@code{"(b*)"} component is checked and @code{(b*)} must match an empty string. - -@end table - -@node shlib, Splay Trees, RegExp, Library -@section SWI-Prolog's shlib library - -@cindex SWI-Compatible foreign file loading -This section discusses the functionality of the (autoload) -@code{library(shlib)}, providing an interface to manage shared -libraries. - -One of the files provides a global function @code{install_mylib()} that -initialises the module using calls to @code{PL_register_foreign()}. Here is a -simple example file @code{mylib.c}, which creates a Windows MessageBox: - -@c_example -#include -#include - -static foreign_t -pl_say_hello(term_t to) -@{ char *a; - - if ( PL_get_atom_chars(to, &a) ) - @{ MessageBox(NULL, a, "DLL test", MB_OK|MB_TASKMODAL); - - PL_succeed; - @} - - PL_fail; -@} - -install_t -install_mylib() -@{ PL_register_foreign("say_hello", 1, pl_say_hello, 0); -@} -@end c_example - -Now write a file mylib.pl: - -@example -:- module(mylib, [ say_hello/1 ]). -:- use_foreign_library(foreign(mylib)). -@end example - -The file mylib.pl can be loaded as a normal Prolog file and provides the predicate defined in C. - -@table @code -@item load_foreign_library(:@var{FileSpec}) is det -@findex load_foreign_library/1 -@snindex load_foreign_library/1 -@cnindex load_foreign_library/1 -@item load_foreign_library(:@var{FileSpec}, +@var{Entry}:atom) is det -@findex load_foreign_library/2 -@snindex load_foreign_library/2 -@cnindex load_foreign_library/2 - Load a shared object or DLL. After loading the @var{Entry} function is - called without arguments. The default entry function is composed - from @code{install_}, followed by the file base-name. E.g., the - load-call below calls the function @code{install_mylib()}. If the platform - prefixes extern functions with @code{_}, this prefix is added before - calling. - -@example - ... - load_foreign_library(foreign(mylib)), - ... -@end example - - @var{FileSpec} is a specification for - @code{absolute_file_name/3}. If searching the file fails, the plain - name is passed to the OS to try the default method of the OS for - locating foreign objects. The default definition of - @code{file_search_path/2} searches /lib/Yap. - - See also - @code{use_foreign_library/1,2} are intended for use in - directives. - -@item [det] use_foreign_library(+@var{FileSpec}), use_foreign_library(+@var{FileSpec}, +@var{Entry}:atom) -@findex use_foreign_library/1 -@snindex use_foreign_library/1 -@cnindex use_foreign_library/1 -@findex use_foreign_library/2 -@snindex use_foreign_library/2 -@cnindex use_foreign_library/2 - Load and install a foreign library as @code{load_foreign_library/1} - and @code{load_foreign_library/2} and - register the installation using @code{initialization/2} with the option - now. This is similar to using: - -@example - :- initialization(load_foreign_library(foreign(mylib))). -@end example - - but using the @code{initialization/1} wrapper causes the library to - be loaded after loading of the file in which it appears is - completed, while @code{use_foreign_library/1} loads the library - immediately. I.e. the difference is only relevant if the remainder - of the file uses functionality of the @code{C}-library. - -@item [det]unload_foreign_library(+@var{FileSpec}) -@item [det]unload_foreign_library(+@var{FileSpec}, +@var{Exit}:atom) -@findex unload_foreign_library/1 -@snindex unload_foreign_library/1 -@cnindex unload_foreign_library/1 -@findex unload_foreign_library/2 -@snindex unload_foreign_library/2 -@cnindex unload_foreign_library/2 - -Unload a shared -object or DLL. After calling the @var{Exit} function, the shared object is -removed from the process. The default exit function is composed from -@code{uninstall_}, followed by the file base-name. - -@item current_foreign_library(?@var{File}, ?@var{Public}) -@findex current_foreign_library/2 -@snindex current_foreign_library/2 -@cnindex current_foreign_library/2 - -Query currently -loaded shared libraries. - -@c @item reload_foreign_libraries -@c @findex reload_foreign_libraries/0 -@c @snindex reload_foreign_libraries/0 -@c @cnindex reload_foreign_libraries/0 -@c Reload all foreign -@c libraries loaded (after restore of a state created using -@c @code{qsave_program/2}). -@end table - -@node Splay Trees, String Input/Output, shlib, Library -@section Splay Trees -@cindex splay trees - -Splay trees are explained in the paper "Self-adjusting Binary Search -Trees", by D.D. Sleator and R.E. Tarjan, JACM, vol. 32, No.3, July 1985, -p. 668. They are designed to support fast insertions, deletions and -removals in binary search trees without the complexity of traditional -balanced trees. The key idea is to allow the tree to become -unbalanced. To make up for this, whenever we find a node, we move it up -to the top. We use code by Vijay Saraswat originally posted to the Prolog -mailing-list. - -@table @code - -@item splay_access(-@var{Return},+@var{Key},?@var{Val},+@var{Tree},-@var{NewTree}) -@findex splay_access/5 -@snindex splay_access/5 -@cnindex splay_access/5 -If item @var{Key} is in tree @var{Tree}, return its @var{Val} and -unify @var{Return} with @code{true}. Otherwise unify @var{Return} with -@code{null}. The variable @var{NewTree} unifies with the new tree. - -@item splay_delete(+@var{Key},?@var{Val},+@var{Tree},-@var{NewTree}) -@findex splay_delete/4 -@snindex splay_delete/4 -@cnindex splay_delete/4 -Delete item @var{Key} from tree @var{Tree}, assuming that it is present -already. The variable @var{Val} unifies with a value for key @var{Key}, -and the variable @var{NewTree} unifies with the new tree. The predicate -will fail if @var{Key} is not present. - -@item splay_init(-@var{NewTree}) -@findex splay_init/3 -@snindex splay_init/3 -@cnindex splay_init/3 -Initialize a new splay tree. - -@item splay_insert(+@var{Key},?@var{Val},+@var{Tree},-@var{NewTree}) -@findex splay_insert/4 -@snindex splay_insert/4 -@cnindex splay_insert/4 -Insert item @var{Key} in tree @var{Tree}, assuming that it is not -there already. The variable @var{Val} unifies with a value for key -@var{Key}, and the variable @var{NewTree} unifies with the new -tree. In our implementation, @var{Key} is not inserted if it is -already there: rather it is unified with the item already in the tree. - -@item splay_join(+@var{LeftTree},+@var{RighTree},-@var{NewTree}) -@findex splay_join/3 -@snindex splay_join/3 -@cnindex splay_join/3 -Combine trees @var{LeftTree} and @var{RighTree} into a single -tree@var{NewTree} containing all items from both trees. This operation -assumes that all items in @var{LeftTree} are less than all those in -@var{RighTree} and destroys both @var{LeftTree} and @var{RighTree}. - -@item splay_split(+@var{Key},?@var{Val},+@var{Tree},-@var{LeftTree},-@var{RightTree}) -@findex splay_split/5 -@snindex splay_split/5 -@cnindex splay_split/5 -Construct and return two trees @var{LeftTree} and @var{RightTree}, -where @var{LeftTree} contains all items in @var{Tree} less than -@var{Key}, and @var{RightTree} contains all items in @var{Tree} -greater than @var{Key}. This operations destroys @var{Tree}. - -@end table - -@node String Input/Output, System, Splay Trees, Library -@section Reading From and Writing To Strings -@cindex string Input/Output - -From Version 4.3.2 onwards YAP implements SICStus Prolog compatible -String Input/Output. The library allows users to read from and write to a memory -buffer as if it was a file. The memory buffer is built from or converted -to a string of character codes by the routines in library. Therefore, if -one wants to read from a string the string must be fully instantiated -before the library built-in opens the string for reading. These commands -are available through the @code{use_module(library(charsio))} command. - -@table @code - -@item format_to_chars(+@var{Form}, +@var{Args}, -@var{Result}) -@findex format_to_chars/3 -@syindex format_to_chars/3 -@cnindex format_to_chars/3 - -Execute the built-in procedure @code{format/2} with form @var{Form} and -arguments @var{Args} outputting the result to the string of character -codes @var{Result}. - -@item format_to_chars(+@var{Form}, +@var{Args}, -@var{Result}, -@var{Result0}) -@findex format_to_chars/4 -@syindex format_to_chars/4 -@cnindex format_to_chars/4 - -Execute the built-in procedure @code{format/2} with form @var{Form} and -arguments @var{Args} outputting the result to the difference list of -character codes @var{Result-Result0}. - -@item write_to_chars(+@var{Term}, -@var{Result}) -@findex write_to_chars/2 -@syindex write_to_chars/2 -@cnindex write_to_chars/2 - -Execute the built-in procedure @code{write/1} with argument @var{Term} -outputting the result to the string of character codes @var{Result}. - -@item write_to_chars(+@var{Term}, -@var{Result0}, -@var{Result}) -@findex write_to_chars/3 -@syindex write_to_chars/3 -@cnindex write_to_chars/3 - -Execute the built-in procedure @code{write/1} with argument @var{Term} -outputting the result to the difference list of character codes -@var{Result-Result0}. - -@item atom_to_chars(+@var{Atom}, -@var{Result}) -@findex atom_to_chars/2 -@syindex atom_to_chars/2 -@cnindex atom_to_chars/2 - -Convert the atom @var{Atom} to the string of character codes -@var{Result}. - -@item atom_to_chars(+@var{Atom}, -@var{Result0}, -@var{Result}) -@findex atom_to_chars/3 -@syindex atom_to_chars/3 -@cnindex atom_to_chars/3 - -Convert the atom @var{Atom} to the difference list of character codes -@var{Result-Result0}. - -@item number_to_chars(+@var{Number}, -@var{Result}) -@findex number_to_chars/2 -@syindex number_to_chars/2 -@cnindex number_to_chars/2 - -Convert the number @var{Number} to the string of character codes -@var{Result}. - -@item number_to_chars(+@var{Number}, -@var{Result0}, -@var{Result}) -@findex number_to_chars/3 -@syindex number_to_chars/3 -@cnindex number_to_chars/3 - -Convert the atom @var{Number} to the difference list of character codes -@var{Result-Result0}. - -@item atom_to_term(+@var{Atom}, -@var{Term}, -@var{Bindings}) -@findex atom_to_term/3 -@syindex atom_to_term/3 -@cnindex atom_to_term/3 -Use @var{Atom} as input to @code{read_term/2} using the option @code{variable_names} and return the read term in @var{Term} and the variable bindings in @var{Bindings}. @var{Bindings} is a list of @code{Name = Var} couples, thus providing access to the actual variable names. See also @code{read_term/2}. If Atom has no valid syntax, a syntax_error exception is raised. - -@item term_to_atom(?@var{Term}, ?@var{Atom}) -@findex term_to_atom/2 -@syindex term_to_atom/2 -@cnindex term_to_atom/2 -True if @var{Atom} describes a term that unifies with @var{Term}. When -@var{Atom} is instantiated @var{Atom} is converted and then unified with -@var{Term}. If @var{Atom} has no valid syntax, a syntax_error exception -is raised. Otherwise @var{Term} is ``written'' on @var{Atom} using -@code{write_term/2} with the option quoted(true). - -@item read_from_chars(+@var{Chars}, -@var{Term}) -@findex read_from_chars/2 -@syindex read_from_chars/2 -@cnindex read_from_chars/2 - -Parse the list of character codes @var{Chars} and return the result in -the term @var{Term}. The character codes to be read must terminate with -a dot character such that either (i) the dot character is followed by -blank characters; or (ii) the dot character is the last character in the -string. - -@item open_chars_stream(+@var{Chars}, -@var{Stream}) -@findex open_chars_stream/2 -@syindex open_chars_stream/2 -@cnindex open_chars_stream/2 - -Open the list of character codes @var{Chars} as a stream @var{Stream}. - -@item with_output_to_chars(?@var{Goal}, -@var{Chars}) -@findex with_output_to_chars/2 -@syindex with_output_to_chars/2 -@cnindex with_output_to_chars/2 - -Execute goal @var{Goal} such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the list of character codes @var{Chars}. - -@item with_output_to_chars(?@var{Goal}, ?@var{Chars0}, -@var{Chars}) -@findex with_output_to_chars/3 -@syindex with_output_to_chars/3 -@cnindex with_output_to_chars/3 - -Execute goal @var{Goal} such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the difference list of character codes -@var{Chars-Chars0}. - -@item with_output_to_chars(?@var{Goal}, -@var{Stream}, ?@var{Chars0}, -@var{Chars}) -@findex with_output_to_chars/4 -@syindex with_output_to_chars/4 -@cnindex with_output_to_chars/4 - -Execute goal @var{Goal} such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the difference list of character codes -@var{Chars-Chars0} and @var{Stream} receives the stream corresponding to -the memory buffer. - -@end table - -The implementation of the character IO operations relies on three YAP -built-ins: -@table @code - -@item charsio:open_mem_read_stream(+@var{String}, -@var{Stream}) -Store a string in a memory buffer and output a stream that reads from this -memory buffer. - -@item charsio:open_mem_write_stream(-@var{Stream}) -Create a new memory buffer and output a stream that writes to it. - -@item charsio:peek_mem_write_stream(-@var{Stream}, L0, L) -Convert the memory buffer associated with stream @var{Stream} to the -difference list of character codes @var{L-L0}. - -@end table -@noindent -These built-ins are initialized to belong to the module @code{charsio} in -@code{init.yap}. Novel procedures for manipulating strings by explicitly -importing these built-ins. - -YAP does not currently support opening a @code{charsio} stream in -@code{append} mode, or seeking in such a stream. - -@node System, Terms, String Input/Output, Library -@section Calling The Operating System from YAP -@cindex Operating System Utilities - -YAP now provides a library of system utilities compatible with the -SICStus Prolog system library. This library extends and to some point -replaces the functionality of Operating System access routines. The -library includes Unix/Linux and Win32 @code{C} code. They -are available through the @code{use_module(library(system))} command. - -@table @code - -@item datime(datime(-@var{Year}, -@var{Month}, -@var{DayOfTheMonth}, --@var{Hour}, -@var{Minute}, -@var{Second}) -@findex datime/1 -@syindex datime/1 -@cnindex datime/1 -The @code{datime/1} procedure returns the current date and time, with -information on @var{Year}, @var{Month}, @var{DayOfTheMonth}, -@var{Hour}, @var{Minute}, and @var{Second}. The @var{Hour} is returned -on local time. This function uses the WIN32 -@code{GetLocalTime} function or the Unix @code{localtime} function. - -@example - ?- datime(X). - -X = datime(2001,5,28,15,29,46) ? -@end example - -@item mktime(datime(+@var{Year}, +@var{Month}, +@var{DayOfTheMonth}, -+@var{Hour}, +@var{Minute}, +@var{Second}), -@var{Seconds}) -@findex mktime/2 -@snindex mktime/2 -@cnindex mktime/2 -The @code{mktime/1} procedure returns the number of @var{Seconds} -elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time -(UTC). The user provides information on @var{Year}, @var{Month}, -@var{DayOfTheMonth}, @var{Hour}, @var{Minute}, and @var{Second}. The -@var{Hour} is given on local time. This function uses the WIN32 -@code{GetLocalTime} function or the Unix @code{mktime} function. - -@example - ?- mktime(datime(2001,5,28,15,29,46),X). - -X = 991081786 ? ; -@end example - -@item delete_file(+@var{File}) -@findex delete_file/1 -@syindex delete_file/1 -@cnindex delete_file/1 -The @code{delete_file/1} procedure removes file @var{File}. If -@var{File} is a directory, remove the directory @emph{and all its subdirectories}. - -@example - ?- delete_file(x). -@end example - -@item delete_file(+@var{File},+@var{Opts}) -@findex delete_file/2 -@syindex delete_file/2 -@cnindex delete_file/2 -The @code{delete_file/2} procedure removes file @var{File} according to -options @var{Opts}. These options are @code{directory} if one should -remove directories, @code{recursive} if one should remove directories -recursively, and @code{ignore} if errors are not to be reported. - -This example is equivalent to using the @code{delete_file/1} predicate: -@example - ?- delete_file(x, [recursive]). -@end example - - -@item directory_files(+@var{Dir},+@var{List}) -@findex directory_files/2 -@syindex directory_files/2 -@cnindex directory_files/2 -Given a directory @var{Dir}, @code{directory_files/2} procedures a -listing of all files and directories in the directory: -@example - ?- directory_files('.',L), writeq(L). -['Makefile.~1~','sys.so','Makefile','sys.o',x,..,'.'] -@end example -The predicates uses the @code{dirent} family of routines in Unix -environments, and @code{findfirst} in WIN32. - -@item file_exists(+@var{File}) -@findex file_exists/1 -@syindex file_exists/1 -@cnindex file_exists/1 -The atom @var{File} corresponds to an existing file. - -@item file_exists(+@var{File},+@var{Permissions}) -@findex file_exists/2 -@syindex file_exists/2 -@cnindex file_exists/2 -The atom @var{File} corresponds to an existing file with permissions -compatible with @var{Permissions}. YAP currently only accepts for -permissions to be described as a number. The actual meaning of this -number is Operating System dependent. - -@item file_property(+@var{File},?@var{Property}) -@findex file_property/2 -@syindex file_property/2 -@cnindex file_property/2 -The atom @var{File} corresponds to an existing file, and @var{Property} -will be unified with a property of this file. The properties are of the -form @code{type(@var{Type})}, which gives whether the file is a regular -file, a directory, a fifo file, or of unknown type; -@code{size(@var{Size})}, with gives the size for a file, and -@code{mod_time(@var{Time})}, which gives the last time a file was -modified according to some Operating System dependent -timestamp; @code{mode(@var{mode})}, gives the permission flags for the -file, and @code{linkto(@var{FileName})}, gives the file pointed to by a -symbolic link. Properties can be obtained through backtracking: - -@example - ?- file_property('Makefile',P). - -P = type(regular) ? ; - -P = size(2375) ? ; - -P = mod_time(990826911) ? ; - -no -@end example - -@item make_directory(+@var{Dir}) -@findex make_directory/2 -@syindex make_directory/2 -@cnindex make_directory/2 -Create a directory @var{Dir}. The name of the directory must be an atom. - -@item rename_file(+@var{OldFile},+@var{NewFile}) -@findex rename_file/2 -@syindex rename_file/2 -@cnindex rename_file/2 -Create file @var{OldFile} to @var{NewFile}. This predicate uses the -@code{C} built-in function @code{rename}. - - -@item environ(?@var{EnvVar},+@var{EnvValue}) -@findex sys_environ/2 -@syindex sys_environ/2 -@cnindex sys_environ/2 -Unify environment variable @var{EnvVar} with its value @var{EnvValue}, -if there is one. This predicate is backtrackable in Unix systems, but -not currently in Win32 configurations. - -@example - ?- environ('HOME',X). - -X = 'C:\\cygwin\\home\\administrator' ? -@end example - -@item host_id(-@var{Id}) -@findex host_id/1 -@syindex host_id/1 -@cnindex host_id/1 - -Unify @var{Id} with an identifier of the current host. YAP uses the -@code{hostid} function when available, - -@item host_name(-@var{Name}) -@findex host_name/1 -@syindex host_name/1 -@cnindex host_name/1 - -Unify @var{Name} with a name for the current host. YAP uses the -@code{hostname} function in Unix systems when available, and the -@code{GetComputerName} function in WIN32 systems. - -@item kill(@var{Id},+@var{SIGNAL}) -@findex kill/2 -@syindex kill/2 -@cnindex kill/2 - -Send signal @var{SIGNAL} to process @var{Id}. In Unix this predicate is -a direct interface to @code{kill} so one can send signals to groups of -processes. In WIN32 the predicate is an interface to -@code{TerminateProcess}, so it kills @var{Id} independently of @var{SIGNAL}. - -@item mktemp(@var{Spec},-@var{File}) -@findex mktemp/2 -@syindex mktemp/2 -@cnindex mktemp/2 - -Direct interface to @code{mktemp}: given a @var{Spec}, that is a file -name with six @var{X} to it, create a file name @var{File}. Use -@code{tmpnam/1} instead. - -@item pid(-@var{Id}) -@findex pid/1 -@syindex pid/1 -@cnindex pid/1 - -Unify @var{Id} with the process identifier for the current -process. An interface to the @t{getpid} function. - -@item tmpnam(-@var{File}) -@findex tmpnam/1 -@syindex tmpnam/1 -@cnindex tmpnam/1 - -Interface with @var{tmpnam}: obtain a new, unique file name @var{File}. - -@item tmp_file(-@var{File}) -@findex tmp_file/2 -@snindex tmp_file/2 -@cnindex tmp_file/2 - -Create a name for a temporary file. @var{Base} is an user provided -identifier for the category of file. The @var{TmpName} is guaranteed to -be unique. If the system halts, it will automatically remove all created -temporary files. - - -@item exec(+@var{Command},[+@var{InputStream},+@var{OutputStream},+@var{ErrorStream}],-@var{PID}) -@findex exec/3 -@syindex exec/3 -@cnindex exec/3 -Execute command @var{Command} with its streams connected to -@var{InputStream}, @var{OutputStream}, and @var{ErrorStream}. The -process that executes the command is returned as @var{PID}. The -command is executed by the default shell @code{bin/sh -c} in Unix. - -The following example demonstrates the use of @code{exec/3} to send a -command and process its output: - -@example -exec(ls,[std,pipe(S),null],P),repeat, get0(S,C), (C = -1, close(S) ! ; put(C)). -@end example - -The streams may be one of standard stream, @code{std}, null stream, -@code{null}, or @code{pipe(S)}, where @var{S} is a pipe stream. Note -that it is up to the user to close the pipe. - -@item popen(+@var{Command}, +@var{TYPE}, -@var{Stream}) -@findex popen/3 -@syindex popen/3 -@cnindex popen/3 -Interface to the @t{popen} function. It opens a process by creating a -pipe, forking and invoking @var{Command} on the current shell. Since a -pipe is by definition unidirectional the @var{Type} argument may be -@code{read} or @code{write}, not both. The stream should be closed -using @code{close/1}, there is no need for a special @code{pclose} -command. - -The following example demonstrates the use of @code{popen/3} to process -the output of a command, as @code{exec/3} would do: - -@pl_example - ?- popen(ls,read,X),repeat, get0(X,C), (C = -1, ! ; put(C)). - -X = 'C:\\cygwin\\home\\administrator' ? -@end pl_example - - -The WIN32 implementation of @code{popen/3} relies on @code{exec/3}. - -@item shell -@findex shell/0 -@syindex shell/0 -@cnindex shell/0 -Start a new shell and leave YAP in background until the shell -completes. YAP uses the shell given by the environment variable -@code{SHELL}. In WIN32 environment YAP will use @code{COMSPEC} if -@code{SHELL} is undefined. - -@item shell(+@var{Command}) -@findex shell/1 -@syindex shell/1 -@cnindex shell/1 -Execute command @var{Command} under a new shell. YAP will be in -background until the command completes. In Unix environments YAP uses -the shell given by the environment variable @code{SHELL} with the option -@code{" -c "}. In WIN32 environment YAP will use @code{COMSPEC} if -@code{SHELL} is undefined, in this case with the option @code{" /c "}. - -@item shell(+@var{Command},-@var{Status}) -@findex shell/2 -@syindex shell/2 -@cnindex shell/2 -Execute command @var{Command} under a new shell and unify @var{Status} -with the exit for the command. YAP will be in background until the -command completes. In Unix environments YAP uses the shell given by the -environment variable @code{SHELL} with the option @code{" -c "}. In -WIN32 environment YAP will use @code{COMSPEC} if @code{SHELL} is -undefined, in this case with the option @code{" /c "}. - -@item sleep(+@var{Time}) -@findex sleep/1 -@syindex sleep/1 -@cnindex sleep/1 -Block the current thread for @var{Time} seconds. When YAP is compiled -without multi-threading support, this predicate blocks the YAP process. -The number of seconds must be a positive number, and it may an integer -or a float. The Unix implementation uses @code{usleep} if the number of -seconds is below one, and @code{sleep} if it is over a second. The WIN32 -implementation uses @code{Sleep} for both cases. - -@item system -@findex system/0 -@syindex system/0 -@cnindex system/0 -Start a new default shell and leave YAP in background until the shell -completes. YAP uses @code{/bin/sh} in Unix systems and @code{COMSPEC} in -WIN32. - -@item system(+@var{Command},-@var{Res}) -@findex system/2 -@syindex system/2 -@cnindex system/2 -Interface to @code{system}: execute command @var{Command} and unify -@var{Res} with the result. - -@item wait(+@var{PID},-@var{Status}) -@findex wait/2 -@syindex wait/2 -@cnindex wait/2 -Wait until process @var{PID} terminates, and return its exits @var{Status}. - -@end table - - -@node Terms, Tries, System, Library -@section Utilities On Terms -@cindex utilities on terms - -The next routines provide a set of commonly used utilities to manipulate -terms. Most of these utilities have been implemented in @code{C} for -efficiency. They are available through the -@code{use_module(library(terms))} command. - -@table @code - -@item cyclic_term(?@var{Term}) -@findex cyclic_term/1 -@syindex cyclic_term/1 -@cnindex cyclic_term/1 -Succeed if the argument @var{Term} is not a cyclic term. - -@item term_hash(+@var{Term}, ?@var{Hash}) -@findex term_hash/2 -@syindex term_hash/2 -@cnindex term_hash/2 - -If @var{Term} is ground unify @var{Hash} with a positive integer -calculated from the structure of the term. Otherwise the argument -@var{Hash} is left unbound. The range of the positive integer is from -@code{0} to, but not including, @code{33554432}. - -@item term_hash(+@var{Term}, +@var{Depth}, +@var{Range}, ?@var{Hash}) -@findex term_hash/4 -@syindex term_hash/4 -@cnindex term_hash/4 - -Unify @var{Hash} with a positive integer calculated from the structure -of the term. The range of the positive integer is from @code{0} to, but -not including, @var{Range}. If @var{Depth} is @code{-1} the whole term -is considered. Otherwise, the term is considered only up to depth -@code{1}, where the constants and the principal functor have depth -@code{1}, and an argument of a term with depth @var{I} has depth @var{I+1}. - -@item variables_within_term(+@var{Variables},?@var{Term}, -@var{OutputVariables}) -@findex variables_within_term/3 -@snindex variables_within_term/3 -@cnindex variables_within_term/3 - -Unify @var{OutputVariables} with the subset of the variables @var{Variables} that occurs in @var{Term}. - -@item new_variables_in_term(+@var{Variables},?@var{Term}, -@var{OutputVariables}) -@findex new_variables_in_term/3 -@snindex new_variables_in_term/3 -@cnindex new_variables_in_term/3 - -Unify @var{OutputVariables} with all variables occurring in @var{Term} that are not in the list @var{Variables}. - -@item variant(?@var{Term1}, ?@var{Term2}) -@findex variant/2 -@syindex variant/2 -@cnindex variant/2 - -Succeed if @var{Term1} and @var{Term2} are variant terms. - -@item subsumes(?@var{Term1}, ?@var{Term2}) -@findex subsumes/2 -@syindex subsumes/2 -@cnindex subsumes/2 - -Succeed if @var{Term1} subsumes @var{Term2}. Variables in term -@var{Term1} are bound so that the two terms become equal. - - -@item subsumes_chk(?@var{Term1}, ?@var{Term2}) -@findex subsumes_chk/2 -@syindex subsumes_chk/2 -@cnindex subsumes_chk/2 - -Succeed if @var{Term1} subsumes @var{Term2} but does not bind any -variable in @var{Term1}. - -@item variable_in_term(?@var{Term},?@var{Var}) -@findex variable_in_term/2 -@snindex variable_in_term/2 -@cnindex variable_in_term/2 -Succeed if the second argument @var{Var} is a variable and occurs in -term @var{Term}. - -@item unifiable(?@var{Term1}, ?@var{Term2}, -@var{Bindings}) -@findex unifiable/3 -@syindex unifiable/3 -@cnindex unifiable/3 - -Succeed if @var{Term1} and @var{Term2} are unifiable with substitution -@var{Bindings}. - -@end table - -@node Tries, Cleanup, Terms, Library -@section Trie DataStructure -@cindex tries - -The next routines provide a set of utilities to create and manipulate -prefix trees of Prolog terms. Tries were originally proposed to -implement tabling in Logic Programming, but can be used for other -purposes. The tries will be stored in the Prolog database and can seen -as alternative to @code{assert} and @code{record} family of -primitives. Most of these utilities have been implemented in @code{C} -for efficiency. They are available through the -@code{use_module(library(tries))} command. - -@table @code -@item trie_open(-@var{Id}) -@findex trie_open/1 -@snindex trie_open/1 -@cnindex trie_open/1 - -Open a new trie with identifier @var{Id}. - -@item trie_close(+@var{Id}) -@findex trie_close/1 -@snindex trie_close/1 -@cnindex trie_close/1 - -Close trie with identifier @var{Id}. - -@item trie_close_all -@findex trie_close_all/0 -@snindex trie_close_all/0 -@cnindex trie_close_all/0 - -Close all available tries. - -@item trie_mode(?@var{Mode}) -@findex trie_mode/1 -@snindex trie_mode/1 -@cnindex trie_mode/1 - -Unify @var{Mode} with trie operation mode. Allowed values are either -@code{std} (default) or @code{rev}. - -@item trie_put_entry(+@var{Trie},+@var{Term},-@var{Ref}) -@findex trie_put_entry/3 -@snindex trie_put_entry/3 -@cnindex trie_put_entry/3 - -Add term @var{Term} to trie @var{Trie}. The handle @var{Ref} gives -a reference to the term. - -@item trie_check_entry(+@var{Trie},+@var{Term},-@var{Ref}) -@findex trie_check_entry/3 -@snindex trie_check_entry/3 -@cnindex trie_check_entry/3 - -Succeeds if a variant of term @var{Term} is in trie @var{Trie}. An handle - @var{Ref} gives a reference to the term. - -@item trie_get_entry(+@var{Ref},-@var{Term}) -@findex trie_get_entry/2 -@snindex trie_get_entry/2 -@cnindex trie_get_entry/2 -Unify @var{Term} with the entry for handle @var{Ref}. - -@item trie_remove_entry(+@var{Ref}) -@findex trie_remove_entry/1 -@snindex trie_remove_entry/1 -@cnindex trie_remove_entry/1 - -Remove entry for handle @var{Ref}. - -@item trie_remove_subtree(+@var{Ref}) -@findex trie_remove_subtree/1 -@snindex trie_remove_subtree/1 -@cnindex trie_remove_subtree/1 - -Remove subtree rooted at handle @var{Ref}. - -@item trie_save(+@var{Trie},+@var{FileName}) -@findex trie_save/2 -@snindex trie_save/2 -@cnindex trie_save/2 -Dump trie @var{Trie} into file @var{FileName}. - - -@item trie_load(+@var{Trie},+@var{FileName}) -@findex trie_load/2 -@snindex trie_load/2 -@cnindex trie_load/2 -Load trie @var{Trie} from the contents of file @var{FileName}. - -@item trie_stats(-@var{Memory},-@var{Tries},-@var{Entries},-@var{Nodes}) -@findex trie_stats/4 -@snindex trie_stats/4 -@cnindex trie_stats/4 -Give generic statistics on tries, including the amount of memory, -@var{Memory}, the number of tries, @var{Tries}, the number of entries, -@var{Entries}, and the total number of nodes, @var{Nodes}. - -@item trie_max_stats(-@var{Memory},-@var{Tries},-@var{Entries},-@var{Nodes}) -@findex trie_max_stats/4 -@snindex trie_max_stats/4 -@cnindex trie_max_stats/4 -Give maximal statistics on tries, including the amount of memory, -@var{Memory}, the number of tries, @var{Tries}, the number of entries, -@var{Entries}, and the total number of nodes, @var{Nodes}. - - -@item trie_usage(+@var{Trie},-@var{Entries},-@var{Nodes},-@var{VirtualNodes}) -@findex trie_usage/4 -@snindex trie_usage/4 -@cnindex trie_usage/4 -Give statistics on trie @var{Trie}, the number of entries, -@var{Entries}, and the total number of nodes, @var{Nodes}, and the -number of @var{VirtualNodes}. - -@item trie_print(+@var{Trie}) -@findex trie_print/1 -@snindex trie_print/1 -@cnindex trie_print/1 -Print trie @var{Trie} on standard output. - - - - -@end table - - -@node Cleanup, Timeout, Tries, Library -@section Call Cleanup -@cindex cleanup - -@t{call_cleanup/1} and @t{call_cleanup/2} allow predicates to register -code for execution after the call is finished. Predicates can be -declared to be @t{fragile} to ensure that @t{call_cleanup} is called -for any Goal which needs it. This library is loaded with the -@code{use_module(library(cleanup))} command. - -@table @code -@item :- fragile @var{P},....,@var{Pn} -@findex fragile -@syindex fragile -@cnindex fragile -Declares the predicate @var{P}=@t{[module:]name/arity} as a fragile -predicate, module is optional, default is the current -typein_module. Whenever such a fragile predicate is used in a query -it will be called through call_cleanup/1. -@pl_example -:- fragile foo/1,bar:baz/2. -@end pl_example - -@item call_cleanup(:@var{Goal}) -@findex call_cleanup/1 -@syindex call_cleanup/1 -@cnindex call_cleanup/1 -Execute goal @var{Goal} within a cleanup-context. Called predicates -might register cleanup Goals which are called right after the end of -the call to @var{Goal}. Cuts and exceptions inside Goal do not prevent the -execution of the cleanup calls. @t{call_cleanup} might be nested. - -@item call_cleanup(:@var{Goal}, :@var{CleanUpGoal}) -@findex call_cleanup/2 -@syindex call_cleanup/2 -@cnindex call_cleanup/2 -This is similar to @t{call_cleanup/1} with an additional -@var{CleanUpGoal} which gets called after @var{Goal} is finished. - -@item setup_call_cleanup(:@var{Setup},:@var{Goal}, :@var{CleanUpGoal}) -@findex setup_call_cleanup/3 -@snindex setup_call_cleanup/3 -@cnindex setup_call_cleanup/3 -Calls @code{(Setup, Goal)}. For each sucessful execution of @var{Setup}, calling @var{Goal}, the -cleanup handler @var{Cleanup} is guaranteed to be called exactly once. -This will happen after @var{Goal} completes, either through failure, -deterministic success, commit, or an exception. @var{Setup} will -contain the goals that need to be protected from asynchronous interrupts -such as the ones received from @code{call_with_time_limit/2} or @code{thread_signal/2}. In -most uses, @var{Setup} will perform temporary side-effects required by -@var{Goal} that are finally undone by @var{Cleanup}. - -Success or failure of @var{Cleanup} is ignored and choice-points it -created are destroyed (as @code{once/1}). If @var{Cleanup} throws an exception, -this is executed as normal. - -Typically, this predicate is used to cleanup permanent data storage -required to execute @var{Goal}, close file-descriptors, etc. The example -below provides a non-deterministic search for a term in a file, closing -the stream as needed. - -@pl_example -term_in_file(Term, File) :- - setup_call_cleanup(open(File, read, In), - term_in_stream(Term, In), - close(In) ). - -term_in_stream(Term, In) :- - repeat, - read(In, T), - ( T == end_of_file - -> !, fail - ; T = Term - ). -@end pl_example - -Note that it is impossible to implement this predicate in Prolog other than -by reading all terms into a list, close the file and call @code{member/2}. -Without @code{setup_call_cleanup/3} there is no way to gain control if the -choice-point left by @code{repeat} is removed by a cut or an exception. - -@code{setup_call_cleanup/2} can also be used to test determinism of a goal: - -@example -?- setup_call_cleanup(true,(X=1;X=2), Det=yes). - -X = 1 ; - -X = 2, -Det = yes ; -@end example - -This predicate is under consideration for inclusion into the ISO standard. -For compatibility with other Prolog implementations see @code{call_cleanup/2}. - - @item setup_call_catcher_cleanup(:@var{Setup},:@var{Goal}, +@var{Catcher},:@var{CleanUpGoal}) -@findex setup_call_catcher_cleanup/4 -@snindex setup_call_catcher_cleanup/4 -@cnindex setup_call_catcher_cleanup/4 -Similar to @code{setup_call_cleanup(@var{Setup}, @var{Goal}, @var{Cleanup})} with -additional information on the reason of calling @var{Cleanup}. Prior -to calling @var{Cleanup}, @var{Catcher} unifies with the termination -code. If this unification fails, @var{Cleanup} is -@strong{not} called. - - -@item on_cleanup(+@var{CleanUpGoal}) -@findex on_cleanup/1 -@syindex on_cleanup/1 -@cnindex on_cleanup/1 -Any Predicate might registers a @var{CleanUpGoal}. The -@var{CleanUpGoal} is put onto the current cleanup context. All such -CleanUpGoals are executed in reverse order of their registration when -the surrounding cleanup-context ends. This call will throw an exception -if a predicate tries to register a @var{CleanUpGoal} outside of any -cleanup-context. - -@item cleanup_all -@findex cleanup_all/0 -@syindex cleanup_all/0 -@cnindex cleanup_all/0 -Calls all pending CleanUpGoals and resets the cleanup-system to an -initial state. Should only be used as one of the last calls in the -main program. - -@end table - -There are some private predicates which could be used in special -cases, such as manually setting up cleanup-contexts and registering -CleanUpGoals for other than the current cleanup-context. -Read the Source Luke. - - -@node Timeout, Trees, Cleanup, Library -@section Calls With Timeout -@cindex timeout - -The @t{time_out/3} command relies on the @t{alarm/3} built-in to -implement a call with a maximum time of execution. The command is -available with the @code{use_module(library(timeout))} command. - -@table @code - - -@item time_out(+@var{Goal}, +@var{Timeout}, -@var{Result}) -@findex time_out/3 -@syindex time_out/3 -@cnindex time_out/3 -Execute goal @var{Goal} with time limited @var{Timeout}, where -@var{Timeout} is measured in milliseconds. If the goal succeeds, unify -@var{Result} with success. If the timer expires before the goal -terminates, unify @var{Result} with @t{time_out}. - -This command is implemented by activating an alarm at procedure -entry. If the timer expires before the goal completes, the alarm will -throw an exception @var{timeout}. - -One should note that @code{time_out/3} is not reentrant, that is, a goal -called from @code{time_out} should never itself call -@code{time_out/3}. Moreover, @code{time_out/3} will deactivate any previous -alarms set by @code{alarm/3} and vice-versa, hence only one of these -calls should be used in a program. - -Last, even though the timer is set in milliseconds, the current -implementation relies on @t{alarm/3}, and therefore can only offer -precision on the scale of seconds. - -@end table - -@node Trees, UGraphs, Timeout, Library -@section Updatable Binary Trees -@cindex updatable tree - -The following queue manipulation routines are available once -included with the @code{use_module(library(trees))} command. - -@table @code - -@item get_label(+@var{Index}, +@var{Tree}, ?@var{Label}) -@findex get_label/3 -@syindex get_label/3 -@cnindex get_label/3 -Treats the tree as an array of @var{N} elements and returns the -@var{Index}-th. - -@item list_to_tree(+@var{List}, -@var{Tree}) -@findex list_to_tree/2 -@syindex list_to_tree/2 -@cnindex list_to_tree/2 -Takes a given @var{List} of @var{N} elements and constructs a binary -@var{Tree}. - -@item map_tree(+@var{Pred}, +@var{OldTree}, -@var{NewTree}) -@findex map_tree/3 -@syindex map_tree/3 -@cnindex map_tree/3 -Holds when @var{OldTree} and @var{NewTree} are binary trees of the same shape -and @code{Pred(Old,New)} is true for corresponding elements of the two trees. - -@item put_label(+@var{Index}, +@var{OldTree}, +@var{Label}, -@var{NewTree}) -@findex put_label/4 -@syindex put_label/4 -@cnindex put_label/4 -constructs a new tree the same shape as the old which moreover has the -same elements except that the @var{Index}-th one is @var{Label}. - -@item tree_size(+@var{Tree}, -@var{Size}) -@findex tree_size/2 -@syindex tree_size/2 -@cnindex tree_size/2 -Calculates the number of elements in the @var{Tree}. - -@item tree_to_list(+@var{Tree}, -@var{List}) -@findex tree_to_list/2 -@syindex tree_to_list/2 -@cnindex tree_to_list/2 -Is the converse operation to list_to_tree. - -@end table - -@node UGraphs, DGraphs, Trees, Library -@section Unweighted Graphs -@cindex unweighted graphs - -The following graph manipulation routines are based in code originally -written by Richard O'Keefe. The code was then extended to be compatible -with the SICStus Prolog ugraphs library. The routines assume directed -graphs, undirected graphs may be implemented by using two edges. Graphs -are represented in one of two ways: - -@itemize @bullet -@item The P-representation of a graph is a list of (from-to) vertex -pairs, where the pairs can be in any old order. This form is -convenient for input/output. - -@item The S-representation of a graph is a list of (vertex-neighbors) -pairs, where the pairs are in standard order (as produced by keysort) -and the neighbors of each vertex are also in standard order (as -produced by sort). This form is convenient for many calculations. -@end itemize - -These built-ins are available once included with the -@code{use_module(library(ugraphs))} command. - -@table @code - -@item vertices_edges_to_ugraph(+@var{Vertices}, +@var{Edges}, -@var{Graph}) -@findex vertices_edges_to_ugraph/3 -@syindex vertices_edges_to_ugraph/3 -@cnindex vertices_edges_to_ugraph/3 -Given a graph with a set of vertices @var{Vertices} and a set of edges -@var{Edges}, @var{Graph} must unify with the corresponding -s-representation. Note that the vertices without edges will appear in -@var{Vertices} but not in @var{Edges}. Moreover, it is sufficient for a -vertex to appear in @var{Edges}. -@pl_example -?- vertices_edges_to_ugraph([],[1-3,2-4,4-5,1-5],L). - -L = [1-[3,5],2-[4],3-[],4-[5],5-[]] ? - -@end pl_example -In this case all edges are defined implicitly. The next example shows -three unconnected edges: -@pl_example -?- vertices_edges_to_ugraph([6,7,8],[1-3,2-4,4-5,1-5],L). - -L = [1-[3,5],2-[4],3-[],4-[5],5-[],6-[],7-[],8-[]] ? - -@end pl_example - -@item vertices(+@var{Graph}, -@var{Vertices}) -@findex vertices/2 -@syindex vertices/2 -@cnindex vertices/2 -Unify @var{Vertices} with all vertices appearing in graph -@var{Graph}. In the next example: -@pl_example -?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). - -L = [1,2,3,4,5] -@end pl_example - -@item edges(+@var{Graph}, -@var{Edges}) -@findex edges/2 -@syindex edges/2 -@cnindex edges/2 -Unify @var{Edges} with all edges appearing in graph -@var{Graph}. In the next example: -@pl_example -?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). - -L = [1,2,3,4,5] -@end pl_example - -@item add_vertices(+@var{Graph}, +@var{Vertices}, -@var{NewGraph}) -@findex add_vertices/3 -@syindex add_vertices/3 -@cnindex add_vertices/3 -Unify @var{NewGraph} with a new graph obtained by adding the list of -vertices @var{Vertices} to the graph @var{Graph}. In the next example: -@pl_example -?- add_vertices([1-[3,5],2-[4],3-[],4-[5], - 5-[],6-[],7-[],8-[]], - [0,2,9,10,11], - NG). - -NG = [0-[],1-[3,5],2-[4],3-[],4-[5],5-[], - 6-[],7-[],8-[],9-[],10-[],11-[]] -@end pl_example - -@item del_vertices(+@var{Graph}, +@var{Vertices}, -@var{NewGraph}) -@findex del_vertices/3 -@syindex del_vertices/3 -@cnindex del_vertices/3 -Unify @var{NewGraph} with a new graph obtained by deleting the list of -vertices @var{Vertices} and all the edges that start from or go to a -vertex in @var{Vertices} to the graph @var{Graph}. In the next example: -@pl_example -?- del_vertices([2,1],[1-[3,5],2-[4],3-[], - 4-[5],5-[],6-[],7-[2,6],8-[]],NL). - -NL = [3-[],4-[5],5-[],6-[],7-[6],8-[]] -@end pl_example - -@item add_edges(+@var{Graph}, +@var{Edges}, -@var{NewGraph}) -@findex add_edges/3 -@syindex add_edges/3 -@cnindex add_edges/3 -Unify @var{NewGraph} with a new graph obtained by adding the list of -edges @var{Edges} to the graph @var{Graph}. In the next example: -@pl_example -?- add_edges([1-[3,5],2-[4],3-[],4-[5],5-[],6-[], - 7-[],8-[]],[1-6,2-3,3-2,5-7,3-2,4-5],NL). - -NL = [1-[3,5,6],2-[3,4],3-[2],4-[5],5-[7],6-[],7-[],8-[]] -@end pl_example - -@item del_edges(+@var{Graph}, +@var{Edges}, -@var{NewGraph}) -@findex del_edges/3 -@syindex del_edges/3 -@cnindex del_edges/3 -Unify @var{NewGraph} with a new graph obtained by removing the list of -edges @var{Edges} from the graph @var{Graph}. Notice that no vertices -are deleted. In the next example: -@pl_example -?- del_edges([1-[3,5],2-[4],3-[],4-[5],5-[], - 6-[],7-[],8-[]], - [1-6,2-3,3-2,5-7,3-2,4-5,1-3],NL). - -NL = [1-[5],2-[4],3-[],4-[],5-[],6-[],7-[],8-[]] -@end pl_example - -@item transpose(+@var{Graph}, -@var{NewGraph}) -@findex transpose/3 -@syindex transpose/3 -@cnindex transpose/3 -Unify @var{NewGraph} with a new graph obtained from @var{Graph} by -replacing all edges of the form @var{V1-V2} by edges of the form -@var{V2-V1}. The cost is @code{O(|V|^2)}. In the next example: -@pl_example -?- transpose([1-[3,5],2-[4],3-[], - 4-[5],5-[],6-[],7-[],8-[]], NL). - -NL = [1-[],2-[],3-[1],4-[2],5-[1,4],6-[],7-[],8-[]] -@end pl_example -Notice that an undirected graph is its own transpose. - -@item neighbors(+@var{Vertex}, +@var{Graph}, -@var{Vertices}) -@findex neighbors/3 -@syindex neighbors/3 -@cnindex neighbors/3 -Unify @var{Vertices} with the list of neighbors of vertex @var{Vertex} -in @var{Graph}. If the vertice is not in the graph fail. In the next -example: -@pl_example -?- neighbors(4,[1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], - NL). - -NL = [1,2,7,5] -@end pl_example - -@item neighbours(+@var{Vertex}, +@var{Graph}, -@var{Vertices}) -@findex neighbours/3 -@syindex neighbours/3 -@cnindex neighbours/3 -Unify @var{Vertices} with the list of neighbours of vertex @var{Vertex} -in @var{Graph}. In the next example: -@pl_example -?- neighbours(4,[1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). - -NL = [1,2,7,5] -@end pl_example - -@item complement(+@var{Graph}, -@var{NewGraph}) -@findex complement/2 -@syindex complement/2 -@cnindex complement/2 -Unify @var{NewGraph} with the graph complementary to @var{Graph}. - In the next example: -@pl_example -?- complement([1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). - -NL = [1-[2,4,6,7,8],2-[1,3,5,6,7,8],3-[1,2,4,5,6,7,8], - 4-[3,5,6,8],5-[1,2,3,4,6,7,8],6-[1,2,3,4,5,7,8], - 7-[1,2,3,4,5,6,8],8-[1,2,3,4,5,6,7]] -@end pl_example - -@item compose(+@var{LeftGraph}, +@var{RightGraph}, -@var{NewGraph}) -@findex compose/3 -@syindex compose/3 -@cnindex compose/3 -Compose the graphs @var{LeftGraph} and @var{RightGraph} to form @var{NewGraph}. - In the next example: -@pl_example -?- compose([1-[2],2-[3]],[2-[4],3-[1,2,4]],L). - -L = [1-[4],2-[1,2,4],3-[]] -@end pl_example - -@item top_sort(+@var{Graph}, -@var{Sort}) -@findex top_sort/2 -@syindex top_sort/2 -@cnindex top_sort/2 -Generate the set of nodes @var{Sort} as a topological sorting of graph -@var{Graph}, if one is possible. - In the next example we show how topological sorting works for a linear graph: -@pl_example -?- top_sort([_138-[_219],_219-[_139], _139-[]],L). - -L = [_138,_219,_139] -@end pl_example - -@item top_sort(+@var{Graph}, -@var{Sort0}, -@var{Sort}) -@findex top_sort/3 -@syindex top_sort/3 -@cnindex top_sort/3 -Generate the difference list @var{Sort}-@var{Sort0} as a topological -sorting of graph @var{Graph}, if one is possible. - -@item transitive_closure(+@var{Graph}, +@var{Closure}) -@findex transitive_closure/2 -@syindex transitive_closure/2 -@cnindex transitive_closure/2 -Generate the graph @var{Closure} as the transitive closure of graph -@var{Graph}. - In the next example: -@pl_example -?- transitive_closure([1-[2,3],2-[4,5],4-[6]],L). - -L = [1-[2,3,4,5,6],2-[4,5,6],4-[6]] -@end pl_example - -@item reachable(+@var{Node}, +@var{Graph}, -@var{Vertices}) -@findex reachable/3 -@syindex reachable/3 -@cnindex reachable/3 -Unify @var{Vertices} with the set of all vertices in graph -@var{Graph} that are reachable from @var{Node}. In the next example: -@pl_example -?- reachable(1,[1-[3,5],2-[4],3-[],4-[5],5-[]],V). - -V = [1,3,5] -@end pl_example - -@end table - -@node DGraphs, UnDGraphs, UGraphs, Library -@section Directed Graphs -@cindex Efficient Directed Graphs - -The following graph manipulation routines use the red-black tree library -to try to avoid linear-time scans of the graph for all graph -operations. Graphs are represented as a red-black tree, where the key is -the vertex, and the associated value is a list of vertices reachable -from that vertex through an edge (ie, a list of edges). - -@table @code - -@item dgraph_new(+@var{Graph}) -@findex dgraph_new/1 -@snindex dgraph_new/1 -@cnindex dgraph_new/1 -Create a new directed graph. This operation must be performed before -trying to use the graph. - -@item dgraph_vertices(+@var{Graph}, -@var{Vertices}) -@findex dgraph_vertices/2 -@snindex dgraph_vertices/2 -@cnindex dgraph_vertices/2 -Unify @var{Vertices} with all vertices appearing in graph -@var{Graph}. - -@item dgraph_edge(+@var{N1}, +@var{N2}, +@var{Graph}) -@findex dgraph_edge/2 -@snindex dgraph_edge/2 -@cnindex dgraph_edge/2 -Edge @var{N1}-@var{N2} is an edge in directed graph @var{Graph}. - -@item dgraph_edges(+@var{Graph}, -@var{Edges}) -@findex dgraph_edges/2 -@snindex dgraph_edges/2 -@cnindex dgraph_edges/2 -Unify @var{Edges} with all edges appearing in graph -@var{Graph}. - -@item dgraph_add_vertices(+@var{Graph}, +@var{Vertex}, -@var{NewGraph}) -@findex dgraph_add_vertex/3 -@snindex dgraph_add_vertex/3 -@cnindex dgraph_add_vertex/3 -Unify @var{NewGraph} with a new graph obtained by adding -vertex @var{Vertex} to the graph @var{Graph}. - -@item dgraph_add_vertices(+@var{Graph}, +@var{Vertices}, -@var{NewGraph}) -@findex dgraph_add_vertices/3 -@snindex dgraph_add_vertices/3 -@cnindex dgraph_add_vertices/3 -Unify @var{NewGraph} with a new graph obtained by adding the list of -vertices @var{Vertices} to the graph @var{Graph}. - -@item dgraph_del_vertex(+@var{Graph}, +@var{Vertex}, -@var{NewGraph}) -@findex dgraph_del_vertex/3 -@syindex dgraph_del_vertex/3 -@cnindex dgraph_del_vertex/3 -Unify @var{NewGraph} with a new graph obtained by deleting vertex -@var{Vertex} and all the edges that start from or go to @var{Vertex} to -the graph @var{Graph}. - -@item dgraph_del_vertices(+@var{Graph}, +@var{Vertices}, -@var{NewGraph}) -@findex dgraph_del_vertices/3 -@syindex dgraph_del_vertices/3 -@cnindex dgraph_del_vertices/3 -Unify @var{NewGraph} with a new graph obtained by deleting the list of -vertices @var{Vertices} and all the edges that start from or go to a -vertex in @var{Vertices} to the graph @var{Graph}. - -@item dgraph_add_edge(+@var{Graph}, +@var{N1}, +@var{N2}, -@var{NewGraph}) -@findex dgraph_add_edge/4 -@snindex dgraph_add_edge/4 -@cnindex dgraph_add_edge/4 -Unify @var{NewGraph} with a new graph obtained by adding the edge -@var{N1}-@var{N2} to the graph @var{Graph}. - -@item dgraph_add_edges(+@var{Graph}, +@var{Edges}, -@var{NewGraph}) -@findex dgraph_add_edges/3 -@snindex dgraph_add_edges/3 -@cnindex dgraph_add_edges/3 -Unify @var{NewGraph} with a new graph obtained by adding the list of -edges @var{Edges} to the graph @var{Graph}. - -@item dgraph_del_edge(+@var{Graph}, +@var{N1}, +@var{N2}, -@var{NewGraph}) -@findex dgraph_del_edge/4 -@snindex dgraph_del_edge/4 -@cnindex dgraph_del_edge/4 -Succeeds if @var{NewGraph} unifies with a new graph obtained by -removing the edge @var{N1}-@var{N2} from the graph @var{Graph}. Notice -that no vertices are deleted. - -@item dgraph_del_edges(+@var{Graph}, +@var{Edges}, -@var{NewGraph}) -@findex dgraph_del_edges/3 -@snindex dgraph_del_edges/3 -@cnindex dgraph_del_edges/3 -Unify @var{NewGraph} with a new graph obtained by removing the list of -edges @var{Edges} from the graph @var{Graph}. Notice that no vertices -are deleted. - -@item dgraph_to_ugraph(+@var{Graph}, -@var{UGraph}) -@findex dgraph_to_ugraph/2 -@snindex dgraph_to_ugraph/2 -@cnindex dgraph_to_ugraph/2 -Unify @var{UGraph} with the representation used by the @var{ugraphs} -unweighted graphs library, that is, a list of the form -@var{V-Neighbors}, where @var{V} is a node and @var{Neighbors} the nodes -children. - -@item ugraph_to_dgraph( +@var{UGraph}, -@var{Graph}) -@findex ugraph_to_dgraph/2 -@snindex ugraph_to_dgraph/2 -@cnindex ugraph_to_dgraph/2 -Unify @var{Graph} with the directed graph obtain from @var{UGraph}, -represented in the form used in the @var{ugraphs} unweighted graphs -library. - -@item dgraph_neighbors(+@var{Vertex}, +@var{Graph}, -@var{Vertices}) -@findex dgraph_neighbors/3 -@snindex dgraph_neighbors/3 -@cnindex dgraph_neighbors/3 -Unify @var{Vertices} with the list of neighbors of vertex @var{Vertex} -in @var{Graph}. If the vertice is not in the graph fail. - -@item dgraph_neighbours(+@var{Vertex}, +@var{Graph}, -@var{Vertices}) -@findex dgraph_neighbours/3 -@snindex dgraph_neighbours/3 -@cnindex dgraph_neighbours/3 -Unify @var{Vertices} with the list of neighbours of vertex @var{Vertex} -in @var{Graph}. - -@item dgraph_complement(+@var{Graph}, -@var{NewGraph}) -@findex dgraph_complement/2 -@snindex dgraph_complement/2 -@cnindex dgraph_complement/2 -Unify @var{NewGraph} with the graph complementary to @var{Graph}. - -@item dgraph_transpose(+@var{Graph}, -@var{Transpose}) -@findex dgraph_transpose/2 -@snindex dgraph_transpose/2 -@cnindex dgraph_transpose/2 -Unify @var{NewGraph} with a new graph obtained from @var{Graph} by -replacing all edges of the form @var{V1-V2} by edges of the form -@var{V2-V1}. - -@item dgraph_compose(+@var{Graph1}, +@var{Graph2}, -@var{ComposedGraph}) -@findex dgraph_compose/3 -@snindex dgraph_compose/3 -@cnindex dgraph_compose/3 -Unify @var{ComposedGraph} with a new graph obtained by composing -@var{Graph1} and @var{Graph2}, ie, @var{ComposedGraph} has an edge -@var{V1-V2} iff there is a @var{V} such that @var{V1-V} in @var{Graph1} -and @var{V-V2} in @var{Graph2}. - -@item dgraph_transitive_closure(+@var{Graph}, -@var{Closure}) -@findex dgraph_transitive_closure/2 -@snindex dgraph_transitive_closure/2 -@cnindex dgraph_transitive_closure/2 -Unify @var{Closure} with the transitive closure of graph @var{Graph}. - -@item dgraph_symmetric_closure(+@var{Graph}, -@var{Closure}) -@findex dgraph_symmetric_closure/2 -@snindex dgraph_symmetric_closure/2 -@cnindex dgraph_symmetric_closure/2 -Unify @var{Closure} with the symmetric closure of graph @var{Graph}, -that is, if @var{Closure} contains an edge @var{U-V} it must also -contain the edge @var{V-U}. - -@item dgraph_top_sort(+@var{Graph}, -@var{Vertices}) -@findex dgraph_top_sort/2 -@snindex dgraph_top_sort/2 -@cnindex dgraph_top_sort/2 -Unify @var{Vertices} with the topological sort of graph @var{Graph}. - -@item dgraph_top_sort(+@var{Graph}, -@var{Vertices}, ?@var{Vertices0}) -@findex dgraph_top_sort/3 -@snindex dgraph_top_sort/3 -@cnindex dgraph_top_sort/3 -Unify the difference list @var{Vertices}-@var{Vertices0} with the -topological sort of graph @var{Graph}. - -@item dgraph_min_path(+@var{V1}, +@var{V1}, +@var{Graph}, -@var{Path}, ?@var{Costt}) -@findex dgraph_min_path/5 -@snindex dgraph_min_path/5 -@cnindex dgraph_min_path/5 -Unify the list @var{Path} with the minimal cost path between nodes -@var{N1} and @var{N2} in graph @var{Graph}. Path @var{Path} has cost -@var{Cost}. - -@item dgraph_max_path(+@var{V1}, +@var{V1}, +@var{Graph}, -@var{Path}, ?@var{Costt}) -@findex dgraph_max_path/5 -@snindex dgraph_max_path/5 -@cnindex dgraph_max_path/5 -Unify the list @var{Path} with the maximal cost path between nodes -@var{N1} and @var{N2} in graph @var{Graph}. Path @var{Path} has cost -@var{Cost}. - -@item dgraph_min_paths(+@var{V1}, +@var{Graph}, -@var{Paths}) -@findex dgraph_min_paths/3 -@snindex dgraph_min_paths/3 -@cnindex dgraph_min_paths/3 -Unify the list @var{Paths} with the minimal cost paths from node -@var{N1} to the nodes in graph @var{Graph}. - -@item dgraph_isomorphic(+@var{Vs}, +@var{NewVs}, +@var{G0}, -@var{GF}) -@findex dgraph_isomorphic/4 -@snindex dgraph_isomorphic/4 -@cnindex dgraph_isomorphic/4 -Unify the list @var{GF} with the graph isomorphic to @var{G0} where -vertices in @var{Vs} map to vertices in @var{NewVs}. - -@item dgraph_path(+@var{Vertex}, +@var{Graph}, ?@var{Path}) -@findex dgraph_path/3 -@snindex dgraph_path/3 -@cnindex dgraph_path/3 -The path @var{Path} is a path starting at vertex @var{Vertex} in graph -@var{Graph}. - -@item dgraph_path(+@var{Vertex}, +@var{Vertex1}, +@var{Graph}, ?@var{Path}) -@findex dgraph_path/4 -@snindex dgraph_path/4 -@cnindex dgraph_path/4 -The path @var{Path} is a path starting at vertex @var{Vertex} in graph -@var{Graph} and ending at path @var{Vertex2}. - -@item dgraph_reachable(+@var{Vertex}, +@var{Graph}, ?@var{Edges}) -@findex dgraph_reachable/3 -@snindex dgraph_reachable/3 -@cnindex dgraph_reachable/3 -The path @var{Path} is a path starting at vertex @var{Vertex} in graph -@var{Graph}. - -@item dgraph_leaves(+@var{Graph}, ?@var{Vertices}) -@findex dgraph_leaves/2 -@snindex dgraph_leaves/2 -@cnindex dgraph_leaves/2 -The vertices @var{Vertices} have no outgoing edge in graph -@var{Graph}. - -@end table - -@node UnDGraphs, DBUsage , DGraphs, Library -@section Undirected Graphs -@cindex undirected graphs - -The following graph manipulation routines use the red-black tree graph -library to implement undirected graphs. Mostly, this is done by having -two directed edges per undirected edge. - -@table @code - -@item undgraph_new(+@var{Graph}) -@findex undgraph_new/1 -@snindex undgraph_new/1 -@cnindex undgraph_new/1 -Create a new directed graph. This operation must be performed before -trying to use the graph. - -@item undgraph_vertices(+@var{Graph}, -@var{Vertices}) -@findex undgraph_vertices/2 -@snindex undgraph_vertices/2 -@cnindex undgraph_vertices/2 -Unify @var{Vertices} with all vertices appearing in graph -@var{Graph}. - -@item undgraph_edge(+@var{N1}, +@var{N2}, +@var{Graph}) -@findex undgraph_edge/2 -@snindex undgraph_edge/2 -@cnindex undgraph_edge/2 -Edge @var{N1}-@var{N2} is an edge in undirected graph @var{Graph}. - -@item undgraph_edges(+@var{Graph}, -@var{Edges}) -@findex undgraph_edges/2 -@snindex undgraph_edges/2 -@cnindex undgraph_edges/2 -Unify @var{Edges} with all edges appearing in graph -@var{Graph}. - -@item undgraph_add_vertices(+@var{Graph}, +@var{Vertices}, -@var{NewGraph}) -@findex undgraph_add_vertices/3 -@snindex undgraph_add_vertices/3 -@cnindex undgraph_add_vertices/3 -Unify @var{NewGraph} with a new graph obtained by adding the list of -vertices @var{Vertices} to the graph @var{Graph}. - -@item undgraph_del_vertices(+@var{Graph}, +@var{Vertices}, -@var{NewGraph}) -@findex undgraph_del_vertices/3 -@syindex undgraph_del_vertices/3 -@cnindex undgraph_del_vertices/3 -Unify @var{NewGraph} with a new graph obtained by deleting the list of -vertices @var{Vertices} and all the edges that start from or go to a -vertex in @var{Vertices} to the graph @var{Graph}. - -@item undgraph_add_edges(+@var{Graph}, +@var{Edges}, -@var{NewGraph}) -@findex undgraph_add_edges/3 -@snindex undgraph_add_edges/3 -@cnindex undgraph_add_edges/3 -Unify @var{NewGraph} with a new graph obtained by adding the list of -edges @var{Edges} to the graph @var{Graph}. - -@item undgraph_del_edges(+@var{Graph}, +@var{Edges}, -@var{NewGraph}) -@findex undgraph_del_edges/3 -@snindex undgraph_del_edges/3 -@cnindex undgraph_del_edges/3 -Unify @var{NewGraph} with a new graph obtained by removing the list of -edges @var{Edges} from the graph @var{Graph}. Notice that no vertices -are deleted. - -@item undgraph_neighbors(+@var{Vertex}, +@var{Graph}, -@var{Vertices}) -@findex undgraph_neighbors/3 -@snindex undgraph_neighbors/3 -@cnindex undgraph_neighbors/3 -Unify @var{Vertices} with the list of neighbors of vertex @var{Vertex} -in @var{Graph}. If the vertice is not in the graph fail. - -@item undgraph_neighbours(+@var{Vertex}, +@var{Graph}, -@var{Vertices}) -@findex undgraph_neighbours/3 -@snindex undgraph_neighbours/3 -@cnindex undgraph_neighbours/3 -Unify @var{Vertices} with the list of neighbours of vertex @var{Vertex} -in @var{Graph}. - -@item undgraph_complement(+@var{Graph}, -@var{NewGraph}) -@findex undgraph_complement/2 -@snindex undgraph_complement/2 -@cnindex undgraph_complement/2 -Unify @var{NewGraph} with the graph complementary to @var{Graph}. - -@item dgraph_to_undgraph( +@var{DGraph}, -@var{UndGraph}) -@findex dgraph_to_undgraph/2 -@snindex dgraph_to_undgraph/2 -@cnindex dgraph_to_undgraph/2 -Unify @var{UndGraph} with the undirected graph obtained from the -directed graph @var{DGraph}. - -@end table - -@node DBUsage, Lambda, UnDGraphs, Library -@section Memory Usage in Prolog Data-Base -@cindex DBUsage - -This library provides a set of utilities for studying memory usage in YAP. -The following routines are available once included with the -@code{use_module(library(dbusage))} command. - -@table @code -@item db_usage -@findex db_usage/0 -@snindex db_usage/0 -@cnindex db_usage/0 -Give general overview of data-base usage in the system. - -@item db_static -@findex db_static/0 -@snindex db_static/0 -@cnindex db_static/0 -List memory usage for every static predicate. - -@item db_static(+@var{Threshold}) -@findex db_static/1 -@snindex db_static/1 -@cnindex db_static/1 -List memory usage for every static predicate. Predicate must use more -than @var{Threshold} bytes. - -@item db_dynamic -@findex db_dynamic/0 -@snindex db_dynamic/0 -@cnindex db_dynamic/0 -List memory usage for every dynamic predicate. - -@item db_dynamic(+@var{Threshold}) -@findex db_dynamic/1 -@snindex db_dynamic/1 -@cnindex db_dynamic/1 -List memory usage for every dynamic predicate. Predicate must use more -than @var{Threshold} bytes. - -@end table - -@node Lambda, LAM, DBUsage, Library -@section Lambda Expressions -@cindex Lambda Expressions - - -This library, designed and implemented by Ulrich Neumerkel, provides -lambda expressions to simplify higher order programming based on @code{call/N}. - -Lambda expressions are represented by ordinary Prolog terms. There are -two kinds of lambda expressions: - -@pl_example - Free+\X1^X2^ ..^XN^Goal - - \X1^X2^ ..^XN^Goal -@end pl_example - -The second is a shorthand for@code{ t+\X1^X2^..^XN^Goal}, where @code{Xi} are the parameters. - -@var{Goal} is a goal or continuation (Syntax note: @var{Operators} within @var{Goal} -require parentheses due to the low precedence of the @code{^} operator). - -Free contains variables that are valid outside the scope of the lambda -expression. They are thus free variables within. - -All other variables of @var{Goal} are considered local variables. They must -not appear outside the lambda expression. This restriction is -currently not checked. Violations may lead to unexpected bindings. - -In the following example the parentheses around @code{X>3} are necessary. - -@pl_example -?- use_module(library(lambda)). -?- use_module(library(apply)). - -?- maplist(\X^(X>3),[4,5,9]). -true. -@end pl_example - -In the following @var{X} is a variable that is shared by both instances -of the lambda expression. The second query illustrates the cooperation -of continuations and lambdas. The lambda expression is in this case a -continuation expecting a further argument. - -@pl_example -?- Xs = [A,B], maplist(X+\Y^dif(X,Y), Xs). -Xs = [A, B], -dif(X, A), -dif(X, B). - -?- Xs = [A,B], maplist(X+\dif(X), Xs). -Xs = [A, B], -dif(X, A), -dif(X, B). - -@end pl_example - -The following queries are all equivalent. To see this, use -the fact @code{f(x,y)}. - -@pl_example -?- call(f,A1,A2). -?- call(\X^f(X),A1,A2). -?- call(\X^Y^f(X,Y), A1,A2). -?- call(\X^(X+\Y^f(X,Y)), A1,A2). -?- call(call(f, A1),A2). -?- call(f(A1),A2). -?- f(A1,A2). -A1 = x, -A2 = y. -@end pl_example - -Further discussions -at Ulrich Neumerker's page in @url{http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/ISO-Hiord}. - - -@node LAM, BDDs, Lambda, Library -@section LAM -@cindex lam - -This library provides a set of utilities for interfacing with LAM MPI. -The following routines are available once included with the -@code{use_module(library(lam_mpi))} command. The yap should be -invoked using the LAM mpiexec or mpirun commands (see LAM manual for -more details). - -@table @code -@item mpi_init -@findex mpi_init/0 -@snindex mpi_init/0 -@cnindex mpi_init/0 - Sets up the mpi environment. This predicate should be called before any other MPI predicate. - -@item mpi_finalize -@findex mpi_finalize/0 -@snindex mpi_finalize/0 -@cnindex mpi_finalize/0 - Terminates the MPI execution environment. Every process must call this predicate before exiting. - -@item mpi_comm_size(-@var{Size}) -@findex mpi_comm_size/1 -@snindex mpi_comm_size/1 -@cnindex mpi_comm_size/1 - Unifies @var{Size} with the number of processes in the MPI environment. - - -@item mpi_comm_rank(-@var{Rank}) -@findex mpi_comm_rank/1 -@snindex mpi_comm_rank/1 -@cnindex mpi_comm_rank/1 - Unifies @var{Rank} with the rank of the current process in the MPI environment. - -@item mpi_version(-@var{Major},-@var{Minor}) -@findex mpi_version/2 -@snindex mpi_version/2 -@cnindex mpi_version/2 - Unifies @var{Major} and @var{Minor} with, respectively, the major and minor version of the MPI. - - -@item mpi_send(+@var{Data},+@var{Dest},+@var{Tag}) -@findex mpi_send/3 -@snindex mpi_send/3 -@cnindex mpi_send/3 - -Blocking communication predicate. The message in @var{Data}, with tag -@var{Tag}, is sent immediately to the processor with rank @var{Dest}. -The predicate succeeds after the message being sent. - - - -@item mpi_isend(+@var{Data},+@var{Dest},+@var{Tag},-@var{Handle}) -@findex mpi_isend/4 -@snindex mpi_isend/4 -@cnindex mpi_isend/4 - -Non blocking communication predicate. The message in @var{Data}, with -tag @var{Tag}, is sent whenever possible to the processor with rank -@var{Dest}. An @var{Handle} to the message is returned to be used to -check for the status of the message, using the @code{mpi_wait} or -@code{mpi_test} predicates. Until @code{mpi_wait} is called, the -memory allocated for the buffer containing the message is not -released. - -@item mpi_recv(?@var{Source},?@var{Tag},-@var{Data}) -@findex mpi_recv/3 -@snindex mpi_recv/3 -@cnindex mpi_recv/3 - -Blocking communication predicate. The predicate blocks until a message -is received from processor with rank @var{Source} and tag @var{Tag}. -The message is placed in @var{Data}. - -@item mpi_irecv(?@var{Source},?@var{Tag},-@var{Handle}) -@findex mpi_irecv/3 -@snindex mpi_irecv/3 -@cnindex mpi_irecv/3 - -Non-blocking communication predicate. The predicate returns an -@var{Handle} for a message that will be received from processor with -rank @var{Source} and tag @var{Tag}. Note that the predicate succeeds -immediately, even if no message has been received. The predicate -@code{mpi_wait_recv} should be used to obtain the data associated to -the handle. - -@item mpi_wait_recv(?@var{Handle},-@var{Status},-@var{Data}) -@findex mpi_wait_recv/3 -@snindex mpi_wait_recv/3 -@cnindex mpi_wait_recv/3 - -Completes a non-blocking receive operation. The predicate blocks until -a message associated with handle @var{Hanlde} is buffered. The -predicate succeeds unifying @var{Status} with the status of the -message and @var{Data} with the message itself. - -@item mpi_test_recv(?@var{Handle},-@var{Status},-@var{Data}) -@findex mpi_test_recv/3 -@snindex mpi_test_recv/3 -@cnindex mpi_test_recv/3 - -Provides information regarding a handle. If the message associated -with handle @var{Hanlde} is buffered then the predicate succeeds -unifying @var{Status} with the status of the message and @var{Data} -with the message itself. Otherwise, the predicate fails. - - -@item mpi_wait(?@var{Handle},-@var{Status}) -@findex mpi_wait/2 -@snindex mpi_wait/2 -@cnindex mpi_wait/2 - -Completes a non-blocking operation. If the operation was a -@code{mpi_send}, the predicate blocks until the message is buffered -or sent by the runtime system. At this point the send buffer is -released. If the operation was a @code{mpi_recv}, it waits until the -message is copied to the receive buffer. @var{Status} is unified with -the status of the message. - -@item mpi_test(?@var{Handle},-@var{Status}) -@findex mpi_test/2 -@snindex mpi_test/2 -@cnindex mpi_test/2 - -Provides information regarding the handle @var{Handle}, ie., if a -communication operation has been completed. If the operation -associate with @var{Hanlde} has been completed the predicate succeeds -with the completion status in @var{Status}, otherwise it fails. - -@item mpi_barrier -@findex mpi_barrier/0 -@snindex mpi_barrier/0 -@cnindex mpi_barrier/0 - -Collective communication predicate. Performs a barrier -synchronization among all processes. Note that a collective -communication means that all processes call the same predicate. To be -able to use a regular @code{mpi_recv} to receive the messages, one -should use @code{mpi_bcast2}. - - -@item mpi_bcast2(+@var{Root}, ?@var{Data}) -@findex mpi_bcast/2 -@snindex mpi_bcast/2 -@cnindex mpi_bcast/2 - -Broadcasts the message @var{Data} from the process with rank @var{Root} -to all other processes. - -@item mpi_bcast3(+@var{Root}, +@var{Data}, +@var{Tag}) -@findex mpi_bcast/3 -@snindex mpi_bcast/3 -@cnindex mpi_bcast/3 - -Broadcasts the message @var{Data} with tag @var{Tag} from the process with rank @var{Root} -to all other processes. - -@item mpi_ibcast(+@var{Root}, +@var{Data}, +@var{Tag}) -@findex mpi_ibcast/3 -@snindex mpi_ibcast/3 -@cnindex mpi_ibcast/3 - -Non-blocking operation. Broadcasts the message @var{Data} with tag @var{Tag} -from the process with rank @var{Root} to all other processes. - -@item mpi_default_buffer_size(-@var{OldBufferSize}, ?@var{NewBufferSize}) -@findex mpi_default_buffer_size/1 -@snindex mpi_default_buffer_size/1 -@cnindex mpi_default_buffer_size/1 - -The @var{OldBufferSize} argument unifies with the current size of the -MPI communication buffer size and sets the communication buffer size -@var{NewBufferSize}. The buffer is used for assynchronous waiting and -for broadcast receivers. Notice that buffer is local at each MPI -process. - - -@item mpi_msg_size(@var{Msg}, -@var{MsgSize}) -@findex mpi_msg_size/2 -@snindex mpi_msg_size/2 -@cnindex mpi_msg_size/2 -Unify @var{MsgSize} with the number of bytes YAP would need to send the -message @var{Msg}. - -@item mpi_gc -@findex mpi_gc/0 -@snindex mpi_gc/0 -@cnindex mpi_gc/0 - -Attempts to perform garbage collection with all the open handles -associated with send and non-blocking broadcasts. For each handle it -tests it and the message has been delivered the handle and the buffer -are released. - -@end table - -@node BDDs, Block Diagram, LAM, Library -@section Binary Decision Diagrams and Friends -@cindex BDDs - -This library provides an interface to the BDD package CUDD. It requires -CUDD compiled as a dynamic library. In Linux this is available out of -box in Fedora, but can easily be ported to other Linux -distributions. CUDD is available in the ports OSX package, and in -cygwin. To use it, call @code{:-use_module(library(bdd))}. - -The following predicates construct a BDD: -@table @code -@item bbd_new(?@var{Exp}, -@var{BddHandle}) -@findex bdd_new/2 -create a new BDD from the logical expression @var{Exp}. The expression -may include: -@table @code -@item Logical Variables: -a leaf-node can be a logical variable. -@item Constants 0 and 1 -a leaf-node can also be one of these two constants. -@item or(@var{X}, @var{Y}), @var{X} \/ @var{Y}, @var{X} + @var{Y} -disjunction -@item and(@var{X}, @var{Y}), @var{X} /\ @var{Y}, @var{X} * @var{Y} -conjunction -@item nand(@var{X}, @var{Y}) -negated conjunction@ -@item nor(@var{X}, @var{Y}) -negated disjunction -@item xor(@var{X}, @var{Y}) -exclusive or -@item not(@var{X}), -@var{X} -negation -@end table - -@item bdd_from_list(?@var{List}, -@var{BddHandle}) -@findex bdd_from_list/2 -Convert a @var{List} of logical expressions of the form above into a BDD -accessible through @var{BddHandle}. - -@item mtbdd_new(?@var{Exp}, -@var{BddHandle}) -@findex mtbdd_new/2 -create a new algebraic decision diagram (ADD) from the logical -expression @var{Exp}. The expression may include: -@table @code -@item Logical Variables: -a leaf-node can be a logical variable, or @emph{parameter}. -@item Number -a leaf-node can also be any number -@item @var{X} * @var{Y} -product -@item @var{X} + @var{Y} -sum -@item @var{X} - @var{Y} -subtraction -@item or(@var{X}, @var{Y}), @var{X} \/ @var{Y} -logical or -@end table - -@item bdd_tree(+@var{BDDHandle}, @var{Term}) -@findex bdd_tree/2 -Convert the BDD or ADD represented by @var{BDDHandle} to a Prolog term -of the form @code{bdd(@var{Dir}, @var{Nodes}, @var{Vars})} or @code{mtbdd(@var{Nodes}, @var{Vars})}, respectively. The arguments are: -@itemize -@item - @var{Dir} direction of the BDD, usually 1 -@item - @var{Nodes} list of nodes in the BDD or ADD. - -In a BDD nodes may be @t{pp} (both terminals are positive) or @t{pn} - (right-hand-side is negative), and have four arguments: a logical - variable that will be bound to the value of the node, the logical - variable corresponding to the node, a logical variable, a 0 or a 1 with - the value of the left-hand side, and a logical variable, a 0 or a 1 - with the right-hand side. - -@item -@var{Vars} are the free variables in the original BDD, or the parameters of the BDD/ADD. -@end itemize -As an example, the BDD for the expression @code{X+(Y+X)*(-Z)} becomes: -@example -bdd(1,[pn(N2,X,1,N1),pp(N1,Y,N0,1),pn(N0,Z,1,1)],vs(X,Y,Z)) -@end example - -@item bdd_eval(+@var{BDDHandle}, @var{Val}) -@findex bdd_eval/2 -Unify @var{Val} with the value of the logical expression compiled in -@var{BDDHandle} given an assignment to its variables. -@example -bdd_new(X+(Y+X)*(-Z), BDD), -[X,Y,Z] = [0,0,0], -bdd_eval(BDD, V), -writeln(V). -@end example -would write 0 in the standard output stream. - -The Prolog code equivalent to @t{bdd_eval/2} is: -@example - Tree = bdd(1, T, _Vs), - reverse(T, RT), - foldl(eval_bdd, RT, _, V). - -eval_bdd(pp(P,X,L,R), _, P) :- - P is ( X/\L ) \/ ( (1-X) /\ R ). -eval_bdd(pn(P,X,L,R), _, P) :- - P is ( X/\L ) \/ ( (1-X) /\ (1-R) ). -@end example -First, the nodes are reversed to implement bottom-up evaluation. Then, -we use the @code{foldl} list manipulation predicate to walk every node, -computing the disjunction of the two cases and binding the output -variable. The top node gives the full expression value. Notice that -@code{(1-@var{X})} implements negation. - -@item bdd_size(+@var{BDDHandle}, -@var{Size}) -@findex bdd_size/2 -Unify @var{Size} with the number of nodes in @var{BDDHandle}. - -@item bdd_print(+@var{BDDHandle}, +@var{File}) -@findex bdd_print/2 -Output bdd @var{BDDHandle} as a dot file to @var{File}. - -@item bdd_to_probability_sum_product(+@var{BDDHandle}, -@var{Prob}) -@findex bdd_to_probability_sum_product/2 -Each node in a BDD is given a probability @var{Pi}. The total -probability of a corresponding sum-product network is @var{Prob}. - -@item bdd_to_probability_sum_product(+@var{BDDHandle}, -@var{Probs}, -@var{Prob}) -@findex bdd_to_probability_sum_product/3 -Each node in a BDD is given a probability @var{Pi}. The total -probability of a corresponding sum-product network is @var{Prob}, and -the probabilities of the inner nodes are @var{Probs}. - -In Prolog, this predicate would correspond to computing the value of a -BDD. The input variables will be bound to probabilities, eg -@code{[@var{X},@var{Y},@var{Z}] = [0.3.0.7,0.1]}, and the previous -@code{eval_bdd} would operate over real numbers: - -@example - Tree = bdd(1, T, _Vs), - reverse(T, RT), - foldl(eval_prob, RT, _, V). - -eval_prob(pp(P,X,L,R), _, P) :- - P is X * L + (1-X) * R. -eval_prob(pn(P,X,L,R), _, P) :- - P is X * L + (1-X) * (1-R). -@end example -@item bdd_close(@var{BDDHandle}) -@findex bdd_close/1 -close the BDD and release any resources it holds. - -@end table - -@node Block Diagram, , BDDs, Library -@section Block Diagram -@cindex Block Diagram - -This library provides a way of visualizing a prolog program using -modules with blocks. To use it use: -@code{:-use_module(library(block_diagram))}. -@table @code -@item make_diagram(+inputfilename, +ouputfilename) -@findex make_diagram/2 -@snindex make_diagram/2 -@cnindex make_diagram/2 - -This will crawl the files following the use_module, ensure_loaded directives withing the inputfilename. -The result will be a file in dot format. -You can make a pdf at the shell by asking @code{dot -Tpdf filename > output.pdf}. - -@item make_diagram(+inputfilename, +ouputfilename, +predicate, +depth, +extension) -@findex make_diagram/5 -@snindex make_diagram/5 -@cnindex make_diagram/5 - -The same as @code{make_diagram/2} but you can define how many of the imported/exporeted predicates will be shown with predicate, and how deep the crawler is allowed to go with depth. The extension is used if the file use module directives do not include a file extension. - -@end table - - -@node SWI-Prolog, SWI-Prolog Global Variables, Library, Top -@cindex SWI-Prolog - -@menu SWI-Prolog Emulation -Subnodes of SWI-Prolog -* Invoking Predicates on all Members of a List :: maplist and friends -* Forall :: forall built-in -@end menu - -@include swi.tex - -@node Extensions,Debugging,SWI-Prolog Global Variables,Top -@chapter Extensions to Prolog - -@menu -* Rational Trees:: Working with Rational Trees -* Co-routining:: Changing the Execution of Goals -* Attributed Variables:: Using attributed Variables -* CLPR:: The CLP(R) System -* Logtalk:: The Logtalk Object-Oriented system -* MYDDAS:: The MYDDAS Database Interface package -* Threads:: Thread Library -* Parallelism:: Running in Or-Parallel -* Tabling:: Storing Intermediate Solutions of programs -* Low Level Profiling:: Profiling Abstract Machine Instructions -* Low Level Tracing:: Tracing at Abstract Machine Level -@end menu - -YAP includes a number of extensions over the original Prolog -language. Next, we discuss support to the most important ones. - -@node Rational Trees, Co-routining, , Extensions -@section Rational Trees - -Prolog unification is not a complete implementation. For efficiency -considerations, Prolog systems do not perform occur checks while -unifying terms. As an example, @code{X = a(X)} will not fail but instead -will create an infinite term of the form @code{a(a(a(a(a(...)))))}, or -@emph{rational tree}. - -Rational trees are now supported by default in YAP. In previous -versions, this was not the default and these terms could easily lead -to infinite computation. For example, @code{X = a(X), X = X} would -enter an infinite loop. - -The @code{RATIONAL_TREES} flag improves support for these -terms. Internal primitives are now aware that these terms can exist, and -will not enter infinite loops. Hence, the previous unification will -succeed. Another example, @code{X = a(X), ground(X)} will succeed -instead of looping. Other affected built-ins include the term comparison -primitives, @code{numbervars/3}, @code{copy_term/2}, and the internal -data base routines. The support does not extend to Input/Output routines -or to @code{assert/1} YAP does not allow directly reading -rational trees, and you need to use @code{write_depth/2} to avoid -entering an infinite cycle when trying to write an infinite term. - -@node Co-routining, Attributed Variables, Rational Trees, Extensions -@section Co-routining - -Prolog uses a simple left-to-right flow of control. It is sometimes -convenient to change this control so that goals will only be executed -when conditions are fulfilled. This may result in a more "data-driven" -execution, or may be necessary to correctly implement extensions such as -negation by default. - -The @code{COROUTINING} flag enables this option. Note that the support for -coroutining will in general slow down execution. - -The following declaration is supported: - -@table @code -@item block/1 -The argument to @code{block/1} is a condition on a goal or a conjunction -of conditions, with each element separated by commas. Each condition is -of the form @code{predname(@var{C1},...,@var{CN})}, where @var{N} is the -arity of the goal, and each @var{CI} is of the form @code{-}, if the -argument must suspend until the first such variable is bound, or -@code{?}, otherwise. - -@item wait/1 -The argument to @code{wait/1} is a predicate descriptor or a conjunction -of these predicates. These predicates will suspend until their first -argument is bound. -@end table - -The following primitives are supported: - -@table @code -@item dif(@var{X},@var{Y}) -@findex dif/2 -@syindex dif/2 -@cnindex dif/2 -Succeed if the two arguments do not unify. A call to @code{dif/2} will -suspend if unification may still succeed or fail, and will fail if they -always unify. - -@item freeze(?@var{X},:@var{G}) -@findex freeze/2 -@syindex freeze/2 -@cnindex freeze/2 -Delay execution of goal @var{G} until the variable @var{X} is bound. - -@item frozen(@var{X},@var{G}) -@findex frozen/2 -@syindex frozen/2 -@cnindex frozen/2 -Unify @var{G} with a conjunction of goals suspended on variable @var{X}, -or @code{true} if no goal has suspended. - -@item when(+@var{C},:@var{G}) -@findex when/2 -@syindex when/2 -@cnindex when/2 -Delay execution of goal @var{G} until the conditions @var{C} are -satisfied. The conditions are of the following form: - -@table @code -@item @var{C1},@var{C2} -Delay until both conditions @var{C1} and @var{C2} are satisfied. -@item @var{C1};@var{C2} -Delay until either condition @var{C1} or condition @var{C2} is satisfied. -@item ?=(@var{V1},@var{C2}) -Delay until terms @var{V1} and @var{V1} have been unified. -@item nonvar(@var{V}) -Delay until variable @var{V} is bound. -@item ground(@var{V}) -Delay until variable @var{V} is ground. -@end table - -Note that @code{when/2} will fail if the conditions fail. - -@item call_residue(:@var{G},@var{L}) -@findex call_residue/2 -@syindex call_residue/2 -@cnindex call_residue/2 - -Call goal @var{G}. If subgoals of @var{G} are still blocked, return -a list containing these goals and the variables they are blocked in. The -goals are then considered as unblocked. The next example shows a case -where @code{dif/2} suspends twice, once outside @code{call_residue/2}, -and the other inside: - -@example -?- dif(X,Y), - call_residue((dif(X,Y),(X = f(Z) ; Y = f(Z))), L). - -X = f(Z), -L = [[Y]-dif(f(Z),Y)], -dif(f(Z),Y) ? ; - -Y = f(Z), -L = [[X]-dif(X,f(Z))], -dif(X,f(Z)) ? ; - -no -@end example -The system only reports one invocation of @code{dif/2} as having -suspended. - -@item call_residue_vars(:@var{G},@var{L}) -@findex call_residue_vars/2 -@syindex call_residue_vars/2 -@cnindex call_residue_vars/2 - -Call goal @var{G} and unify @var{L} with a list of all constrained variables created @emph{during} execution of @var{G}: - -@example - ?- dif(X,Z), call_residue_vars(dif(X,Y),L). -dif(X,Z), call_residue_vars(dif(X,Y),L). -L = [Y], -dif(X,Z), -dif(X,Y) ? ; - -no -@end example - -@end table - -@node Attributed Variables, CLPR, Co-routining, Extensions -@section Attributed Variables -@cindex attributed variables - -@menu -* New Style Attribute Declarations:: New Style code -* Old Style Attribute Declarations:: Old Style code (deprecated) -@end menu - -YAP supports attributed variables, originally developed at OFAI by -Christian Holzbaur. Attributes are a means of declaring that an -arbitrary term is a property for a variable. These properties can be -updated during forward execution. Moreover, the unification algorithm is -aware of attributed variables and will call user defined handlers when -trying to unify these variables. - -Attributed variables provide an elegant abstraction over which one can -extend Prolog systems. Their main application so far has been in -implementing constraint handlers, such as Holzbaur's CLPQR, Fruewirth -and Holzbaur's CHR, and CLP(BN). - -Different Prolog systems implement attributed variables in different -ways. Traditionally, YAP has used the interface designed by SICStus -Prolog. This interface is still -available in the @t{atts} library, but from YAP-6.0.3 we recommend using -the hProlog, SWI style interface. The main reason to do so is that -most packages included in YAP that use attributed variables, such as CHR, CLP(FD), and CLP(QR), -rely on the SWI-Prolog interface. - - -@node New Style Attribute Declarations, Old Style Attribute Declarations, , Attributed Variables -@section hProlog and SWI-Prolog style Attribute Declarations - -The following documentation is taken from the SWI-Prolog manual. - -Binding an attributed variable schedules a goal to be executed at the -first possible opportunity. In the current implementation the hooks are -executed immediately after a successful unification of the clause-head -or successful completion of a foreign language (built-in) predicate. Each -attribute is associated to a module and the hook @code{attr_unify_hook/2} is -executed in this module. The example below realises a very simple and -incomplete finite domain reasoner. - -@example -:- module(domain, - [ domain/2 % Var, ?Domain - ]). -:- use_module(library(ordsets)). - -domain(X, Dom) :- - var(Dom), !, - get_attr(X, domain, Dom). -domain(X, List) :- - list_to_ord_set(List, Domain), - put_attr(Y, domain, Domain), - X = Y. - -% An attributed variable with attribute value Domain has been -% assigned the value Y - -attr_unify_hook(Domain, Y) :- - ( get_attr(Y, domain, Dom2) - -> ord_intersection(Domain, Dom2, NewDomain), - ( NewDomain == [] - -> fail - ; NewDomain = [Value] - -> Y = Value - ; put_attr(Y, domain, NewDomain) - ) - ; var(Y) - -> put_attr( Y, domain, Domain ) - ; ord_memberchk(Y, Domain) - ). - -% Translate attributes from this module to residual goals - -attribute_goals(X) --> - @{ get_attr(X, domain, List) @}, - [domain(X, List)]. -@end example - - -Before explaining the code we give some example queries: - -@texinfo -@multitable @columnfractions .70 .30 - @item @code{?- domain(X, [a,b]), X = c} -@tab @code{fail} -@item @code{domain(X, [a,b]), domain(X, [a,c]).} - @tab @code{X=a} - @item @code{domain(X, [a,b,c]), domain(X, [a,c]).} - @tab @code{domain(X, [a,c]).} - @end multitable -@end texinfo - - -The predicate @code{domain/2} fetches (first clause) or assigns -(second clause) the variable a @emph{domain}, a set of values it can -be unified with. In the second clause first associates the domain -with a fresh variable and then unifies X to this variable to deal -with the possibility that X already has a domain. The -predicate @code{attr_unify_hook/2} is a hook called after a variable with -a domain is assigned a value. In the simple case where the variable -is bound to a concrete value we simply check whether this value is in -the domain. Otherwise we take the intersection of the domains and either -fail if the intersection is empty (first example), simply assign the -value if there is only one value in the intersection (second example) or -assign the intersection as the new domain of the variable (third -example). The nonterminal @code{attribute_goals/3} is used to translate -remaining attributes to user-readable goals that, when executed, reinstate -these attributes. - -@table @code - -@item put_attr(+@var{Var},+@var{Module},+@var{Value}) -@findex put_attr/3 -@snindex put_attr/3 -@cnindex put_attr/3 - -If @var{Var} is a variable or attributed variable, set the value for the -attribute named @var{Module} to @var{Value}. If an attribute with this -name is already associated with @var{Var}, the old value is replaced. -Backtracking will restore the old value (i.e., an attribute is a mutable -term. See also @code{setarg/3}). This predicate raises a representation error if -@var{Var} is not a variable and a type error if @var{Module} is not an atom. - -@item get_attr(+@var{Var},+@var{Module},-@var{Value}) -@findex get_attr/3 -@snindex get_attr/3 -@cnindex get_attr/3 - -Request the current @var{value} for the attribute named @var{Module}. If -@var{Var} is not an attributed variable or the named attribute is not -associated to @var{Var} this predicate fails silently. If @var{Module} -is not an atom, a type error is raised. - -@item del_attr(+@var{Var},+@var{Module}) -@findex del_attr/2 -@snindex del_attr/2 -@cnindex del_attr/2 - -Delete the named attribute. If @var{Var} loses its last attribute it -is transformed back into a traditional Prolog variable. If @var{Module} -is not an atom, a type error is raised. In all other cases this -predicate succeeds regardless whether or not the named attribute is -present. - -@item attr_unify_hook(+@var{AttValue},+@var{VarValue}) -@findex attr_unify_hook/2 -@snindex attr_unify_hook/2 -@cnindex attr_unify_hook/2 - -Hook that must be defined in the module an attributed variable refers -to. Is is called @emph{after} the attributed variable has been -unified with a non-var term, possibly another attributed variable. -@var{AttValue} is the attribute that was associated to the variable -in this module and @var{VarValue} is the new value of the variable. -Normally this predicate fails to veto binding the variable to -@var{VarValue}, forcing backtracking to undo the binding. If -@var{VarValue} is another attributed variable the hook often combines -the two attribute and associates the combined attribute with -@var{VarValue} using @code{put_attr/3}. - -@item attr_portray_hook(+@var{AttValue},+@var{Var}) -@findex attr_portray_hook/2 -@snindex attr_portray_hook/2 -@cnindex attr_portray_hook/2 - -Called by @code{write_term/2} and friends for each attribute if the option -@code{attributes(portray)} is in effect. If the hook succeeds the -attribute is considered printed. Otherwise @code{Module = ...} is -printed to indicate the existence of a variable. - -@item attribute_goals(+@var{Var},-@var{Gs},+@var{GsRest}) -@findex attribute_goals/2 -@snindex attribute_goals/2 -@cnindex attribute_goals/2 - -This nonterminal, if it is defined in a module, is used by @var{copy_term/3} -to project attributes of that module to residual goals. It is also -used by the toplevel to obtain residual goals after executing a query. -@end table - -Normal user code should deal with @code{put_attr/3}, @code{get_attr/3} and @code{del_attr/2}. -The routines in this section fetch or set the entire attribute list of a -variables. Use of these predicates is anticipated to be restricted to -printing and other special purpose operations. - -@table @code - -@item get_attrs(+@var{Var},-@var{Attributes}) -@findex get_attrs/2 -@snindex get_attrs/2 -@cnindex get_attrs/2 - -Get all attributes of @var{Var}. @var{Attributes} is a term of the form -@code{att(@var{Module}, @var{Value}, @var{MoreAttributes})}, where @var{MoreAttributes} is -@code{[]} for the last attribute. - -@item put_attrs(+@var{Var},+@var{Attributes}) -@findex put_attrs/2 -@snindex put_attrs/2 -@cnindex put_attrs/2 -Set all attributes of @var{Var}. See @code{get_attrs/2} for a description of -@var{Attributes}. - -@item del_attrs(+@var{Var}) -@findex del_attrs/1 -@snindex del_attrs/1 -@cnindex del_attrs/1 -If @var{Var} is an attributed variable, delete @emph{all} its -attributes. In all other cases, this predicate succeeds without -side-effects. - -@item term_attvars(+@var{Term},-@var{AttVars}) -@findex term_attvars/2 -@snindex term_attvars/2 -@cnindex term_attvars/2 -@var{AttVars} is a list of all attributed variables in @var{Term} and -its attributes. I.e., @code{term_attvars/2} works recursively through -attributes. This predicate is Cycle-safe. - -@item copy_term(?@var{TI},-@var{TF},-@var{Goals}) -@findex copy_term/3 -@syindex copy_term/3 -@cnindex copy_term/3 -Term @var{TF} is a variant of the original term @var{TI}, such that for -each variable @var{V} in the term @var{TI} there is a new variable @var{V'} -in term @var{TF} without any attributes attached. Attributed -variables are thus converted to standard variables. @var{Goals} is -unified with a list that represents the attributes. The goal -@code{maplist(call,@var{Goals})} can be called to recreate the -attributes. - -Before the actual copying, @code{copy_term/3} calls -@code{attribute_goals/1} in the module where the attribute is -defined. - -@item copy_term_nat(?@var{TI},-@var{TF}) -@findex copy_term_nat/2 -@syindex copy_term_nat/2 -@cnindex copy_term_nat/2 -As @code{copy_term/2}. Attributes however, are @emph{not} copied but replaced -by fresh variables. - -@end table - -@node Old Style Attribute Declarations, , New Style Attribute Declarations, Attributed Variables -@section SICStus Prolog style Attribute Declarations - -@menu -* Attribute Declarations:: Declaring New Attributes -* Attribute Manipulation:: Setting and Reading Attributes -* Attributed Unification:: Tuning the Unification Algorithm -* Displaying Attributes:: Displaying Attributes in User-Readable Form -* Projecting Attributes:: Obtaining the Attributes of Interest -* Attribute Examples:: Two Simple Examples of how to use Attributes. -@end menu - -Old style attribute declarations are activated through loading the library @t{atts} . The command -@example -| ?- use_module(library(atts)). -@end example -enables this form of use of attributed variables. The package provides the -following functionality: -@itemize @bullet -@item Each attribute must be declared first. Attributes are described by a functor -and are declared per module. Each Prolog module declares its own sets of -attributes. Different modules may have different functors with the same -module. -@item The built-in @code{put_atts/2} adds or deletes attributes to a -variable. The variable may be unbound or may be an attributed -variable. In the latter case, YAP discards previous values for the -attributes. -@item The built-in @code{get_atts/2} can be used to check the values of -an attribute associated with a variable. -@item The unification algorithm calls the user-defined predicate -@t{verify_attributes/3} before trying to bind an attributed -variable. Unification will resume after this call. -@item The user-defined predicate -@t{attribute_goal/2} converts from an attribute to a goal. -@item The user-defined predicate -@t{project_attributes/2} is used from a set of variables into a set of -constraints or goals. One application of @t{project_attributes/2} is in -the top-level, where it is used to output the set of -floundered constraints at the end of a query. -@end itemize - -@node Attribute Declarations, Attribute Manipulation, , Old Style Attribute Declarations -@subsection Attribute Declarations - -Attributes are compound terms associated with a variable. Each attribute -has a @emph{name} which is @emph{private} to the module in which the -attribute was defined. Variables may have at most one attribute with a -name. Attribute names are defined with the following declaration: - -@cindex attribute declaration -@cindex declaration, attribute -@findex attribute/1 (declaration) - -@example -:- attribute AttributeSpec, ..., AttributeSpec. -@end example - -@noindent -where each @var{AttributeSpec} has the form (@var{Name}/@var{Arity}). -One single such declaration is allowed per module @var{Module}. - -Although the YAP module system is predicate based, attributes are local -to modules. This is implemented by rewriting all calls to the -built-ins that manipulate attributes so that attribute names are -preprocessed depending on the module. The @code{user:goal_expansion/3} -mechanism is used for this purpose. - - -@node Attribute Manipulation, Attributed Unification, Attribute Declarations, Old Style Attribute Declarations -@subsection Attribute Manipulation - - -The attribute manipulation predicates always work as follows: -@enumerate -@item The first argument is the unbound variable associated with -attributes, -@item The second argument is a list of attributes. Each attribute will -be a Prolog term or a constant, prefixed with the @t{+} and @t{-} unary -operators. The prefix @t{+} may be dropped for convenience. -@end enumerate - -The following three procedures are available to the user. Notice that -these built-ins are rewritten by the system into internal built-ins, and -that the rewriting process @emph{depends} on the module on which the -built-ins have been invoked. - -@table @code -@item @var{Module}:get_atts(@var{-Var},@var{?ListOfAttributes}) -@findex get_atts/2 -@syindex get_atts/2 -@cnindex get_atts/2 -Unify the list @var{?ListOfAttributes} with the attributes for the unbound -variable @var{Var}. Each member of the list must be a bound term of the -form @code{+(@var{Attribute})}, @code{-(@var{Attribute})} (the @t{kbd} -prefix may be dropped). The meaning of @t{+} and @t{-} is: -@item +(@var{Attribute}) -Unifies @var{Attribute} with a corresponding attribute associated with -@var{Var}, fails otherwise. - -@item -(@var{Attribute}) -Succeeds if a corresponding attribute is not associated with -@var{Var}. The arguments of @var{Attribute} are ignored. - -@item @var{Module}:put_atts(@var{-Var},@var{?ListOfAttributes}) -@findex put_atts/2 -@syindex put_atts/2 -@cnindex put_atts/2 -Associate with or remove attributes from a variable @var{Var}. The -attributes are given in @var{?ListOfAttributes}, and the action depends -on how they are prefixed: -@item +(@var{Attribute}) -Associate @var{Var} with @var{Attribute}. A previous value for the -attribute is simply replace (like with @code{set_mutable/2}). - -@item -(@var{Attribute}) -Remove the attribute with the same name. If no such attribute existed, -simply succeed. -@end table - -@node Attributed Unification, Displaying Attributes, Attribute Manipulation, Old Style Attribute Declarations -@subsection Attributed Unification - -The user-predicate predicate @code{verify_attributes/3} is called when -attempting to unify an attributed variable which might have attributes -in some @var{Module}. - -@table @code -@item @var{Module}:verify_attributes(@var{-Var}, @var{+Value}, @var{-Goals}) -@findex verify_attributes/3 -@syindex verify_attributes/3 -@cnindex verify_attributes/3 - -The predicate is called when trying to unify the attributed variable -@var{Var} with the Prolog term @var{Value}. Note that @var{Value} may be -itself an attributed variable, or may contain attributed variables. The -goal @t{verify_attributes/3} is actually called before @var{Var} is -unified with @var{Value}. - -It is up to the user to define which actions may be performed by -@t{verify_attributes/3} but the procedure is expected to return in -@var{Goals} a list of goals to be called @emph{after} @var{Var} is -unified with @var{Value}. If @t{verify_attributes/3} fails, the -unification will fail. - -Notice that the @t{verify_attributes/3} may be called even if @var{Var}< -has no attributes in module @t{Module}. In this case the routine should -simply succeed with @var{Goals} unified with the empty list. - -@item attvar(@var{-Var}) -@findex attvar/1 -@snindex attvar/1 -@cnindex attvar/1 -Succeed if @var{Var} is an attributed variable. -@end table - - - -@node Displaying Attributes, Projecting Attributes,Attributed Unification, Old Style Attribute Declarations -@subsection Displaying Attributes - -Attributes are usually presented as goals. The following routines are -used by built-in predicates such as @code{call_residue/2} and by the -Prolog top-level to display attributes: - -@table @code -@item @var{Module}:attribute_goal(@var{-Var}, @var{-Goal}) -@findex attribute_goal/2 -@syindex attribute_goal/2 -@cnindex attribute_goal/2 -User-defined procedure, called to convert the attributes in @var{Var} to -a @var{Goal}. Should fail when no interpretation is available. - -@end table - -@node Projecting Attributes, Attribute Examples, Displaying Attributes, Old Style Attribute Declarations -@subsection Projecting Attributes - -Constraint solvers must be able to project a set of constraints to a set -of variables. This is useful when displaying the solution to a goal, but -may also be used to manipulate computations. The user-defined -@code{project_attributes/2} is responsible for implementing this -projection. - - -@table @code -@item @var{Module}:project_attributes(@var{+QueryVars}, @var{+AttrVars}) -@findex project_attributes/2 -@syindex project_attributes/2 -@cnindex project_attributes/2 -Given a list of variables @var{QueryVars} and list of attributed -variables @var{AttrVars}, project all attributes in @var{AttrVars} to -@var{QueryVars}. Although projection is constraint system dependent, -typically this will involve expressing all constraints in terms of -@var{QueryVars} and considering all remaining variables as existentially -quantified. -@end table - -Projection interacts with @code{attribute_goal/2} at the Prolog top -level. When the query succeeds, the system first calls -@code{project_attributes/2}. The system then calls -@code{attribute_goal/2} to get a user-level representation of the -constraints. Typically, @code{attribute_goal/2} will convert from the -original constraints into a set of new constraints on the projection, -and these constraints are the ones that will have an -@code{attribute_goal/2} handler. - -@node Attribute Examples, ,Projecting Attributes, Old Style Attribute Declarations -@subsection Attribute Examples - -The following two examples example is taken from the SICStus Prolog manual. It -sketches the implementation of a simple finite domain ``solver''. Note -that an industrial strength solver would have to provide a wider range -of functionality and that it quite likely would utilize a more efficient -representation for the domains proper. The module exports a single -predicate @code{domain(@var{-Var},@var{?Domain})} which associates -@var{Domain} (a list of terms) with @var{Var}. A variable can be -queried for its domain by leaving @var{Domain} unbound. - -We do not present here a definition for @code{project_attributes/2}. -Projecting finite domain constraints happens to be difficult. - - -@example -:- module(domain, [domain/2]). - -:- use_module(library(atts)). -:- use_module(library(ordsets), [ - ord_intersection/3, - ord_intersect/2, - list_to_ord_set/2 - ]). - -:- attribute dom/1. - -verify_attributes(Var, Other, Goals) :- - get_atts(Var, dom(Da)), !, % are we involved? - ( var(Other) -> % must be attributed then - ( get_atts(Other, dom(Db)) -> % has a domain? - ord_intersection(Da, Db, Dc), - Dc = [El|Els], % at least one element - ( Els = [] -> % exactly one element - Goals = [Other=El] % implied binding - ; Goals = [], - put_atts(Other, dom(Dc))% rescue intersection - ) - ; Goals = [], - put_atts(Other, dom(Da)) % rescue the domain - ) - ; Goals = [], - ord_intersect([Other], Da) % value in domain? - ). -verify_attributes(_, _, []). % unification triggered - % because of attributes - % in other modules - -attribute_goal(Var, domain(Var,Dom)) :- % interpretation as goal - get_atts(Var, dom(Dom)). - -domain(X, Dom) :- - var(Dom), !, - get_atts(X, dom(Dom)). -domain(X, List) :- - list_to_ord_set(List, Set), - Set = [El|Els], % at least one element - ( Els = [] -> % exactly one element - X = El % implied binding - ; put_atts(Fresh, dom(Set)), - X = Fresh % may call - % verify_attributes/3 - ). -@end example - -Note that the ``implied binding'' @code{Other=El} was deferred until after -the completion of @code{verify_attribute/3}. Otherwise, there might be a -danger of recursively invoking @code{verify_attribute/3}, which might bind -@code{Var}, which is not allowed inside the scope of @code{verify_attribute/3}. -Deferring unifications into the third argument of @code{verify_attribute/3} -effectively serializes the calls to @code{verify_attribute/3}. - -Assuming that the code resides in the file @file{domain.yap}, we -can use it via: - -@example -| ?- use_module(domain). -@end example - -Let's test it: - -@example -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]). - -domain(X,[1,5,6,7]), -domain(Y,[3,4,5,6]), -domain(Z,[1,6,7,8]) ? - -yes -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), - X=Y. - -Y = X, -domain(X,[5,6]), -domain(Z,[1,6,7,8]) ? - -yes -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), - X=Y, Y=Z. - -X = 6, -Y = 6, -Z = 6 -@end example - -To demonstrate the use of the @var{Goals} argument of -@code{verify_attributes/3}, we give an implementation of -@code{freeze/2}. We have to name it @code{myfreeze/2} in order to -avoid a name clash with the built-in predicate of the same name. - -@example -:- module(myfreeze, [myfreeze/2]). - -:- use_module(library(atts)). - -:- attribute frozen/1. - -verify_attributes(Var, Other, Goals) :- - get_atts(Var, frozen(Fa)), !, % are we involved? - ( var(Other) -> % must be attributed then - ( get_atts(Other, frozen(Fb)) % has a pending goal? - -> put_atts(Other, frozen((Fa,Fb))) % rescue conjunction - ; put_atts(Other, frozen(Fa)) % rescue the pending goal - ), - Goals = [] - ; Goals = [Fa] - ). -verify_attributes(_, _, []). - -attribute_goal(Var, Goal) :- % interpretation as goal - get_atts(Var, frozen(Goal)). - -myfreeze(X, Goal) :- - put_atts(Fresh, frozen(Goal)), - Fresh = X. -@end example - -Assuming that this code lives in file @file{myfreeze.yap}, -we would use it via: - -@example -| ?- use_module(myfreeze). -| ?- myfreeze(X,print(bound(x,X))), X=2. - -bound(x,2) % side effect -X = 2 % bindings -@end example - -The two solvers even work together: - -@example -| ?- myfreeze(X,print(bound(x,X))), domain(X,[1,2,3]), - domain(Y,[2,10]), X=Y. - -bound(x,2) % side effect -X = 2, % bindings -Y = 2 -@end example - -The two example solvers interact via bindings to shared attributed -variables only. More complicated interactions are likely to be found -in more sophisticated solvers. The corresponding -@code{verify_attributes/3} predicates would typically refer to the -attributes from other known solvers/modules via the module prefix in -@code{@var{Module}:get_atts/2}. - -@node CLPR, CHR, Attributed Variables, Extensions -@cindex CLPQ -@cindex CLPR - -@menu -* CLPR Solver Predicates:: -* CLPR Syntax:: -* CLPR Unification:: -* CLPR Non-linear Constraints:: -@end menu - - -@include clpr.tex - -@node CHR, Logtalk, CLPR, Top - -@menu -* CHR Introduction:: -* CHR Syntax and Semantics:: -* CHR in YAP Programs:: -* CHR Debugging:: -* CHR Examples:: -* CHR Compatibility:: -* CHR Guidelines:: -@end menu - -@include chr.tex - -@node Logtalk, MYDDAS, CHR, Extensions -@section Logtalk -@cindex Logtalk - -The Logtalk object-oriented extension is available after running its -standalone installer by using the @code{yaplgt} command in POSIX -systems or by using the @code{Logtalk - YAP} shortcut in the Logtalk -program group in the Start Menu on Windows systems. For more information -please see the URL @url{http://logtalk.org/}. - -@node MYDDAS, Real, Logtalk, Extensions -@section MYDDAS -@cindex MYDDAS - -The MYDDAS database project was developed within a FCT project aiming at -the development of a highly efficient deductive database system, based -on the coupling of the MySQL relational database system with the Yap -Prolog system. MYDDAS was later expanded to support the ODBC interface. - -@menu -Subnodes of MYDDAS -* Requirements and Installation Guide:: -* MYDDAS Architecture:: -* Loading MYDDAS:: -* Connecting to and disconnecting from a Database Server:: -* Accessing a Relation:: -* View Level Interface :: -* Accessing Tables in Data Sources Using SQL:: -* Insertion of Rows:: -* Types of Attributes:: -* Number of Fields:: -* Describing a Relation:: -* Enumerating Relations:: -* The MYDDAS MySQL Top Level:: -* Other MYDDAS Properties:: -@end menu - -@node Requirements and Installation Guide, MYDDAS Architecture, , MYDDAS -@section Requirements and Installation Guide - -Next, we describe how to usen of the YAP with the MYDDAS System. The -use of this system is entirely depend of the MySQL development libraries -or the ODBC development libraries. At least one of the this development -libraries must be installed on the computer system, otherwise MYDDAS -will not compile. The MySQL development libraries from MySQL 3.23 an -above are know to work. We recommend the usage of MySQL versusODBC, -but it is possible to have both options installed - -At the same time, without any problem. The MYDDAS system automatically -controls the two options. Currently, MYDDAS is know to compile without -problems in Linux. The usage of this system on Windows has not been -tested yet. MYDDAS must be enabled at configure time. This can be done -with the following options: - -@table @code - -@item --enable-myddas - This option will detect which development libraries are installed on the computer system, MySQL, ODBC or both, and will compile the Yap system with the support for which libraries it detects; -@item --enable-myddas-stats -This option is only available in MySQL. It includes code to get -statistics from the MYDDAS system; -@item --enable-top-level -This option is only available in MySQL. It enables the option to interact with the MySQL server in -two different ways. As if we were on the MySQL Client Shell, and as if -we were using Datalog. -@end table - -@node MYDDAS Architecture, Loading MYDDAS, Requirements and Installation Guide, MYDDAS -@section MYDDAS Architecture - -The system includes four main blocks that are put together through the -MYDDAS interface: the Yap Prolog compiler, the MySQL database system, an -ODBC layer and a Prolog to SQL compiler. Current effort is put on the -MySQL interface rather than on the ODBC interface. If you want to use -the full power of the MYDDAS interface we recommend you to use a MySQL -database. Other databases, such as Oracle, PostGres or Microsoft SQL -Server, can be interfaced through the ODBC layer, but with limited -performance and features support. - -The main structure of the MYDDAS interface is simple. Prolog queries -involving database goals are translated to SQL using the Prolog to SQL -compiler; then the SQL expression is sent to the database system, which -returns the set of tuples satisfying the query; and finally those tuples -are made available to the Prolog engine as terms. For recursive queries -involving database goals, the YapTab tabling engine provides the -necessary support for an efficient evaluation of such queries. - -An important aspect of the MYDDAS interface is that for the programmer -the use of predicates which are defined in database relations is -completely transparent. An example of this transparent support is the -Prolog cut operator, which has exactly the same behaviour from -predicates defined in the Prolog program source code, or from predicates -defined in database as relations. - -@node Loading MYDDAS, Connecting to and disconnecting from a Database Server, MYDDAS Architecture, MYDDAS -@section Loading MYDDAS - -Begin by starting YAP and loading the library -@code{use_module(library(myddas))}. This library already includes the -Prolog to SQL Compiler described in [2] and [1]. In MYDDAS this compiler -has been extended to support further constructs which allow a more -efficient SQL translation. - -@node Connecting to and disconnecting from a Database Server, Accessing a Relation, Loading MYDDAS, MYDDAS -@section Connecting to and disconnecting from a Database Server - - -@table @code -@item db open(+,+,+,+,+). -@findex db_open/5 -@snindex db_open/5 -@cnindex db_open/5 - -@item db open(+,+,+,+). -@findex db_open/4 -@snindex db_open/4 -@cnindex db_open/4 - -@item db close(+). -@findex db_close/1 -@snindex db_close/1 -@cnindex db_close/1 - -@end table - - Assuming the MySQL server is running and we have an account, we can -login to MySQL by invoking @code{db_open/5} as one of the following: -@example -?- db_open(mysql,Connection,Host/Database,User,Password). -?- db_open(mysql,Connection,Host/Database/Port,User,Password). -?- db_open(mysql,Connection,Host/Database/UnixSocket,User,Password). -?- db_open(mysql,Connection,Host/Database/Port/UnixSocket,User,Password). - -@end example -If the login is successful, there will be a response of @code{yes}. For -instance: - @example -?- db_open(mysql,con1,localhost/guest_db,guest,''). -@end example -uses the MySQL native interface, selected by the first argument, to open -a connection identified by the @code{con1} atom, to an instance of a -MySQL server running on host @code{localhost}, using database guest @code{db} -and user @code{guest} with empty @code{password}. To disconnect from the @code{con1} -connection we use: -@example -?- db_close(con1). -@end example - Alternatively, we can use @code{db_open/4} and @code{db_close/0,} without an argument -to identify the connection. In this case the default connection is used, -with atom @code{myddas}. Thus using -@example -?- db_open(mysql,localhost/guest_db,guest,''). -?- db_close. -@end example -or -@example -?- db_open(mysql,myddas,localhost/guest_db,guest,''). -?- db_close(myddas). -@end example -is exactly the same. - -MYDDAS also supports ODBC. To connect to a database using an ODBC driver -you must have configured on your system a ODBC DSN. If so, the @code{db_open/4} -and @code{db_open/5} have the following mode: -@example - ?- db_open(odbc,Connection,ODBC_DSN,User,Password). - ?- db_open(odbc,ODBC_DSN,User,Password). -@end example - -For instance, if you do @code{db_open(odbc,odbc_dsn,guest,'')}. it will connect -to a database, through ODBC, using the definitions on the @code{odbc_dsn} DSN -configured on the system. The user will be the user @code{guest} with no -password. - -@node Accessing a Relation, View Level Interface , Connecting to and disconnecting from a Database Server, MYDDAS -@section Accessing a Relation - -@table @code -@item db_import(+Conn,+RelationName,+PredName). -@findex db_import/3 -@snindex db_import/3 -@cnindex db_import/3 - -@item db_import(+RelationName,+PredName). -@findex db_import/2 -@snindex db_import/2 -@cnindex db_import/2 -@end table - -Assuming you have access permission for the relation you wish to import, -you can use @code{db_import/3} or @code{db_import/2} as: -@example -?- db_import(Conn,RelationName,PredName). -?- db_import(RelationName,PredName). -@end example - where @var{RelationName}, is the name of -relation we wish to access, @var{PredName} is the name of the predicate we -wish to use to access the relation from YAP. @var{Conn}, is the connection -identifier, which again can be dropped so that the default myddas connection -is used. For instance, if we want to access the relation phonebook, -using the predicate @code{phonebook/3} we write: -@example -?- db_import(con1,phonebook,phonebook). -yes -?- phonebook(Letter,Name,Number). -Letter = 'D', -Name = 'John Doe', -Number = 123456789 ? -yes -@end example -Backtracking can then be used to retrieve the next row -of the relation phonebook. Records with particular field values may be -selected in the same way as in Prolog. (In particular, no mode -specification for database predicates is required). For instance: -@example -?- phonebook(Letter,'John Doe',Letter). -Letter = 'D', -Number = 123456789 ? -yes -@end example -generates the query -@example -SELECT A.Letter , 'John Doe' , A.Number -FROM 'phonebook' A -WHERE A.Name = 'John Doe'; -@end example - -@node View Level Interface, Accessing Tables in Data Sources Using SQL, Accessing a Relation, MYDDAS -@section View Level Interface - -@table @code -@item db view(+,+,+). -@findex db_view/3 -@snindex db_view/3 -@cnindex db_view/3 - -@item db view(+,+). -@findex db_view/2 -@snindex db_view/2 -@cnindex db_view/2 -@end table -If we import a database relation, such as an edge relation representing the edges of a directed graph, through -@example -?- db_import('Edge',edge). -yes -@end example -and we then write a query to retrieve all the direct cycles in the -graph, such as -@example -?- edge(A,B), edge(B,A). -A = 10, -B = 20 ? -@end example -this is clearly inefficient [3], because of relation-level -access. Relation-level access means that a separate SQL query will be -generated for every goal in the body of the clause. For the second -@code{edge/2} goal, a SQL query is generated using the variable bindings that -result from the first @code{edge/2} goal execution. If the second -@code{edge/2} goal -fails, or if alternative solutions are demanded, backtracking access the -next tuple for the first @code{edge/2} goal and another SQL query will be -generated for the second @code{edge/2} goal. The generation of this large -number of queries and the communication overhead with the database -system for each of them, makes the relation-level approach inefficient. -To solve this problem the view level interface can be used for the -definition of rules whose bodies includes only imported database -predicates. One can use the view level interface through the predicates -@code{db_view/3} and @code{db_view/2}: -@example -?- db_view(Conn,PredName(Arg_1,...,Arg_n),DbGoal). -?- db_view(PredName(Arg_1,...,Arg_n),DbGoal). -@end example - All arguments are standard Prolog terms. @var{Arg1} through @var{Argn} -define the attributes to be retrieved from the database, while -@var{DbGoal} defines the selection restrictions and join -conditions. @var{Conn} is the connection identifier, which again can be -dropped. Calling predicate @code{PredName/n} will retrieve database -tuples using a single SQL query generated for the @var{DbGoal}. We next show -an example of a view definition for the direct cycles discussed -above. Assuming the declaration: -@example -?- db_import('Edge',edge). -yes -@end example -we -write: -@example -?- db_view(direct_cycle(A,B),(edge(A,B), edge(B,A))). -yes -?- direct_cycle(A,B)). -A = 10, -B = 20 ? -@end example -This call generates the SQL -statement: -@example -SELECT A.attr1 , A.attr2 -FROM Edge A , Edge B -WHERE B.attr1 = A.attr2 AND B.attr2 = A.attr1; -@end example - -Backtracking, as in relational level interface, can be used to retrieve the next row of the view. -The view interface also supports aggregate function predicates such as -@code{sum}, @code{avg}, @code{count}, @code{min} and @code{max}. For -instance: -@example -?- db_view(count(X),(X is count(B, B^edge(10,B)))). -@end example -generates the query : -@example -SELECT COUNT(A.attr2) -FROM Edge A WHERE A.attr1 = 10; -@end example - -To know how to use db @code{view/3}, please refer to Draxler's Prolog to -SQL Compiler Manual. - -@node Accessing Tables in Data Sources Using SQL, Insertion of Rows, View Level Interface , MYDDAS -@section Accessing Tables in Data Sources Using SQL - -@table @code -@item db_sql(+,+,?). -@findex db_sql/3 -@snindex db_sql/3 -@cnindex db_sql/3 - -@item db_sql(+,?). -@findex db_sql/2 -@snindex db_sql/2 -@cnindex db_sql/2 -@end table - -It is also possible to explicitly send a SQL query to the database server using -@example -?- db_sql(Conn,SQL,List). -?- db_sql(SQL,List). -@end example -where @var{SQL} is an arbitrary SQL expression, and @var{List} is a list -holding the first tuple of result set returned by the server. The result -set can also be navigated through backtracking. - -Example: -@example -?- db_sql('SELECT * FROM phonebook',LA). -LA = ['D','John Doe',123456789] ? -@end example - -@node Insertion of Rows, Types of Attributes, Accessing Tables in Data Sources Using SQL, MYDDAS -@section Insertion of Rows - -@table @code -@item db_assert(+,+). -@findex db_assert/2 -@snindex db_assert/2 -@cnindex db_assert/2 - -@item db_assert(+). -@findex db_assert/1 -@snindex db_assert/1 -@cnindex db_assert/1 - -@end table - -Assuming you have imported the related base table using - @code{db_import/2} or @code{db_import/3}, you can insert to that table - by using @code{db_assert/2} predicate any given fact. -@example -?- db_assert(Conn,Fact). -?- db_assert(Fact). -@end example -The second argument must be declared with all of its arguments bound to -constants. For example assuming @code{helloWorld} is imported through -@code{db_import/2}: -@example -?- db_import('Hello World',helloWorld). -yes -?- db_assert(helloWorld('A' ,'Ana',31)). -yes -@end example -This, would generate the following query -@example -INSERT INTO helloWorld -VALUES ('A','Ana',3) -@end example -which would insert into the helloWorld, the following row: -@code{A,Ana,31}. If we want to insert @code{NULL} values into the -relation, we call @code{db_assert/2} with a uninstantiated variable in -the data base imported predicate. For example, the following query on -the YAP-prolog system: - -@example -?- db_assert(helloWorld('A',NULL,31)). -yes -@end example - -Would insert the row: @code{A,null value,31} into the relation -@code{Hello World}, assuming that the second row allows null values. - -@table @code -@item db insert(+,+,+). -@findex db_insert/3 -@snindex db_insert/3 -@cnindex db_insert/3 - -@item db insert(+,+). -@findex db_insert/2 -@snindex db_insert/2 -@cnindex db_insert/2 -@end table - -This predicate would create a new database predicate, which will insert -any given tuple into the database. -@example -?- db_insert(Conn,RelationName,PredName). -?- db_insert(RelationName,PredName). -@end example -This would create a new predicate with name @var{PredName}, that will -insert tuples into the relation @var{RelationName}. is the connection -identifier. For example, if we wanted to insert the new tuple -@code{('A',null,31)} into the relation @code{Hello World}, we do: -@example -?- db_insert('Hello World',helloWorldInsert). -yes -?- helloWorldInsert('A',NULL,31). -yes -@end example - -@node Types of Attributes, Number of Fields, Insertion of Rows, MYDDAS -@section Types of Attributes - - -@table @code -@item db_get_attributes_types(+,+,?). -@findex db_get_attributes_types/3 -@snindex db_get_attributes_types/3 -@cnindex db_get_attributes_types/3 - -@item db_get_attributes_types(+,?). -@findex db_get_attributes_types/2 -@snindex db_get_attributes_types/2 -@cnindex db_get_attributes_types/2 - -@end table - -The prototype for this predicate is the following: -@example -?- db_get_attributes_types(Conn,RelationName,ListOfFields). -?- db_get_attributes_types(RelationName,ListOfFields). -@end example - -You can use the -predicate @code{db_get_attributes types/2} or @code{db_get_attributes_types/3}, to -know what are the names and attributes types of the fields of a given -relation. For example: -@example -?- db_get_attributes_types(myddas,'Hello World',LA). -LA = ['Number',integer,'Name',string,'Letter',string] ? -yes -@end example -where @t{Hello World} is the name of the relation and @t{myddas} is the -connection identifier. - -@node Number of Fields, Describing a Relation, Types of Attributes, MYDDAS -@section Number of Fields - -@table @code -@item db_number_of_fields(+,?). -@findex db_number_of_fields/2 -@snindex db_number_of_fields/2 -@cnindex db_number_of_fields/2 - -@item db_number_of_fields(+,+,?). -@findex db_number_of_fields/3 -@snindex db_number_of_fields/3 -@cnindex db_number_of_fields/3 -@end table - -The prototype for this -predicate is the following: -@example - ?- db_number_of_fields(Conn,RelationName,Arity). - ?- db_number_of_fields(RelationName,Arity). -@end example -You can use the predicate @code{db_number_of_fields/2} or -@code{db_number_of_fields/3} to know what is the arity of a given -relation. Example: -@example -?- db_number_of_fields(myddas,'Hello World',Arity). -Arity = 3 ? -yes -@end example -where @code{Hello World} is the name of the -relation and @code{myddas} is the connection identifier. - -@node Describing a Relation, Enumerating Relations, Number of Fields, MYDDAS -@section Describing a Relation - -@table @code -@item db_datalog_describe(+,+). -@findex db_datalog_describe/2 -@snindex db_datalog_describe/2 -@cnindex db_datalog_describe/2 - -@item db_datalog_describe(+). -@findex db_datalog_describe/1 -@snindex db_datalog_describe/1 -@cnindex db_datalog_describe/1 -@end table - - -The db @code{datalog_describe/2} predicate does not really returns any -value. It simply prints to the screen the result of the MySQL describe -command, the same way as @code{DESCRIBE} in the MySQL prompt would. -@example -?- db_datalog_describe(myddas,'Hello World'). -+----------+----------+------+-----+---------+-------+ -| Field | Type | Null | Key | Default | Extra | -+----------+----------+------+-----+---------+-------+ -+ Number | int(11) | YES | | NULL | | -+ Name | char(10) | YES | | NULL | | -+ Letter | char(1) | YES | | NULL | | -+----------+----------+------+-----+---------+-------+ -yes -@end example - -@table @code -@item db_describe(+,+). -@findex db_describe/2 -@snindex db_describe/2 -@cnindex db_describe/2 - -@item db_describe(+). -@findex db_describe/1 -@snindex db_describe/1 -@cnindex db_describe/1 - -@end table - -The @code{db_describe/3} predicate does the same action as -@code{db_datalog_describe/2} predicate but with one major -difference. The results are returned by backtracking. For example, the -last query: -@example - ?- db_describe(myddas,'Hello World',Term). -Term = tableInfo('Number',int(11),'YES','',null(0),'') ? ; -Term = tableInfo('Name',char(10),'YES','',null(1),'' ? ; -Term = tableInfo('Letter',char(1),'YES','',null(2),'') ? ; -no -@end example - -@node Enumerating Relations, The MYDDAS MySQL Top Level, Describing a Relation, MYDDAS -@section Enumeration Relations - -@table @code -@item db_datalog_show_tables(+). -@item db_datalog_show_tables -@end table - - -If we need to know what relations exists in a given MySQL Schema, we can use -the @code{db_datalog_show_tables/1} predicate. As @t{db_datalog_describe/2}, -it does not returns any value, but instead prints to the screen the result of the -@code{SHOW TABLES} command, the same way as it would be in the MySQL prompt. -@example -?- db_datalog_show_tables(myddas). -+-----------------+ -| Tables_in_guest | -+-----------------+ -| Hello World | -+-----------------+ -yes -@end example - -@table @code -@item db_show_tables(+, ?). -@findex db_show_tables/2 -@snindex db_show_tables/2 -@cnindex db_show_tables/2 - -@item db_show_tables(?) -@findex db_show_tables/1 -@snindex db_show_tables/1 -@cnindex db_show_tables/1 - -@end table - -The @code{db_show_tables/2} predicate does the same action as -@code{db_show_tables/1} predicate but with one major difference. The -results are returned by backtracking. For example, given the last query: -@example -?- db_show_tables(myddas,Table). -Table = table('Hello World') ? ; -no -@end example - -@node The MYDDAS MySQL Top Level, Other MYDDAS Properties, Enumerating Relations, MYDDAS -@section The MYDDAS MySQL Top Level - - -@table @code -@item db_top_level(+,+,+,+,+). -@findex db_top_level/5 -@snindex db_top_level/5 -@cnindex db_top_level/5 - -@item db_top_level(+,+,+,+). -@findex db_top_level/4 -@snindex db_top_level/4 -@cnindex db_top_level/4 - -@end table - -Through MYDDAS is also possible to access the MySQL Database Server, in -the same wthe mysql client. In this mode, is possible to query the -SQL server by just using the standard SQL language. This mode is exactly the same as -different from the standard mysql client. We can use this -mode, by invoking the db top level/5. as one of the following: -@example -?- db_top_level(mysql,Connection,Host/Database,User,Password). -?- db_top_level(mysql,Connection,Host/Database/Port,User,Password). -?- db_top_level(mysql,Connection,Host/Database/UnixSocket,User,Password). -?- db_top_level(mysql,Connection,Host/Database/Port/UnixSocket,User,Password). -@end example - -Usage is similar as the one described for the @code{db_open/5} predicate -discussed above. If the login is successful, automatically the prompt of -the mysql client will be used. For example: -@example - ?- db_top_level(mysql,con1,localhost/guest_db,guest,''). -@end example -opens a -connection identified by the @code{con1} atom, to an instance of a MySQL server -running on host @code{localhost}, using database guest @code{db} and user @code{guest} with -empty password. After this is possible to use MYDDAS as the mysql -client. -@example - ?- db_top_level(mysql,con1,localhost/guest_db,guest,''). -Reading table information for completion of table and column names -You can turn off this feature to get a quicker startup with -A - -Welcome to the MySQL monitor. -Commands end with ; or \g. - -Your MySQL connection id is 4468 to server version: 4.0.20 -Type 'help;' or '\h' for help. -Type '\c' to clear the buffer. -mysql> exit -Bye -yes -?- -@end example - -@node Other MYDDAS Properties, , The MYDDAS MySQL Top Level , MYDDAS -@section Other MYDDAS Properties - - -@table @code -@item db_verbose(+). -@item db_top_level(+,+,+,+). -@end table - -When we ask a question to YAP, using a predicate asserted by -@code{db_import/3}, or by @code{db_view/3}, this will generate a SQL -@code{QUERY}. If we want to see that query, we must to this at a given -point in our session on YAP. -@example -?- db_verbose(1). -yes -?- -@end example -If we want to -disable this feature, we must call the @code{db_verbose/1} predicate with the value 0. - -@table @code -@item db_module(?). -@findex db_module/1 -@snindex db_module/1 -@cnindex db_module/1 - -@end table - -When we create a new database predicate, by using @code{db_import/3}, -@code{db_view/3} or @code{db_insert/3}, that predicate will be asserted -by default on the @code{user} module. If we want to change this value, we can -use the @code{db_module/1} predicate to do so. -@example -?- db_module(lists). -yes -?- -@end example -By executing this predicate, all of the predicates asserted by the -predicates enumerated earlier will created in the lists module. -If we want to put back the value on default, we can manually put the -value user. Example: -@example -?- db_module(user). -yes -?- -@end example - -We can also see in what module the predicates are being asserted by doing: -@example -?- db_module(X). -X=user -yes - ?- -@end example - -@table @code -@item db_my_result_set(?). -@findex db_my_result_set/1 -@snindex db_my_result_set/1 -@cnindex db_my_result_set/1 - -@end table - - -The MySQL C API permits two modes for transferring the data generated by -a query to the client, in our case YAP. The first mode, and the default -mode used by the MYDDAS-MySQL, is to store the result. This mode copies all the -information generated to the client side. -@example -?- db_my_result_set(X). -X=store_result -yes -@end example - - -The other mode that we can use is use result. This one uses the result -set created directly from the server. If we want to use this mode, he -simply do -@example - ?- db_my_result_set(use_result). -yes -@end example -After this command, all -of the database predicates will use use result by default. We can change -this by doing again @code{db_my_result_set(store_result)}. - -@table @code -@item db_my_sql_mode(+Conn,?SQL_Mode). -@findex db_my_sql_mode/2 -@snindex db_my_sql_mode/2 -@cnindex db_my_sql_mode/2 - -@item db_my_sql_mode(?SQL_Mode). -@findex db_my_sql_mode/1 -@snindex db_my_sql_mode/1 -@cnindex db_my_sql_mode/1 - -@end table - -The MySQL server allows the user to change the SQL mode. This can be -very useful for debugging proposes. For example, if we want MySQL server -not to ignore the INSERT statement warnings and instead of taking -action, report an error, we could use the following SQL mode. -@example - ?-db_my_sql_mode(traditional). yes -@end example -You can see the available SQL Modes at the MySQL homepage at -@url{http://www.mysql.org}. - -@node Real, Threads, MYDDAS, Extensions - -@chapter Real:: Talking to the R language - -@ifplaintext - -@copydoc real - -@end ifplaintext - -@node Threads, Parallelism, Real, Extensions -@chapter Threads - -YAP implements a SWI-Prolog compatible multithreading -library. Like in SWI-Prolog, Prolog threads have their own stacks and -only share the Prolog @emph{heap}: predicates, records, flags and other -global non-backtrackable data. The package is based on the POSIX thread -standard (Butenhof:1997:PPT) used on most popular systems except -for MS-Windows. - -@comment On Windows it uses the -@comment \url[pthread-win32]{http://sources.redhat.com/pthreads-win32/} emulation -@comment of POSIX threads mixed with the Windows native API for smoother and -@comment faster operation. - -@menu -Subnodes of Threads -* Creating and Destroying Prolog Threads:: -* Monitoring Threads:: -* Thread Communication:: -* Thread Synchronisation:: - -Subnodes of Thread Communication -* Message Queues:: -* Signalling Threads:: -* Threads and Dynamic Predicates:: -@end menu - -@node Creating and Destroying Prolog Threads, Monitoring Threads, ,Threads -@section Creating and Destroying Prolog Threads - -@table @code - -@item thread_create(:@var{Goal}, -@var{Id}, +@var{Options}) -@findex thread_create/3 -@snindex thread_create/3 -@cnindex thread_create/3 - -Create a new Prolog thread (and underlying C-thread) and start it -by executing @var{Goal}. If the thread is created successfully, the -thread-identifier of the created thread is unified to @var{Id}. -@var{Options} is a list of options. Currently defined options are: - -@table @code - @item stack -Set the limit in K-Bytes to which the Prolog stacks of -this thread may grow. If omitted, the limit of the calling thread is -used. See also the commandline @code{-S} option. - - @item trail -Set the limit in K-Bytes to which the trail stack of this thread may -grow. If omitted, the limit of the calling thread is used. See also the -commandline option @code{-T}. - - @item alias -Associate an alias-name with the thread. This named may be used to -refer to the thread and remains valid until the thread is joined -(see @code{thread_join/2}). - - @item at_exit -Define an exit hook for the thread. This hook is called when the thread -terminates, no matter its exit status. - - @item detached -If @code{false} (default), the thread can be waited for using -@code{thread_join/2}. @code{thread_join/2} must be called on this thread -to reclaim the all resources associated to the thread. If @code{true}, -the system will reclaim all associated resources automatically after the -thread finishes. Please note that thread identifiers are freed for reuse -after a detached thread finishes or a normal thread has been joined. -See also @code{thread_join/2} and @code{thread_detach/1}. -@end table - -The @var{Goal} argument is @emph{copied} to the new Prolog engine. -This implies further instantiation of this term in either thread does -not have consequences for the other thread: Prolog threads do not share -data from their stacks. - -@item thread_create(:@var{Goal}, -@var{Id}) -@findex thread_create/2 -@snindex thread_create/2 -@cnindex thread_create/2 - -Create a new Prolog thread using default options. See @code{thread_create/3}. - -@item thread_create(:@var{Goal}) -@findex thread_create/1 -@snindex thread_create/1 -@cnindex thread_create/1 - -Create a new Prolog detached thread using default options. See @code{thread_create/3}. - -@item thread_self(-@var{Id}) -@findex thread_self/1 -@snindex thread_self/1 -@cnindex thread_self/1 -Get the Prolog thread identifier of the running thread. If the thread -has an alias, the alias-name is returned. - -@item thread_join(+@var{Id}, -@var{Status}) -@findex thread_join/2 -@snindex thread_join/2 -@cnindex thread_join/2 -Wait for the termination of thread with given @var{Id}. Then unify the -result-status of the thread with @var{Status}. After this call, -@var{Id} becomes invalid and all resources associated with the thread -are reclaimed. Note that threads with the attribute @code{detached} -@code{true} cannot be joined. See also @code{current_thread/2}. - -A thread that has been completed without @code{thread_join/2} being -called on it is partly reclaimed: the Prolog stacks are released and the -C-thread is destroyed. A small data-structure representing the -exit-status of the thread is retained until @code{thread_join/2} is called on -the thread. Defined values for @var{Status} are: - -@table @code - @item true -The goal has been proven successfully. - - @item false -The goal has failed. - - @item exception(@var{Term}) - The thread is terminated on an -exception. See @code{print_message/2} to turn system exceptions into -readable messages. - - @item exited(@var{Term}) -The thread is terminated on @code{thread_exit/1} using the argument @var{Term}. -@end table - - -@item thread_detach(+@var{Id}) -@findex thread_detach/1 -@snindex thread_detach/1 -@cnindex thread_detach/1 -Switch thread into detached-state (see @code{detached} option at -@code{thread_create/3} at runtime. @var{Id} is the identifier of the thread -placed in detached state. - -One of the possible applications is to simplify debugging. Threads that -are created as @code{detached} leave no traces if they crash. For -not-detached threads the status can be inspected using -@code{current_thread/2}. Threads nobody is waiting for may be created -normally and detach themselves just before completion. This way they -leave no traces on normal completion and their reason for failure can be -inspected. - -@item thread_yield -@findex thread_yield/0 -@snindex thread_yield/0 -@cnindex thread_yield/0 -Voluntarily relinquish the processor. - -@item thread_exit(+@var{Term}) -@findex thread_exit/1 -@snindex thread_exit/1 -@cnindex thread_exit/1 -Terminates the thread immediately, leaving @code{exited(@var{Term})} as -result-state for @code{thread_join/2}. If the thread has the attribute -@code{detached} @code{true} it terminates, but its exit status cannot be -retrieved using @code{thread_join/2} making the value of @var{Term} -irrelevant. The Prolog stacks and C-thread are reclaimed. - -@item thread_at_exit(:@var{Term}) -@findex thread_at_exit/1 -@snindex thread_at_exit/1 -@cnindex thread_at_exit/1 -Run @var{Goal} just before releasing the thread resources. This is to -be compared to @code{at_halt/1}, but only for the current -thread. These hooks are ran regardless of why the execution of the -thread has been completed. As these hooks are run, the return-code is -already available through @code{thread_property/2} using the result of -@code{thread_self/1} as thread-identifier. If you want to guarantee the -execution of an exit hook no matter how the thread terminates (the thread -can be aborted before reaching the @code{thread_at_exit/1} call), consider -using instead the @code{at_exit/1} option of @code{thread_create/3}. - -@item thread_setconcurrency(+@var{Old}, -@var{New}) -@findex thread_setconcurrency/2 -@snindex thread_setconcurrency/2 -@cnindex thread_setconcurrency/2 -Determine the concurrency of the process, which is defined as the -maximum number of concurrently active threads. `Active' here means -they are using CPU time. This option is provided if the -thread-implementation provides -@code{pthread_setconcurrency()}. Solaris is a typical example of this -family. On other systems this predicate unifies @var{Old} to 0 (zero) -and succeeds silently. - -@item thread_sleep(+@var{Time}) -@findex thread_sleep/1 -@snindex thread_sleep/1 -@cnindex thread_sleep/1 -Make current thread sleep for @var{Time} seconds. @var{Time} may be an -integer or a floating point number. When time is zero or a negative value -the call succeeds and returns immediately. This call should not be used if -alarms are also being used. -@end table - - -@node Monitoring Threads, Thread Communication,Creating and Destroying Prolog Threads,Threads -@section Monitoring Threads - -Normal multi-threaded applications should not need these the predicates -from this section because almost any usage of these predicates is -unsafe. For example checking the existence of a thread before signalling -it is of no use as it may vanish between the two calls. Catching -exceptions using @code{catch/3} is the only safe way to deal with -thread-existence errors. - -These predicates are provided for diagnosis and monitoring tasks. - - -@table @code -@item thread_property(?@var{Id}, ?@var{Property}) -@findex thread_property/2 -@snindex thread_property/2 -@cnindex thread_property/2 -Enumerates the properties of the specified thread. -Calling @code{thread_property/2} does not influence any thread. See also -@code{thread_join/2}. For threads that have an alias-name, this name can -be used in @var{Id} instead of the numerical thread identifier. -@var{Property} is one of: - -@table @code - @item status(@var{Status}) -The thread status of a thread (see below). - - @item alias(@var{Alias}) -The thread alias, if it exists. - - @item at_exit(@var{AtExit}) -The thread exit hook, if defined (not available if the thread is already terminated). - - @item detached(@var{Boolean}) -The detached state of the thread. - - @item stack(@var{Size}) -The thread stack data-area size. - - @item trail(@var{Size}) -The thread trail data-area size. - - @item system(@var{Size}) -The thread system data-area size. -@end table - -@item current_thread(+@var{Id}, -@var{Status}) -@findex current_thread/2 -@snindex current_thread/2 -@cnindex current_thread/2 -Enumerates identifiers and status of all currently known threads. -Calling @code{current_thread/2} does not influence any thread. See also -@code{thread_join/2}. For threads that have an alias-name, this name is -returned in @var{Id} instead of the numerical thread identifier. -@var{Status} is one of: - -@table @code - @item running -The thread is running. This is the initial status of a thread. Please -note that threads waiting for something are considered running too. - - @item false -The @var{Goal} of the thread has been completed and failed. - - @item true -The @var{Goal} of the thread has been completed and succeeded. - - @item exited(@var{Term}) -The @var{Goal} of the thread has been terminated using @code{thread_exit/1} -with @var{Term} as argument. If the underlying native thread has -exited (using pthread_exit()) @var{Term} is unbound. - - @item exception(@var{Term}) -The @var{Goal} of the thread has been terminated due to an uncaught -exception (see @code{throw/1} and @code{catch/3}). -@end table - -@item thread_statistics(+@var{Id}, +@var{Key}, -@var{Value}) -@findex thread_statistics/3 -@snindex thread_statistics/3 -@cnindex thread_statistics/3 -Obtains statistical information on thread @var{Id} as @code{statistics/2} -does in single-threaded applications. This call returns all keys -of @code{statistics/2}, although only information statistics about the -stacks and CPU time yield different values for each thread. - -@item mutex_statistics -@findex mutex_statistics/0 -@snindex mutex_statistics/0 -@cnindex mutex_statistics/0 -Print usage statistics on internal mutexes and mutexes associated -with dynamic predicates. For each mutex two numbers are printed: -the number of times the mutex was acquired and the number of -collisions: the number times the calling thread has to -wait for the mutex. The collision-count is not available on -Windows as this would break portability to Windows-95/98/ME or -significantly harm performance. Generally collision count is -close to zero on single-CPU hardware. - -@item threads -@findex threads/0 -@snindex threads/0 -@cnindex threads/0 -Prints a table of current threads and their status. -@end table - - -@node Thread Communication, Thread Synchronisation, Monitoring Threads, Threads -@section Thread communication - -@menu -Subnodes of Thread Communication -* Message Queues:: -* Signalling Threads:: -* Threads and Dynamic Predicates:: -@end menu - -@node Message Queues, Signalling Threads, ,Thread Communication -@subsection Message Queues - -Prolog threads can exchange data using dynamic predicates, database -records, and other globally shared data. These provide no suitable means -to wait for data or a condition as they can only be checked in an -expensive polling loop. @emph{Message queues} provide a means for -threads to wait for data or conditions without using the CPU. - -Each thread has a message-queue attached to it that is identified -by the thread. Additional queues are created using -@code{message_queue_create/2}. - -@table @code - -@item thread_send_message(+@var{Term}) -@findex thread_send_message/1 -@snindex thread_send_message/1 -@cnindex thread_send_message/1 -Places @var{Term} in the message-queue of the thread running the goal. -Any term can be placed in a message queue, but note that the term is -copied to the receiving thread and variable-bindings are thus lost. -This call returns immediately. - -@item thread_send_message(+@var{QueueOrThreadId}, +@var{Term}) -@findex thread_send_message/2 -@snindex thread_send_message/2 -@cnindex thread_send_message/2 -Place @var{Term} in the given queue or default queue of the indicated -thread (which can even be the message queue of itself (see -@code{thread_self/1}). Any term can be placed in a message queue, but note that -the term is copied to the receiving thread and variable-bindings are -thus lost. This call returns immediately. - -If more than one thread is waiting for messages on the given queue and -at least one of these is waiting with a partially instantiated -@var{Term}, the waiting threads are @emph{all} sent a wakeup signal, -starting a rush for the available messages in the queue. This behaviour -can seriously harm performance with many threads waiting on the same -queue as all-but-the-winner perform a useless scan of the queue. If -there is only one waiting thread or all waiting threads wait with an -unbound variable an arbitrary thread is restarted to scan the queue. -@comment \footnote{See the documentation for the POSIX thread functions -@comment pthread_cond_signal() v.s.\ pthread_cond_broadcastt() -@comment for background information.} - -@item thread_get_message(?@var{Term}) -@findex thread_get_message/1 -@snindex thread_get_message/1 -@cnindex thread_get_message/1 -Examines the thread message-queue and if necessary blocks execution -until a term that unifies to @var{Term} arrives in the queue. After -a term from the queue has been unified unified to @var{Term}, the -term is deleted from the queue and this predicate returns. - -Please note that not-unifying messages remain in the queue. After -the following has been executed, thread 1 has the term @code{gnu} -in its queue and continues execution using @var{A} is @code{gnat}. - -@example - - thread_get_message(a(A)), - - - thread_send_message(b(gnu)), - thread_send_message(a(gnat)), -@end example - -See also @code{thread_peek_message/1}. - -@item message_queue_create(?@var{Queue}) -@findex message_queue_create/1 -@snindex message_queue_create/1 -@cnindex message_queue_create/1 -If @var{Queue} is an atom, create a named queue. To avoid ambiguity -on @code{thread_send_message/2}, the name of a queue may not be in use -as a thread-name. If @var{Queue} is unbound an anonymous queue is -created and @var{Queue} is unified to its identifier. - -@item message_queue_destroy(+@var{Queue}) -@findex message_queue_destroy/1 -@snindex message_queue_destroy/1 -@cnindex message_queue_destroy/1 -Destroy a message queue created with @code{message_queue_create/1}. It is -@emph{not} allows to destroy the queue of a thread. Neither is it -allowed to destroy a queue other threads are waiting for or, for -anonymous message queues, may try to wait for later. - -@item thread_get_message(+@var{Queue}, ?@var{Term}) -@findex thread_get_message/2 -@snindex thread_get_message/2 -@cnindex thread_get_message/2 -As @code{thread_get_message/1}, operating on a given queue. It is allowed to -peek into another thread's message queue, an operation that can be used -to check whether a thread has swallowed a message sent to it. - -@item thread_peek_message(?@var{Term}) -@findex thread_peek_message/1 -@snindex thread_peek_message/1 -@cnindex thread_peek_message/1 -Examines the thread message-queue and compares the queued terms -with @var{Term} until one unifies or the end of the queue has been -reached. In the first case the call succeeds (possibly instantiating -@var{Term}. If no term from the queue unifies this call fails. - -@item thread_peek_message(+@var{Queue}, ?@var{Term}) -@findex thread_peek_message/2 -@snindex thread_peek_message/2 -@cnindex thread_peek_message/2 -As @code{thread_peek_message/1}, operating on a given queue. It is allowed to -peek into another thread's message queue, an operation that can be used -to check whether a thread has swallowed a message sent to it. - -@end table - - -Explicit message queues are designed with the @emph{worker-pool} model -in mind, where multiple threads wait on a single queue and pick up the -first goal to execute. Below is a simple implementation where the -workers execute arbitrary Prolog goals. Note that this example provides -no means to tell when all work is done. This must be realised using -additional synchronisation. - -@example -% create_workers(+Id, +N) -% -% Create a pool with given Id and number of workers. - -create_workers(Id, N) :- - message_queue_create(Id), - forall(between(1, N, _), - thread_create(do_work(Id), _, [])). - -do_work(Id) :- - repeat, - thread_get_message(Id, Goal), - ( catch(Goal, E, print_message(error, E)) - -> true - ; print_message(error, goal_failed(Goal, worker(Id))) - ), - fail. - -% work(+Id, +Goal) -% -% Post work to be done by the pool - -work(Id, Goal) :- - thread_send_message(Id, Goal). -@end example - -@node Signalling Threads, Threads and Dynamic Predicates,Message Queues, Thread Communication -@subsection Signalling Threads - -These predicates provide a mechanism to make another thread execute some -goal as an @emph{interrupt}. Signalling threads is safe as these -interrupts are only checked at safe points in the virtual machine. -Nevertheless, signalling in multi-threaded environments should be -handled with care as the receiving thread may hold a @emph{mutex} -(see @code{with_mutex/2}). Signalling probably only makes sense to start -debugging threads and to cancel no-longer-needed threads with @code{throw/1}, -where the receiving thread should be designed carefully do handle -exceptions at any point. - -@table @code -@item thread_signal(+@var{ThreadId}, :@var{Goal}) -@findex thread_signal/2 -@snindex thread_signal/2 -@cnindex thread_signal/2 -Make thread @var{ThreadId} execute @var{Goal} at the first -opportunity. In the current implementation, this implies at the first -pass through the @emph{Call-port}. The predicate @code{thread_signal/2} -itself places @var{Goal} into the signalled-thread's signal queue -and returns immediately. - -Signals (interrupts) do not cooperate well with the world of -multi-threading, mainly because the status of mutexes cannot be -guaranteed easily. At the call-port, the Prolog virtual machine -holds no locks and therefore the asynchronous execution is safe. - -@var{Goal} can be any valid Prolog goal, including @code{throw/1} to make -the receiving thread generate an exception and @code{trace/0} to start -tracing the receiving thread. - -@comment In the Windows version, the receiving thread immediately executes -@comment the signal if it reaches a Windows GetMessage() call, which generally -@comment happens of the thread is waiting for (user-)input. -@end table - -@node Threads and Dynamic Predicates, , Signalling Threads, Thread Communication -@subsection Threads and Dynamic Predicates - -Besides queues threads can share and exchange data using dynamic -predicates. The multi-threaded version knows about two types of -dynamic predicates. By default, a predicate declared @emph{dynamic} -(see @code{dynamic/1}) is shared by all threads. Each thread may -assert, retract and run the dynamic predicate. Synchronisation inside -Prolog guarantees the consistency of the predicate. Updates are -@emph{logical}: visible clauses are not affected by assert/retract -after a query started on the predicate. In many cases primitive from -thread synchronisation should be used to ensure application invariants on -the predicate are maintained. - -Besides shared predicates, dynamic predicates can be declared with the -@code{thread_local/1} directive. Such predicates share their -attributes, but the clause-list is different in each thread. - -@table @code -@item thread_local(@var{+Functor/Arity}) -@findex thread_local/1 (directive) -@snindex thread_local/1 (directive) -@cnindex thread_local/1 (directive) -related to the dynamic/1 directive. It tells the system that the -predicate may be modified using @code{assert/1}, @code{retract/1}, -etc, during execution of the program. Unlike normal shared dynamic -data however each thread has its own clause-list for the predicate. -As a thread starts, this clause list is empty. If there are still -clauses as the thread terminates these are automatically reclaimed by -the system. The @code{thread_local} property implies -the property @code{dynamic}. - -Thread-local dynamic predicates are intended for maintaining -thread-specific state or intermediate results of a computation. - -It is not recommended to put clauses for a thread-local predicate into -a file as in the example below as the clause is only visible from the -thread that loaded the source-file. All other threads start with an -empty clause-list. - -@example -:- thread_local - foo/1. - -foo(gnat). -@end example - -@end table - - -@node Thread Synchronisation, , Thread Communication, Threads -@section Thread Synchronisation - -All internal Prolog operations are thread-safe. This implies two Prolog -threads can operate on the same dynamic predicate without corrupting the -consistency of the predicate. This section deals with user-level -@emph{mutexes} (called @emph{monitors} in ADA or -@emph{critical-sections} by Microsoft). A mutex is a -@emph{MUT}ual @emph{EX}clusive device, which implies at most one thread -can @emph{hold} a mutex. - -Mutexes are used to realise related updates to the Prolog database. -With `related', we refer to the situation where a `transaction' implies -two or more changes to the Prolog database. For example, we have a -predicate @code{address/2}, representing the address of a person and we want -to change the address by retracting the old and asserting the new -address. Between these two operations the database is invalid: this -person has either no address or two addresses, depending on the -assert/retract order. - -Here is how to realise a correct update: - -@example -:- initialization - mutex_create(addressbook). - -change_address(Id, Address) :- - mutex_lock(addressbook), - retractall(address(Id, _)), - asserta(address(Id, Address)), - mutex_unlock(addressbook). -@end example - - -@table @code -@item mutex_create(?@var{MutexId}) -@findex mutex_create/1 -@snindex mutex_create/1 -@cnindex mutex_create/1 -Create a mutex. if @var{MutexId} is an atom, a @emph{named} mutex is -created. If it is a variable, an anonymous mutex reference is returned. -There is no limit to the number of mutexes that can be created. - -@item mutex_destroy(+@var{MutexId}) -@findex mutex_destroy/1 -@snindex mutex_destroy/1 -@cnindex mutex_destroy/1 -Destroy a mutex. After this call, @var{MutexId} becomes invalid and -further references yield an @code{existence_error} exception. - -@item with_mutex(+@var{MutexId}, :@var{Goal}) -@findex with_mutex/2 -@snindex with_mutex/2 -@cnindex with_mutex/2 -Execute @var{Goal} while holding @var{MutexId}. If @var{Goal} leaves -choicepoints, these are destroyed (as in @code{once/1}). The mutex is unlocked -regardless of whether @var{Goal} succeeds, fails or raises an exception. -An exception thrown by @var{Goal} is re-thrown after the mutex has been -successfully unlocked. See also @code{mutex_create/2}. - -Although described in the thread-section, this predicate is also -available in the single-threaded version, where it behaves simply as -@code{once/1}. - -@item mutex_lock(+@var{MutexId}) -@findex mutex_lock/1 -@snindex mutex_lock/1 -@cnindex mutex_lock/1 -Lock the mutex. Prolog mutexes are @emph{recursive} mutexes: they -can be locked multiple times by the same thread. Only after unlocking -it as many times as it is locked, the mutex becomes available for -locking by other threads. If another thread has locked the mutex the -calling thread is suspended until to mutex is unlocked. - -If @var{MutexId} is an atom, and there is no current mutex with that -name, the mutex is created automatically using @code{mutex_create/1}. This -implies named mutexes need not be declared explicitly. - -Please note that locking and unlocking mutexes should be paired -carefully. Especially make sure to unlock mutexes even if the protected -code fails or raises an exception. For most common cases use -@code{with_mutex/2}, which provides a safer way for handling Prolog-level -mutexes. - -@item mutex_trylock(+@var{MutexId}) -@findex mutex_trylock/1 -@snindex mutex_trylock/1 -@cnindex mutex_trylock/1 -As mutex_lock/1, but if the mutex is held by another thread, this -predicates fails immediately. - -@item mutex_unlock(+@var{MutexId}) -@findex mutex_unlock/1 -@snindex mutex_unlock/1 -@cnindex mutex_unlock/1 -Unlock the mutex. This can only be called if the mutex is held by the -calling thread. If this is not the case, a @code{permission_error} -exception is raised. - -@item mutex_unlock_all -@findex mutex_unlock_all/0 -@snindex mutex_unlock_all/0 -@cnindex mutex_unlock_all/0 -Unlock all mutexes held by the current thread. This call is especially -useful to handle thread-termination using @code{abort/0} or exceptions. See -also @code{thread_signal/2}. - -@item current_mutex(?@var{MutexId}, ?@var{ThreadId}, ?@var{Count}) -@findex current_mutex/3 -@snindex current_mutex/3 -@cnindex current_mutex/3 -Enumerates all existing mutexes. If the mutex is held by some thread, -@var{ThreadId} is unified with the identifier of the holding thread and -@var{Count} with the recursive count of the mutex. Otherwise, -@var{ThreadId} is @code{[]} and @var{Count} is 0. -@end table - - -@node Parallelism, Tabling, Threads, Extensions -@section Parallelism - -@cindex parallelism -@cindex or-parallelism -There has been a sizeable amount of work on an or-parallel -implementation for YAP, called @strong{YAPOr}. Most of this work has -been performed by Ricardo Rocha. In this system parallelism is exploited -implicitly by running several alternatives in or-parallel. This option -can be enabled from the @code{configure} script or by checking the -system's @code{Makefile}. - -@strong{YAPOr} is still a very experimental system, going through rapid -development. The following restrictions are of note: - -@itemize @bullet -@item @strong{YAPOr} currently only supports the Linux/X86 and SPARC/Solaris -platforms. Porting to other Unix-like platforms should be straightforward. - -@item @strong{YAPOr} does not support parallel updates to the -data-base. - -@item @strong{YAPOr} does not support opening or closing of streams during -parallel execution. - -@item Garbage collection and stack shifting are not supported in -@strong{YAPOr}. - -@item Built-ins that cause side-effects can only be executed when -left-most in the search-tree. There are no primitives to provide -asynchronous or cavalier execution of these built-ins, as in Aurora or -Muse. - -@item YAP does not support voluntary suspension of work. -@end itemize - -We expect that some of these restrictions will be removed in future -releases. - -@node Tabling, Low Level Tracing, Parallelism , Extensions -@section Tabling -@cindex tabling - -@strong{YAPTab} is the tabling engine that extends YAP's execution -model to support tabled evaluation for definite programs. YAPTab was -implemented by Ricardo Rocha and its implementation is largely based -on the ground-breaking design of the XSB Prolog system, which -implements the SLG-WAM. Tables are implemented using tries and YAPTab -supports the dynamic intermixing of batched scheduling and local -scheduling at the subgoal level. Currently, the following restrictions -are of note: -@itemize @bullet -@item YAPTab does not handle tabled predicates with loops through negation (undefined behaviour). -@item YAPTab does not handle tabled predicates with cuts (undefined behaviour). -@item YAPTab does not support coroutining (configure error). -@item YAPTab does not support tabling dynamic predicates (permission error). -@end itemize - -To experiment with YAPTab use @code{--enable-tabling} in the configure -script or add @code{-DTABLING} to @code{YAP_EXTRAS} in the system's -@code{Makefile}. We next describe the set of built-ins predicates -designed to interact with YAPTab and control tabled execution: - -@table @code -@item table +@var{P} -@findex table/1 -@snindex table/1 -@cnindex table/1 -Declares predicate @var{P} (or a list of predicates -@var{P1},...,@var{Pn} or [@var{P1},...,@var{Pn}]) as a tabled -predicate. @var{P} must be written in the form -@var{name/arity}. Examples: -@example -:- table son/3. -:- table father/2. -:- table mother/2. -@end example -@noindent or -@example -:- table son/3, father/2, mother/2. -@end example -@noindent or -@example -:- table [son/3, father/2, mother/2]. -@end example - -@item is_tabled(+@var{P}) -@findex is_tabled/1 -@snindex is_tabled/1 -@cnindex is_tabled/1 -Succeeds if the predicate @var{P} (or a list of predicates -@var{P1},...,@var{Pn} or [@var{P1},...,@var{Pn}]), of the form -@var{name/arity}, is a tabled predicate. - -@item tabling_mode(+@var{P},?@var{Mode}) -@findex tabling_mode/2 -@snindex tabling_mode/2 -@cnindex tabling_mode/2 -Sets or reads the default tabling mode for a tabled predicate @var{P} -(or a list of predicates @var{P1},...,@var{Pn} or -[@var{P1},...,@var{Pn}]). The list of @var{Mode} options includes: -@table @code -@item batched - Defines that, by default, batched scheduling is the scheduling - strategy to be used to evaluated calls to predicate @var{P}. -@item local - Defines that, by default, local scheduling is the scheduling - strategy to be used to evaluated calls to predicate @var{P}. -@item exec_answers - Defines that, by default, when a call to predicate @var{P} is - already evaluated (completed), answers are obtained by executing - compiled WAM-like code directly from the trie data - structure. This reduces the loading time when backtracking, but - the order in which answers are obtained is undefined. -@item load_answers - Defines that, by default, when a call to predicate @var{P} is - already evaluated (completed), answers are obtained (as a - consumer) by loading them from the trie data structure. This - guarantees that answers are obtained in the same order as they - were found. Somewhat less efficient but creates less choice-points. -@end table -The default tabling mode for a new tabled predicate is @code{batched} -and @code{exec_answers}. To set the tabling mode for all predicates at -once you can use the @code{yap_flag/2} predicate as described next. - -@item yap_flag(tabling_mode,?@var{Mode}) -@findex tabling_mode (yap_flag/2 option) -Sets or reads the tabling mode for all tabled predicates. The list of -@var{Mode} options includes: -@table @code -@item default - Defines that (i) all calls to tabled predicates are evaluated - using the predicate default mode, and that (ii) answers for all - completed calls are obtained by using the predicate default mode. -@item batched - Defines that all calls to tabled predicates are evaluated using - batched scheduling. This option ignores the default tabling mode - of each predicate. -@item local - Defines that all calls to tabled predicates are evaluated using - local scheduling. This option ignores the default tabling mode - of each predicate. -@item exec_answers - Defines that answers for all completed calls are obtained by - executing compiled WAM-like code directly from the trie data - structure. This option ignores the default tabling mode - of each predicate. -@item load_answers - Defines that answers for all completed calls are obtained by - loading them from the trie data structure. This option ignores - the default tabling mode of each predicate. -@end table - -@item abolish_table(+@var{P}) -@findex abolish_table/1 -@snindex abolish_table/1 -@cnindex abolish_table/1 -Removes all the entries from the table space for predicate @var{P} (or -a list of predicates @var{P1},...,@var{Pn} or -[@var{P1},...,@var{Pn}]). The predicate remains as a tabled predicate. - -@item abolish_all_tables/0 -@findex abolish_all_tables/0 -@snindex abolish_all_tables/0 -@cnindex abolish_all_tables/0 -Removes all the entries from the table space for all tabled -predicates. The predicates remain as tabled predicates. - -@item show_table(+@var{P}) -@findex show_table/1 -@snindex show_table/1 -@cnindex show_table/1 -Prints table contents (subgoals and answers) for predicate @var{P} -(or a list of predicates @var{P1},...,@var{Pn} or -[@var{P1},...,@var{Pn}]). - -@item table_statistics(+@var{P}) -@findex table_statistics/1 -@snindex table_statistics/1 -@cnindex table_statistics/1 -Prints table statistics (subgoals and answers) for predicate @var{P} -(or a list of predicates @var{P1},...,@var{Pn} or -[@var{P1},...,@var{Pn}]). - -@item tabling_statistics/0 -@findex tabling_statistics/0 -@snindex tabling_statistics/0 -@cnindex tabling_statistics/0 -Prints statistics on space used by all tables. -@end table - - -@node Low Level Tracing, Low Level Profiling, Tabling, Extensions -@section Tracing at Low Level - -It is possible to follow the flow at abstract machine level if -YAP is compiled with the flag @code{LOW_LEVEL_TRACER}. Note -that this option is of most interest to implementers, as it quickly generates -an huge amount of information. - -Low level tracing can be toggled from an interrupt handler by using the -option @code{T}. There are also two built-ins that activate and -deactivate low level tracing: - -@table @code -@item start_low_level_trace -@findex start_low_level_trace/0 -@snindex start_low_level_trace/0 -@cnindex start_low_level_trace/0 -Begin display of messages at procedure entry and retry. - -@item stop_low_level_trace -@findex stop_low_level_trace/0 -@snindex stop_low_level_trace/0 -@cnindex stop_low_level_trace/0 -Stop display of messages at procedure entry and retry. -@end table - -Note that this compile-time option will slow down execution. - -@node Low Level Profiling, , Low Level Tracing, Extensions -@section Profiling the Abstract Machine - -Implementors may be interested in detecting on which abstract machine -instructions are executed by a program. The @code{ANALYST} flag can give -WAM level information. Note that this option slows down execution very -substantially, and is only of interest to developers of the system -internals, or to system debuggers. - -@table @code -@item reset_op_counters -@findex reset_op_counters/0 -@snindex reset_op_counters/0 -@cnindex reset_op_counters/0 -Reinitialize all counters. - -@item show_op_counters(+@var{A}) -@findex show_op_counters/1 -@snindex show_op_counters/1 -@cnindex show_op_counters/1 -Display the current value for the counters, using label @var{A}. The -label must be an atom. - -@item show_ops_by_group(+@var{A}) -@findex show_ops_by_group/1 -@snindex show_ops_by_group/1 -@cnindex show_ops_by_group/1 -Display the current value for the counters, organized by groups, using -label @var{A}. The label must be an atom. - -@end table - -@node Debugging,Efficiency,Extensions,Top -@section Debugging - -@menu -* Deb Preds:: Debugging Predicates -* Deb Interaction:: Interacting with the debugger -@end menu - -@node Deb Preds, Deb Interaction, , Debugging -@section Debugging Predicates - -The following predicates are available to control the debugging of -programs: - -@table @code -@item debug -@findex debug/0 -@saindex debug/0 -@cyindex debug/0 -Switches the debugger on. - -@item debugging -@findex debugging/0 -@syindex debugging/0 -@cyindex debugging/0 -Outputs status information about the debugger which includes the leash -mode and the existing spy-points, when the debugger is on. - -@item nodebug -@findex nodebug/0 -@syindex nodebug/0 -@cyindex nodebug/0 -Switches the debugger off. - -@item spy +@var{P} -@findex spy/1 -@syindex spy/1 -@cyindex spy/1 - Sets spy-points on all the predicates represented by -@var{P}. @var{P} can either be a single specification or a list of -specifications. Each one must be of the form @var{Name/Arity} -or @var{Name}. In the last case all predicates with the name -@var{Name} will be spied. As in C-Prolog, system predicates and -predicates written in C, cannot be spied. - -@item nospy +@var{P} -@findex nospy/1 -@syindex nospy/1 -@cyindex nospy/1 - Removes spy-points from all predicates specified by @var{P}. -The possible forms for @var{P} are the same as in @code{spy P}. - -@item nospyall -@findex nospyall/0 -@syindex nospyall/0 -@cnindex nospyall/0 -Removes all existing spy-points. - -@item leash(+@var{M}) -@findex leash/1 -@syindex leash/1 -@cyindex leash/1 - Sets leashing mode to @var{M}. -The mode can be specified as: -@table @code -@item full -prompt on Call, Exit, Redo and Fail -@item tight -prompt on Call, Redo and Fail -@item half -prompt on Call and Redo -@item loose -prompt on Call -@item off -never prompt -@item none -never prompt, same as @code{off} -@end table -@noindent -The initial leashing mode is @code{full}. - - -@noindent -The user may also specify directly the debugger ports -where he wants to be prompted. If the argument for leash -is a number @var{N}, each of lower four bits of the number is used to -control prompting at one the ports of the box model. The debugger will -prompt according to the following conditions: - -@itemize @bullet -@item -if @code{N/\ 1 =\= 0} prompt on fail -@item -if @code{N/\ 2 =\= 0} prompt on redo -@item -if @code{N/\ 4 =\= 0} prompt on exit -@item -if @code{N/\ 8 =\= 0} prompt on call -@end itemize -@noindent -Therefore, @code{leash(15)} is equivalent to @code{leash(full)} and -@code{leash(0)} is equivalent to @code{leash(off)}. - -@noindent -Another way of using @code{leash} is to give it a list with the names of -the ports where the debugger should stop. For example, -@code{leash([call,exit,redo,fail])} is the same as @code{leash(full)} or -@code{leash(15)} and @code{leash([fail])} might be used instead of -@code{leash(1)}. - -@item spy_write(+@var{Stream},Term) -@findex spy_write/2 -@snindex spy_write/2 -@cnindex spy_write/2 -If defined by the user, this predicate will be used to print goals by -the debugger instead of @code{write/2}. - -@item trace -@findex trace/0 -@syindex trace/0 -@cyindex trace/0 -Switches on the debugger and starts tracing. - -@item notrace -@findex notrace/0 -@syindex notrace/0 -@cyindex notrace/0 -Ends tracing and exits the debugger. This is the same as -@code{nodebug/0}. - -@end table - - -@node Deb Interaction, , Deb Preds, Debugging -@section Interacting with the debugger - -Debugging with YAP is similar to debugging with C-Prolog. Both systems -include a procedural debugger, based on Byrd's four port model. In this -model, execution is seen at the procedure level: each activation of a -procedure is seen as a box with control flowing into and out of that -box. - - In the four port model control is caught at four key points: before -entering the procedure, after exiting the procedure (meaning successful -evaluation of all queries activated by the procedure), after backtracking but -before trying new alternative to the procedure and after failing the -procedure. Each one of these points is named a port: - -@smallexample -@group - *--------------------------------------* - Call | | Exit ----------> + descendant(X,Y) :- offspring(X,Y). + ---------> - | | - | descendant(X,Z) :- | -<--------- + offspring(X,Y), descendant(Y,Z). + <--------- - Fail | | Redo - *--------------------------------------* -@end group -@end smallexample - -@table @code - -@item Call -The call port is activated before initial invocation of -procedure. Afterwards, execution will try to match the goal with the -head of existing clauses for the procedure. -@item Exit -This port is activated if the procedure succeeds. -Control will now leave the procedure and return to its ancestor. -@item Redo -if the goal, or goals, activated after the call port -fail then backtracking will eventually return control to this procedure -through the redo port. -@item Fail -If all clauses for this predicate fail, then the -invocation fails, and control will try to redo the ancestor of this -invocation. -@end table - -To start debugging, the user will either call @code{trace} or spy the -relevant procedures, entering debug mode, and start execution of the -program. When finding the first spy-point, YAP's debugger will take -control and show a message of the form: - -@example -* (1) call: quicksort([1,2,3],_38) ? -@end example - - The debugger message will be shown while creeping, or at spy-points, -and it includes four or five fields: - -@itemize @bullet -@item - The first three characters are used to point out special states of the -debugger. If the port is exit and the first character is '?', the -current call is non-deterministic, that is, it still has alternatives to -be tried. If the second character is a @code{*}, execution is at a -spy-point. If the third character is a @code{>}, execution has returned -either from a skip, a fail or a redo command. -@item - The second field is the activation number, and uniquely identifies the -activation. The number will start from 1 and will be incremented for -each activation found by the debugger. -@item - In the third field, the debugger shows the active port. -@item - The fourth field is the goal. The goal is written by - @code{write_term/3} on the standard error stream, using the options - given by @code{debugger_print_options}. -@end itemize - - If the active port is leashed, the debugger will prompt the user with a -@code{?}, and wait for a command. A debugger command is just a -character, followed by a return. By default, only the call and redo -entries are leashed, but the @code{leash/1} predicate can be used in -order to make the debugger stop where needed. - - There are several commands available, but the user only needs to -remember the help command, which is @code{h}. This command shows all the -available options, which are: -@table @code -@item c - creep -this command makes YAP continue execution and stop at the next -leashed port. -@item return - creep -the same as c -@item l - leap -YAP will execute until it meets a port for a spied predicate; this mode -keeps all computation history for debugging purposes, so it is more -expensive than standard execution. Use @t{k} or @t{z} for fast execution. -@item k - quasi-leap -similar to leap but faster since the computation history is -not kept; useful when leap becomes too slow. -@item z - zip -same as @t{k} -@item s - skip -YAP will continue execution without showing any messages until -returning to the current activation. Spy-points will be ignored in this -mode. Note that this command keeps all debugging history, use @t{t} for fast execution. This command is meaningless, and therefore illegal, in the fail -and exit ports. -@item t - fast-skip -similar to skip but faster since computation history is not -kept; useful if skip becomes slow. -@item f [@var{GoalId}] - fail -If given no argument, forces YAP to fail the goal, skipping the fail -port and backtracking to the parent. - If @t{f} receives a goal number as -the argument, the command fails all the way to the goal. If goal @var{GoalId} has completed execution, YAP fails until meeting the first active ancestor. -@item r [@var{GoalId}] - retry -This command forces YAP to jump back call to the port. Note that any -side effects of the goal cannot be undone. This command is not available -at the call port. If @t{f} receives a goal number as the argument, the -command retries goal @var{GoalId} instead. If goal @var{GoalId} has -completed execution, YAP fails until meeting the first active ancestor. - -@item a - abort -execution will be aborted, and the interpreter will return to the -top-level. YAP disactivates debug mode, but spypoints are not removed. -@item n - nodebug -stop debugging and continue execution. The command will not clear active -spy-points. -@item e - exit -leave YAP. -@item h - help -show the debugger commands. -@item ! Query -execute a query. YAP will not show the result of the query. -@item b - break -break active execution and launch a break level. This is the same as @code{!break}. -@item + - spy this goal -start spying the active goal. The same as @code{! spy G} where @var{G} -is the active goal. -@item - - nospy this goal -stop spying the active goal. The same as @code{! nospy G} where @var{G} is -the active goal. -@item p - print -shows the active goal using print/1 -@item d - display -shows the active goal using display/1 -@item -
      • The original YAP C-interface exports the YAP engine. -
      • -
      • The @ref swi-c-interface emulates Jan Wielemaker's SWI foreign language interface. -
      • -
      • The @ref yap-cplus-interface is desiged to interface with Object-Oriented systems. -
      • -
      -@end ifplaintext - -Before describing in full detail how to interface to C code, we will examine -a brief example. - -Assume the user requires a predicate @code{my_process_id(Id)} which succeeds -when @var{Id} unifies with the number of the process under which YAP is running. - -In this case we will create a @code{my_process.c} file containing the -C-code described below. - -@c_example -@cartouche -#include "YAP/YapInterface.h" - -static int my_process_id(void) -@{ - YAP_Term pid = YAP_MkIntTerm(getpid()); - YAP_Term out = YAP_ARG1; - return(YAP_Unify(out,pid)); -@} - -void init_my_predicates() -@{ - YAP_UserCPredicate("my_process_id",my_process_id,1); -@} -@end cartouche -@end c_example - -The commands to compile the above file depend on the operating -system. Under Linux (i386 and Alpha) you should use: -@example - gcc -c -shared -fPIC my_process.c - ld -shared -o my_process.so my_process.o -@end example -@noindent -Under WIN32 in a MINGW/CYGWIN environment, using the standard -installation path you should use: -@example - gcc -mno-cygwin -I "c:/Yap/include" -c my_process.c - gcc -mno-cygwin "c:/Yap/bin/yap.dll" --shared -o my_process.dll my_process.o -@end example -@noindent -Under WIN32 in a pure CYGWIN environment, using the standard -installation path, you should use: -@example - gcc -I/usr/local -c my_process.c - gcc -shared -o my_process.dll my_process.o /usr/local/bin/yap.dll -@end example -@noindent -Under Solaris2 it is sufficient to use: -@example - gcc -fPIC -c my_process.c -@end example -@noindent -Under SunOS it is sufficient to use: -@example - gcc -c my_process.c -@end example -@noindent -Under Digital Unix you need to create a @code{so} file. Use: -@example - gcc tst.c -c -fpic - ld my_process.o -o my_process.so -shared -expect_unresolved '*' -@end example -@noindent -and replace my @code{process.so} for my @code{process.o} in the -remainder of the example. -@noindent -And could be loaded, under YAP, by executing the following Prolog goal -@example - load_foreign_files(['my_process'],[],init_my_predicates). -@end example -Note that since YAP4.3.3 you should not give the suffix for object -files. YAP will deduce the correct suffix from the operating system it -is running under. - -After loading that file the following Prolog goal -@example - my_process_id(N) -@end example -@noindent -would unify N with the number of the process under which YAP is running. - - -Having presented a full example, we will now examine in more detail the -contents of the C source code file presented above. - -The include statement is used to make available to the C source code the -macros for the handling of Prolog terms and also some YAP public -definitions. - -The function @code{my_process_id} is the implementation, in C, of the -desired predicate. Note that it returns an integer denoting the success -of failure of the goal and also that it has no arguments even though the -predicate being defined has one. - In fact the arguments of a Prolog predicate written in C are accessed -through macros, defined in the include file, with names @var{YAP_ARG1}, -@var{YAP_ARG2}, ..., @var{YAP_ARG16} or with @var{YAP_A}(@var{N}) -where @var{N} is the argument number (starting with 1). In the present -case the function uses just one local variable of type @code{YAP_Term}, the -type used for holding YAP terms, where the integer returned by the -standard unix function @code{getpid()} is stored as an integer term (the -conversion is done by @code{YAP_MkIntTerm(Int))}. Then it calls the -pre-defined routine @code{YAP_Unify(YAP_Term, YAP_Term)} which in turn returns an -integer denoting success or failure of the unification. - -@findex YAP_UserCPredicate -The role of the procedure @code{init_my_predicates} is to make known to -YAP, by calling @code{YAP_UserCPredicate}, the predicates being -defined in the file. This is in fact why, in the example above, -@code{init_my_predicates} was passed as the third argument to -@code{load_foreign_files/3}. - -The rest of this appendix describes exhaustively how to interface C to YAP. - -@menu -* Manipulating Terms:: Primitives available to the C programmer -* Unifying Terms:: How to Unify Two Prolog Terms -* Manipulating Strings:: From character arrays to Lists of codes and back -* Memory Allocation:: Stealing Memory From YAP -* Controlling Streams:: Control How YAP sees Streams -* Utility Functions:: From character arrays to Lists of codes and back -* Calling YAP From C:: From C to YAP to C to YAP -* Module Manipulation in C:: Create and Test Modules from within C -* Miscellaneous C-Functions:: Other Helpful Interface Functions -* Writing C:: Writing Predicates in C -* Loading Objects:: Loading Object Files -* Save&Rest:: Saving and Restoring -* YAP4 Notes:: Changes in Foreign Predicates Interface -@end menu - -@node Manipulating Terms, Unifying Terms, , C-Interface -@section Terms - -This section provides information about the primitives available to the C -programmer for manipulating Prolog terms. - -Several C typedefs are included in the header file @code{yap/YAPInterface.h} to -describe, in a portable way, the C representation of Prolog terms. -The user should write is programs using this macros to ensure portability of -code across different versions of YAP. - - -The more important typedef is @var{YAP_Term} which is used to denote the -type of a Prolog term. - -Terms, from a point of view of the C-programmer, can be classified as -follows -@table @i -@item uninstantiated variables -@item instantiated variables -@item integers -@item floating-point numbers -@item database references -@item atoms -@item pairs (lists) -@item compound terms -@end table - -The primitive -@table @code -@item YAP_Bool YAP_IsVarTerm(YAP_Term @var{t}) -@findex YAP_IsVarTerm (C-Interface function) -@noindent -returns true iff its argument is an uninstantiated variable. Conversely the -primitive -@item YAP_Bool YAP_NonVarTerm(YAP_Term @var{t}) -@findex YAP_IsNonVarTerm (C-Interface function) -returns true iff its argument is not a variable. -@end table -@noindent - - -The user can create a new uninstantiated variable using the primitive -@table @code - @item YAP_Term YAP_MkVarTerm() -@end table - - -The following primitives can be used to discriminate among the different types -of non-variable terms: -@table @code -@item YAP_Bool YAP_IsIntTerm(YAP_Term @var{t}) -@findex YAP_IsIntTerm (C-Interface function) -@item YAP_Bool YAP_IsFloatTerm(YAP_Term @var{t}) -@findex YAP_IsFloatTerm (C-Interface function) -@item YAP_Bool YAP_IsDbRefTerm(YAP_Term @var{t}) -@findex YAP_IsDBRefTerm (C-Interface function) -@item YAP_Bool YAP_IsAtomTerm(YAP_Term @var{t}) -@findex YAP_IsAtomTerm (C-Interface function) -@item YAP_Bool YAP_IsPairTerm(YAP_Term @var{t}) -@findex YAP_IsPairTerm (C-Interface function) -@item YAP_Bool YAP_IsApplTerm(YAP_Term @var{t}) -@findex YAP_IsApplTerm (C-Interface function) -@item YAP_Bool YAP_IsCompoundTerm(YAP_Term @var{t}) -@findex YAP_IsCompoundTerm (C-Interface function) -@end table - - -The next primitive gives the type of a Prolog term: -@table @code -@item YAP_tag_t YAP_TagOfTerm(YAP_Term @var{t}) -@end table -The set of possible values is an enumerated type, with the following values: -@table @i -@item @code{YAP_TAG_ATT}: an attributed variable -@item @code{YAP_TAG_UNBOUND}: an unbound variable -@item @code{YAP_TAG_REF}: a reference to a term -@item @code{YAP_TAG_PAIR}: a list -@item @code{YAP_TAG_ATOM}: an atom -@item @code{YAP_TAG_INT}: a small integer -@item @code{YAP_TAG_LONG_INT}: a word sized integer -@item @code{YAP_TAG_BIG_INT}: a very large integer -@item @code{YAP_TAG_RATIONAL}: a rational number -@item @code{YAP_TAG_FLOAT}: a floating point number -@item @code{YAP_TAG_OPAQUE}: an opaque term -@item @code{YAP_TAG_APPL}: a compound term -@end table - - -Next, we mention the primitives that allow one to destruct and construct -terms. All the above primitives ensure that their result is -@i{dereferenced}, i.e. that it is not a pointer to another term. - -The following primitives are provided for creating an integer term from an -integer and to access the value of an integer term. -@table @code -@item YAP_Term YAP_MkIntTerm(YAP_Int @var{i}) -@findex YAP_MkIntTerm (C-Interface function) -@item YAP_Int YAP_IntOfTerm(YAP_Term @var{t}) -@findex YAP_IntOfTerm (C-Interface function) -@end table -@noindent -where @code{YAP_Int} is a typedef for the C integer type appropriate for -the machine or compiler in question (normally a long integer). The size -of the allowed integers is implementation dependent but is always -greater or equal to 24 bits: usually 32 bits on 32 bit machines, and 64 -on 64 bit machines. - -The two following primitives play a similar role for floating-point terms -@table @code -@item YAP_Term YAP_MkFloatTerm(YAP_flt @var{double}) -@findex YAP_MkFloatTerm (C-Interface function) - -@item YAP_flt YAP_FloatOfTerm(YAP_Term @var{t}) -@findex YAP_FloatOfTerm (C-Interface function) -@end table -@noindent -where @code{flt} is a typedef for the appropriate C floating point type, -nowadays a @code{double} - -The following primitives are provided for verifying whether a term is -a big int, creating a term from a big integer and to access the value -of a big int from a term. -@table @code -@item YAP_Bool YAP_IsBigNumTerm(YAP_Term @var{t}) -@findex YAP_IsBigNumTerm (C-Interface function) -@item YAP_Term YAP_MkBigNumTerm(void *@var{b}) -@findex YAP_MkBigNumTerm (C-Interface function) -@item void *YAP_BigNumOfTerm(YAP_Term @var{t}, void *@var{b}) -@findex YAP_BigNumOfTerm (C-Interface function) -@end table -@noindent -YAP must support bignum for the configuration you are using (check the -YAP configuration and setup). For now, YAP only supports the GNU GMP -library, and @code{void *} will be a cast for @code{mpz_t}. Notice -that @code{YAP_BigNumOfTerm} requires the number to be already -initialised. As an example, we show how to print a bignum: - -@example -static int -p_print_bignum(void) -@{ - mpz_t mz; - if (!YAP_IsBigNumTerm(YAP_ARG1)) - return FALSE; - - mpz_init(mz); - YAP_BigNumOfTerm(YAP_ARG1, mz); - gmp_printf("Shows up as %Zd\n", mz); - mpz_clear(mz); - return TRUE; -@} -@end example - - -Currently, no primitives are supplied to users for manipulating data base -references. - -A special typedef @code{YAP_Atom} is provided to describe Prolog -@i{atoms} (symbolic constants). The two following primitives can be used -to manipulate atom terms -@table @code - @item YAP_Term YAP_MkAtomTerm(YAP_Atom at) -@findex YAP_MkAtomTerm (C-Interface function) - @item YAP_Atom YAP_AtomOfTerm(YAP_Term @var{t}) -@findex YAP_AtomOfTerm (C-Interface function) -@end table -@noindent -The following primitives are available for associating atoms with their -names -@table @code - @item YAP_Atom YAP_LookupAtom(char * @var{s}) -@findex YAP_LookupAtom (C-Interface function) - @item YAP_Atom YAP_FullLookupAtom(char * @var{s}) -@findex YAP_FullLookupAtom (C-Interface function) - @item char *YAP_AtomName(YAP_Atom @var{t}) -@findex YAP_AtomName (C-Interface function) -@end table -The function @code{YAP_LookupAtom} looks up an atom in the standard hash -table. The function @code{YAP_FullLookupAtom} will also search if the -atom had been "hidden": this is useful for system maintenance from C -code. The functor @code{YAP_AtomName} returns a pointer to the string -for the atom. - -@noindent -The following primitives handle constructing atoms from strings with -wide characters, and vice-versa: -@table @code - @item YAP_Atom YAP_LookupWideAtom(wchar_t * @var{s}) -@findex YAP_LookupWideAtom (C-Interface function) - @item wchar_t *YAP_WideAtomName(YAP_Atom @var{t}) -@findex YAP_WideAtomName (C-Interface function) -@end table - -@noindent -The following primitive tells whether an atom needs wide atoms in its -representation: -@table @code -@item int YAP_IsWideAtom(YAP_Atom @var{t}) -@findex YAP_IsIsWideAtom (C-Interface function) -@end table - -@noindent -The following primitive can be used to obtain the size of an atom in a -representation-independent way: -@table @code - @item int YAP_AtomNameLength(YAP_Atom @var{t}) -@findex YAP_AtomNameLength (C-Interface function) -@end table - -The next routines give users some control over the atom -garbage collector. They allow the user to guarantee that an atom is not -to be garbage collected (this is important if the atom is hold -externally to the Prolog engine, allow it to be collected, and call a -hook on garbage collection: -@table @code - @item int YAP_AtomGetHold(YAP_Atom @var{at}) -@findex YAP_AtomGetHold (C-Interface function) -@item int YAP_AtomReleaseHold(YAP_Atom @var{at}) -@findex YAP_AtomReleaseHold (C-Interface function) - @item int YAP_AGCRegisterHook(YAP_AGC_hook @var{f}) -@findex YAP_AGCHook (C-Interface function) -@end table - -A @i{pair} is a Prolog term which consists of a tuple of two Prolog -terms designated as the @i{head} and the @i{tail} of the term. Pairs are -most often used to build @emph{lists}. The following primitives can be -used to manipulate pairs: -@table @code - @item YAP_Term YAP_MkPairTerm(YAP_Term @var{Head}, YAP_Term @var{Tail}) -@findex YAP_MkPairTerm (C-Interface function) - @item YAP_Term YAP_MkNewPairTerm(void) -@findex YAP_MkNewPairTerm (C-Interface function) - @item YAP_Term YAP_HeadOfTerm(YAP_Term @var{t}) -@findex YAP_HeadOfTerm (C-Interface function) - @item YAP_Term YAP_TailOfTerm(YAP_Term @var{t}) -@findex YAP_TailOfTerm (C-Interface function) - @item YAP_Term YAP_MkListFromTerms(YAP_Term *@var{pt}, YAP_Int *@var{sz}) -@findex YAP_MkListFromTerms (C-Interface function) -@end table -One can construct a new pair from two terms, or one can just build a -pair whose head and tail are new unbound variables. Finally, one can -fetch the head or the tail. - -The last function supports the common operation of constructing a list from an -array of terms of size @var{sz} in a simple sweep. - -Notice that the list constructors can call the garbage collector if -there is not enough space in the global stack. - -A @i{compound} term consists of a @i{functor} and a sequence of terms with -length equal to the @i{arity} of the functor. A functor, described in C by -the typedef @code{Functor}, consists of an atom and of an integer. -The following primitives were designed to manipulate compound terms and -functors -@table @code -@item YAP_Term YAP_MkApplTerm(YAP_Functor @var{f}, unsigned long int @var{n}, YAP_Term[] @var{args}) -@findex YAP_MkApplTerm (C-Interface function) -@item YAP_Term YAP_MkNewApplTerm(YAP_Functor @var{f}, int @var{n}) -@findex YAP_MkNewApplTerm (C-Interface function) -@item YAP_Term YAP_ArgOfTerm(int argno,YAP_Term @var{ts}) -@findex YAP_ArgOfTerm (C-Interface function) - @item YAP_Term *YAP_ArgsOfTerm(YAP_Term @var{ts}) -@findex YAP_ArgsOfTerm (C-Interface function) - @item YAP_Functor YAP_FunctorOfTerm(YAP_Term @var{ts}) -@findex YAP_FunctorOfTerm (C-Interface function) -@end table -@noindent -The @code{YAP_MkApplTerm} function constructs a new term, with functor -@var{f} (of arity @var{n}), and using an array @var{args} of @var{n} -terms with @var{n} equal to the arity of the -functor. @code{YAP_MkNewApplTerm} builds up a compound term whose -arguments are unbound variables. @code{YAP_ArgOfTerm} gives an argument -to a compound term. @code{argno} should be greater or equal to 1 and -less or equal to the arity of the functor. @code{YAP_ArgsOfTerm} -returns a pointer to an array of arguments. - -Notice that the compound term constructors can call the garbage -collector if there is not enough space in the global stack. - -YAP allows one to manipulate the functors of compound term. The function -@code{YAP_FunctorOfTerm} allows one to obtain a variable of type -@code{YAP_Functor} with the functor to a term. The following functions -then allow one to construct functors, and to obtain their name and arity. - -@findex YAP_MkFunctor (C-Interface function) -@findex YAP_NameOfFunctor (C-Interface function) -@findex YAP_ArityOfFunctor (C-Interface function) -@table @code - @item YAP_Functor YAP_MkFunctor(YAP_Atom @var{a},unsigned long int @var{arity}) - @item YAP_Atom YAP_NameOfFunctor(YAP_Functor @var{f}) - @item YAP_Int YAP_ArityOfFunctor(YAP_Functor @var{f}) -@end table -@noindent - -Note that the functor is essentially a pair formed by an atom, and -arity. - -Constructing terms in the stack may lead to overflow. The routine -@table @code - @item int YAP_RequiresExtraStack(size_t @var{min}) -@end table -verifies whether you have at least @var{min} cells free in the stack, -and it returns true if it has to ensure enough memory by calling the -garbage collector and or stack shifter. The routine returns false if no -memory is needed, and a negative number if it cannot provide enough -memory. - -You can set @var{min} to zero if you do not know how much room you need -but you do know you do not need a big chunk at a single go. Usually, the routine -would usually be called together with a long-jump to restart the -code. Slots can also be used if there is small state. - -@node Unifying Terms, Manipulating Strings, Manipulating Terms, C-Interface -@section Unification - -@findex YAP_Unify (C-Interface function) -YAP provides a single routine to attempt the unification of two Prolog -terms. The routine may succeed or fail: -@table @code - @item Int YAP_Unify(YAP_Term @var{a}, YAP_Term @var{b}) -@end table -@noindent -The routine attempts to unify the terms @var{a} and -@var{b} returning @code{TRUE} if the unification succeeds and @code{FALSE} -otherwise. - -@node Manipulating Strings, Memory Allocation, Unifying Terms, C-Interface -@section Strings - -@findex YAP_StringToBuffer (C-Interface function) -The YAP C-interface now includes an utility routine to copy a string -represented as a list of a character codes to a previously allocated buffer -@table @code - @item int YAP_StringToBuffer(YAP_Term @var{String}, char *@var{buf}, unsigned int @var{bufsize}) -@end table -@noindent -The routine copies the list of character codes @var{String} to a -previously allocated buffer @var{buf}. The string including a -terminating null character must fit in @var{bufsize} characters, -otherwise the routine will simply fail. The @var{StringToBuffer} routine -fails and generates an exception if @var{String} is not a valid string. - -@findex YAP_BufferToString (C-Interface function) -@findex YAP_NBufferToString (C-Interface function) -@findex YAP_WideBufferToString (C-Interface function) -@findex YAP_NWideBufferToString (C-Interface function) -@findex YAP_BufferToAtomList (C-Interface function) -@findex YAP_NBufferToAtomList (C-Interface function) -@findex YAP_WideBufferToAtomList (C-Interface function) -@findex YAP_NWideBufferToAtomList (C-Interface function) -@findex YAP_BufferToDiffList (C-Interface function) -@findex YAP_NBufferToDiffList (C-Interface function) -@findex YAP_WideBufferToDiffList (C-Interface function) -@findex YAP_NWideBufferToDiffList (C-Interface function) -The C-interface also includes utility routines to do the reverse, that -is, to copy a from a buffer to a list of character codes, to a -difference list, or to a list of -character atoms. The routines work either on strings of characters or -strings of wide characters: -@table @code -@item YAP_Term YAP_BufferToString(char *@var{buf}) - @item YAP_Term YAP_NBufferToString(char *@var{buf}, size_t @var{len}) -@item YAP_Term YAP_WideBufferToString(wchar_t *@var{buf}) -@item YAP_Term YAP_NWideBufferToString(wchar_t *@var{buf}, size_t @var{len}) -@item YAP_Term YAP_BufferToAtomList(char *@var{buf}) -@item YAP_Term YAP_NBufferToAtomList(char *@var{buf}, size_t @var{len}) -@item YAP_Term YAP_WideBufferToAtomList(wchar_t *@var{buf}) -@item YAP_Term YAP_NWideBufferToAtomList(wchar_t *@var{buf}, size_t @var{len}) -@end table -@noindent -Users are advised to use the @var{N} version of the routines. Otherwise, -the user-provided string must include a terminating null character. - -@findex YAP_ReadBuffer (C-Interface function) -The C-interface function calls the parser on a sequence of characters -stored at @var{buf} and returns the resulting term. -@table @code - @item YAP_Term YAP_ReadBuffer(char *@var{buf},YAP_Term *@var{error}) -@end table -@noindent -The user-provided string must include a terminating null -character. Syntax errors will cause returning @code{FALSE} and binding -@var{error} to a Prolog term. - -@findex YAP_IntsToList (C-Interface function) -@findex YAP_FloatsToList (C-Interface function) -These C-interface functions are useful when converting chunks of data to Prolog: -@table @code -@item YAP_Term YAP_FloatsToList(double *@var{buf},size_t @var{sz}) -@item YAP_Term YAP_IntsToList(YAP_Int *@var{buf},size_t @var{sz}) -@end table -@noindent -Notice that they are unsafe, and may call the garbage collector. They -return 0 on error. - -@findex YAP_ListToInts (C-Interface function) -@findex YAP_ToListFloats (C-Interface function) -These C-interface functions are useful when converting Prolog lists to arrays: -@table @code -@item YAP_Int YAP_IntsToList(YAP_Term t, YAP_Int *@var{buf},size_t @var{sz}) -@item YAP_Int YAP_FloatsToList(YAP_Term t, double *@var{buf},size_t @var{sz}) -@end table -@noindent -They return the number of integers scanned, up to a maximum of @t{sz}, -and @t{-1} on error. - -@node Memory Allocation, Controlling Streams, Manipulating Strings, C-Interface -@section Memory Allocation - -@findex YAP_AllocSpaceFromYAP (C-Interface function) -The next routine can be used to ask space from the Prolog data-base: -@table @code - @item void *YAP_AllocSpaceFromYAP(int @var{size}) -@end table -@noindent -The routine returns a pointer to a buffer allocated from the code area, -or @code{NULL} if sufficient space was not available. - -@findex YAP_FreeSpaceFromYAP (C-Interface function) -The space allocated with @code{YAP_AllocSpaceFromYAP} can be released -back to YAP by using: -@table @code - @item void YAP_FreeSpaceFromYAP(void *@var{buf}) -@end table -@noindent -The routine releases a buffer allocated from the code area. The system -may crash if @code{buf} is not a valid pointer to a buffer in the code -area. - -@node Controlling Streams, Utility Functions, Memory Allocation, C-Interface -@section Controlling YAP Streams from @code{C} - -@findex YAP_StreamToFileNo (C-Interface function) -The C-Interface also provides the C-application with a measure of -control over the YAP Input/Output system. The first routine allows one -to find a file number given a current stream: -@table @code - @item int YAP_StreamToFileNo(YAP_Term @var{stream}) -@end table -@noindent -This function gives the file descriptor for a currently available -stream. Note that null streams and in memory streams do not have -corresponding open streams, so the routine will return a -negative. Moreover, YAP will not be aware of any direct operations on -this stream, so information on, say, current stream position, may become -stale. - -@findex YAP_CloseAllOpenStreams (C-Interface function) -A second routine that is sometimes useful is: -@table @code -@item void YAP_CloseAllOpenStreams(void) -@end table -@noindent -This routine closes the YAP Input/Output system except for the first -three streams, that are always associated with the three standard Unix -streams. It is most useful if you are doing @code{fork()}. - -@findex YAP_FlushAllStreams (C-Interface function) -Last, one may sometimes need to flush all streams: -@table @code - @item void YAP_CloseAllOpenStreams(void) -@end table -@noindent -It is also useful before you do a @code{fork()}, or otherwise you may -have trouble with unflushed output. - -@findex YAP_OpenStream (C-Interface function) -The next routine allows a currently open file to become a stream. The -routine receives as arguments a file descriptor, the true file name as a -string, an atom with the user name, and a set of flags: -@table @code - @item void YAP_OpenStream(void *@var{FD}, char *@var{name}, YAP_Term @var{t}, int @var{flags}) -@end table -@noindent -The available flags are @code{YAP_INPUT_STREAM}, -@code{YAP_OUTPUT_STREAM}, @code{YAP_APPEND_STREAM}, -@code{YAP_PIPE_STREAM}, @code{YAP_TTY_STREAM}, @code{YAP_POPEN_STREAM}, -@code{YAP_BINARY_STREAM}, and @code{YAP_SEEKABLE_STREAM}. By default, the -stream is supposed to be at position 0. The argument @var{name} gives -the name by which YAP should know the new stream. - -@node Utility Functions, Calling YAP From C, Controlling Streams, C-Interface -@section Utility Functions in @code{C} - - -The C-Interface provides the C-application with a a number of utility -functions that are useful. - - -@findex YAP_Record (C-Interface function) -The first provides a way to insert a term into the data-base -@table @code -@item void *YAP_Record(YAP_Term @var{t}) -@end table -@noindent -This function returns a pointer to a copy of the term in the database -(or to @t{NULL} if the operation fails. - -@findex YAP_Recorded (C-Interface function) -The next functions provides a way to recover the term from the data-base: -@table @code - @item YAP_Term YAP_Recorded(void *@var{handle}) -@end table -@noindent -Notice that the semantics are the same as for @code{recorded/3}: this -function creates a new copy of the term in the stack, with fresh -variables. The function returns @t{0L} if it cannot create a new term. - -@findex YAP_Erase (C-Interface function) -Last, the next function allows one to recover space: -@table @code - @item int YAP_Erase(void *@var{handle}) -@end table -@noindent -Notice that any accesses using @var{handle} after this operation may -lead to a crash. - -The following functions are often required to compare terms. - -@findex YAP_ExactlyEqual (C-Interface function) -Succeed if two terms are actually the same term, as in -@code{==/2}: -@table @code -@item int YAP_ExactlyEqual(YAP_Term t1, YAP_Term t2) -@end table -@noindent - -The next function succeeds if two terms are variant terms, and returns -0 otherwise, as -@code{=@=/2}: -@table @code - @item int YAP_Variant(YAP_Term t1, YAP_Term t2) -@end table -@noindent - -The next functions deal with numbering variables in terms: -@table @code - @item int YAP_NumberVars(YAP_Term t, YAP_Int first_number) - @item YAP_Term YAP_UnNumberVars(YAP_Term t) - @item int YAP_IsNumberedVariable(YAP_Term t) -@end table -@noindent - -The next one returns the length of a well-formed list @var{t}, or -@code{-1} otherwise: -@table @code -@item Int YAP_ListLength(YAP_Term t) -@end table -@noindent - - -Last, this function succeeds if two terms are unifiable: -@code{=@=/2}: -@table @code - @item int YAP_Unifiable(YAP_Term t1, YAP_Term t2) -@end table -@noindent - -The second function computes a hash function for a term, as in -@code{term_hash/4}. -@table @code - @item YAP_Int YAP_TermHash(YAP_Term t, YAP_Int range, YAP_Int depth, int ignore_variables)); -@end table -@noindent -The first three arguments follow @code{term_has/4}. The last argument -indicates what to do if we find a variable: if @code{0} fail, otherwise -ignore the variable. - -@node Calling YAP From C, Module Manipulation in C, Utility Functions, C-Interface -@section From @code{C} back to Prolog - -@findex YAP_RunGoal (C-Interface function) -There are several ways to call Prolog code from C-code. By default, the -@code{YAP_RunGoal()} should be used for this task. It assumes the engine -has been initialised before: - -@table @code -@item YAP_Int YAP_RunGoal(YAP_Term Goal) -@end table -Execute query @var{Goal} and return 1 if the query succeeds, and 0 -otherwise. The predicate returns 0 if failure, otherwise it will return -an @var{YAP_Term}. - -Quite often, one wants to run a query once. In this case you should use -@var{Goal}: -@table @code - @item YAP_Int YAP_RunGoalOnce(YAP_Term Goal) -@end table -The @code{YAP_RunGoal()} function makes sure to recover stack space at -the end of execution. - -Prolog terms are pointers: a problem users often find is that the term -@var{Goal} may actually @emph{be moved around} during the execution of -@code{YAP_RunGoal()}, due to garbage collection or stack shifting. If -this is possible, @var{Goal} will become invalid after executing -@code{YAP_RunGoal()}. In this case, it is a good idea to save @var{Goal} -@emph{slots}, as shown next: - -@example - long sl = YAP_InitSlot(scoreTerm); - - out = YAP_RunGoal(t); - t = YAP_GetFromSlot(sl); - YAP_RecoverSlots(1); - if (out == 0) return FALSE; -@end example - -@ifplaintext - -@copydoc real - -@end ifplaintext - -@texinfo - -Slots are safe houses in the stack, the garbage collector and the stack -shifter know about them and make sure they have correct values. In this -case, we use a slot to preserve @var{t} during the execution of -@code{YAP_RunGoal}. When the execution of @var{t} is over we read the -(possibly changed) value of @var{t} back from the slot @var{sl} and tell -YAP that the slot @var{sl} is not needed and can be given back to the -system. The slot functions are as follows: - -@table @code -@item YAP_Int YAP_NewSlots(int @var{NumberOfSlots}) -@findex YAP_NewSlots (C-Interface function) -Allocate @var{NumberOfSlots} from the stack and return an handle to the -last one. The other handle can be obtained by decrementing the handle. - -@item YAP_Int YAP_CurrentSlot(void) -@findex YAP_CurrentSlot (C-Interface function) -Return a handle to the system's default slot. - -@item YAP_Int YAP_InitSlot(YAP_Term @var{t}) -@findex YAP_InitSlot (C-Interface function) -Create a new slot, initialise it with @var{t}, and return a handle to -this slot, that also becomes the current slot. - -@item YAP_Term *YAP_AddressFromSlot(YAP_Int @var{slot}) -@findex YAP_AddressFromSlot (C-Interface function) -Return the address of slot @var{slot}: please use with care. - -@item void YAP_PutInSlot(YAP_Int @var{slot}, YAP_Term @var{t}) -@findex YAP_PutInSlot (C-Interface function) -Set the contents of slot @var{slot} to @var{t}. - -@item int YAP_RecoverSlots(int @var{HowMany}) -@findex YAP_RecoverSlots (C-Interface function) -Recover the space for @var{HowMany} slots: these will include the -current default slot. Fails if no such slots exist. - -@item YAP_Int YAP_ArgsToSlots(int @var{HowMany}) -@findex YAP_ArgsToSlots (C-Interface function) -Store the current first @var{HowMany} arguments in new slots. - -@item void YAP_SlotsToArgs(int @var{HowMany}, YAP_Int @var{slot}) -@findex YAP_SlotsToArgs (C-Interface function) -Set the first @var{HowMany} arguments to the @var{HowMany} slots -starting at @var{slot}. -@end table - -@end texinfo - -The following functions complement @var{YAP_RunGoal}: -@table @code -@item @code{int} YAP_RestartGoal(@code{void}) -@findex YAP_RestartGoal (C-Interface function) -Look for the next solution to the current query by forcing YAP to -backtrack to the latest goal. Notice that slots allocated since the last -@code{YAP_RunGoal} will become invalid. - -@Item @code{int} YAP_Reset(@code{void}) -@findex YAP_Reset (C-Interface function) -Reset execution environment (similar to the @code{abort/0} -built-in). This is useful when you want to start a new query before -asking all solutions to the previous query. - -@item @code{int} YAP_ShutdownGoal(@code{int backtrack}) -@findex YAP_ShutdownGoal (C-Interface function) -Clean up the current goal. If -@code{backtrack} is true, stack space will be recovered and bindings -will be undone. In both cases, any slots allocated since the goal was -created will become invalid. - -@item @code{YAP_Bool} YAP_GoalHasException(@code{YAP_Term *tp}) -@findex YAP_GoalHasException (C-Interface function) -Check if the last goal generated an exception, and if so copy it to the -space pointed to by @var{tp} - -@item @code{void} YAP_ClearExceptions(@code{void}) -@findex YAP_ClearExceptions (C-Interface function) -Reset any exceptions left over by the system. -@end table - -The @var{YAP_RunGoal} interface is designed to be very robust, but may -not be the most efficient when repeated calls to the same goal are made -and when there is no interest in processing exception. The -@var{YAP_EnterGoal} interface should have lower-overhead: -@table @code -@item @code{YAP_PredEntryPtr} YAP_FunctorToPred(@code{YAP_Functor} @var{f}, -@findex YAP_FunctorToPred (C-Interface function) -Return the predicate whose main functor is @var{f}. - -@item @code{YAP_PredEntryPtr} YAP_AtomToPred(@code{YAP_Atom} @var{at} -@findex YAP_AtomToPred (C-Interface function) -Return the arity 0 predicate whose name is @var{at}. - -@item @code{YAP_PredEntryPtr} -YAP_FunctorToPredInModule(@code{YAP_Functor} @var{f}, @code{YAP_Module} @var{m}), -@findex YAP_FunctorToPredInModule (C-Interface function) -Return the predicate in module @var{m} whose main functor is @var{f}. - -@item @code{YAP_PredEntryPtr} YAP_AtomToPred(@code{YAP_Atom} @var{at}, @code{YAP_Module} @var{m}), -@findex YAP_AtomToPredInModule (C-Interface function) -Return the arity 0 predicate in module @var{m} whose name is @var{at}. - -@item @code{YAP_Bool} YAP_EnterGoal(@code{YAP_PredEntryPtr} @var{pe}, -@code{YAP_Term *} @var{array}, @code{YAP_dogoalinfo *} @var{infop}) -@findex YAP_EnterGoal (C-Interface function) -Execute a query for predicate @var{pe}. The query is given as an -array of terms @var{Array}. @var{infop} is the address of a goal -handle that can be used to backtrack and to recover space. Succeeds if -a solution was found. - -Notice that you cannot create new slots if an YAP_EnterGoal goal is open. - -@item @code{YAP_Bool} YAP_RetryGoal(@code{YAP_dogoalinfo *} @var{infop}) - -@findex YAP_RetryGoal (C-Interface function) -Backtrack to a query created by @code{YAP_EnterGoal}. The query is -given by the handle @var{infop}. Returns whether a new solution could -be be found. - -@item @code{YAP_Bool} YAP_LeaveGoal(@code{YAP_Bool} @var{backtrack}, -@code{YAP_dogoalinfo *} @var{infop}) -@findex YAP_LeaveGoal (C-Interface function) -Exit a query query created by @code{YAP_EnterGoal}. If -@code{backtrack} is @code{TRUE}, variable bindings are undone and Heap -space is recovered. Otherwise, only stack space is recovered, ie, -@code{LeaveGoal} executes a cut. -@end table -Next, follows an example of how to use @code{YAP_EnterGoal}: -@example -void -runall(YAP_Term g) -@{ - YAP_dogoalinfo goalInfo; - YAP_Term *goalArgs = YAP_ArraysOfTerm(g); - YAP_Functor *goalFunctor = YAP_FunctorOfTerm(g); - YAP_PredEntryPtr goalPred = YAP_FunctorToPred(goalFunctor); - - result = YAP_EnterGoal( goalPred, goalArgs, &goalInfo ); - while (result) - result = YAP_RetryGoal( &goalInfo ); - YAP_LeaveGoal(TRUE, &goalInfo); -@} -@end example - -@findex YAP_CallProlog (C-Interface function) -YAP allows calling a @strong{new} Prolog interpreter from @code{C}. One -way is to first construct a goal @code{G}, and then it is sufficient to -perform: -@table @code - @item YAP_Bool YAP_CallProlog(YAP_Term @var{G}) -@end table -@noindent -the result will be @code{FALSE}, if the goal failed, or @code{TRUE}, if -the goal succeeded. In this case, the variables in @var{G} will store -the values they have been unified with. Execution only proceeds until -finding the first solution to the goal, but you can call -@code{findall/3} or friends if you need all the solutions. - -Notice that during execution, garbage collection or stack shifting may -have moved the terms - -@node Module Manipulation in C, Miscellaneous C-Functions, Calling YAP From C, C-Interface -@section Module Manipulation in C - -YAP allows one to create a new module from C-code. To create the new -code it is sufficient to call: -@table @code - @item YAP_Module YAP_CreateModule(YAP_Atom @var{ModuleName}) -@end table -@noindent -Notice that the new module does not have any predicates associated and -that it is not the current module. To find the current module, you can call: -@table @code - @item YAP_Module YAP_CurrentModule() -@end table - -Given a module, you may want to obtain the corresponding name. This is -possible by using: -@table @code - @item YAP_Term YAP_ModuleName(YAP_Module mod) -@end table -@noindent -Notice that this function returns a term, and not an atom. You can -@code{YAP_AtomOfTerm} to extract the corresponding Prolog atom. - -@node Miscellaneous C-Functions, Writing C, Module Manipulation in C, C-Interface -@section Miscellaneous C Functions - -@table @code -@item @code{void} YAP_Throw(@code{YAP_Term exception}) -@item @code{void} YAP_AsyncThrow(@code{YAP_Term exception}) -@findex YAP_Throw (C-Interface function) -@findex YAP_AsyncThrow (C-Interface function) - -Throw an exception with term @var{exception}, just like if you called -@code{throw/2}. The function @t{YAP_AsyncThrow} is supposed to be used -from interrupt handlers. -@c See also @code{at_halt/1}. - -@item @code{int} YAP_SetYAPFlag(@code{yap_flag_t flag, int value}) -@findex YAP_SetYAPFlag (C-Interface function) - -This function allows setting some YAP flags from @code{C} .Currently, -only two boolean flags are accepted: @code{YAPC_ENABLE_GC} and -@code{YAPC_ENABLE_AGC}. The first enables/disables the standard garbage -collector, the second does the same for the atom garbage collector.` - -@item @code{YAP_TERM} YAP_AllocExternalDataInStack(@code{size_t bytes}) -@item @code{void *} YAP_ExternalDataInStackFromTerm(@code{YAP_Term t}) -@item @code{YAP_Bool} YAP_IsExternalDataInStackTerm(@code{YAP_Term t}) -@findex YAP_AllocExternalDataInStack (C-Interface function) - -The next routines allow one to store external data in the Prolog -execution stack. The first routine reserves space for @var{sz} bytes -and returns an opaque handle. The second routines receives the handle -and returns a pointer to the data. The last routine checks if a term -is an opaque handle. - -Data will be automatically reclaimed during -backtracking. Also, this storage is opaque to the Prolog garbage compiler, -so it should not be used to store Prolog terms. On the other hand, it -may be useful to store arrays in a compact way, or pointers to external objects. - -@item @code{int} YAP_HaltRegisterHook(@code{YAP_halt_hook f, void *closure}) -@findex YAP_HaltRegisterHook (C-Interface function) - -Register the function @var{f} to be called if YAP is halted. The -function is called with two arguments: the exit code of the process -(@code{0} if this cannot be determined on your operating system) and -the closure argument @var{closure}. -@c See also @code{at_halt/1}. - -@item @code{int} YAP_Argv(@code{char ***argvp}) -@findex YAP_Argv (C-Interface function) -Return the number of arguments to YAP and instantiate argvp to point to the list of such arguments. - -@end table - - -@node Writing C, Loading Objects, Miscellaneous C-Functions, C-Interface -@section Writing predicates in C - -We will distinguish two kinds of predicates: -@table @i -@item @i{deterministic} predicates which either fail or succeed but are not -backtrackable, like the one in the introduction; -@item @i{backtrackable} -predicates which can succeed more than once. -@end table - -The first kind of predicates should be implemented as a C function with -no arguments which should return zero if the predicate fails and a -non-zero value otherwise. The predicate should be declared to -YAP, in the initialization routine, with a call to -@table @code - @item void YAP_UserCPredicate(char *@var{name}, YAP_Bool *@var{fn}(), unsigned long int @var{arity}); -@findex YAP_UserCPredicate (C-Interface function) -@noindent -where @var{name} is a string with the name of the predicate, @var{init}, -@var{cont}, @var{cut} are the C functions used to start, continue and -when pruning the execution of the predicate, @var{arity} is the -predicate arity, and @var{sizeof} is the size of the data to be -preserved in the stack. - -For the second kind of predicates we need three C functions. The first one - is called when the predicate is first activated; the second one -is called on backtracking to provide (possibly) other solutions; the - last one is called on pruning. Note -also that we normally also need to preserve some information to find out -the next solution. - -In fact the role of the two functions can be better understood from the -following Prolog definition -@example - p :- start. - p :- repeat, - continue. -@end example -@noindent -where @code{start} and @code{continue} correspond to the two C functions -described above. - -The interface works as follows: - -@table @code - @item void YAP_UserBackCutCPredicate(char *@var{name}, int *@var{init}(), int *@var{cont}(), int *@var{cut}(), unsigned long int @var{arity}, unsigned int @var{sizeof}) -@findex YAP_UserBackCutCPredicate (C-Interface function) -@noindent -describes a new predicate where @var{name} is the name of the predicate, -@var{init}, @var{cont}, and @var{cut} are the C functions that implement -the predicate and @var{arity} is the predicate's arity. - -@item void YAP_UserBackCPredicate(char *@var{name}, int *@var{init}(), int *@var{cont}(), unsigned long int @var{arity}, unsigned int @var{sizeof}) -@findex YAP_UserBackCPredicate (C-Interface function) -@noindent -describes a new predicate where @var{name} is the name of the predicate, -@var{init}, and @var{cont} are the C functions that implement the -predicate and @var{arity} is the predicate's arity. - -@item void YAP_PRESERVE_DATA(@var{ptr}, @var{type}); -@findex YAP_PRESERVE_DATA (C-Interface function) - -@item void YAP_PRESERVED_DATA(@var{ptr}, @var{type}); -@findex YAP_PRESERVED_DATA (C-Interface function) - -@item void YAP_PRESERVED_DATA_CUT(@var{ptr}, @var{type}); -@findex YAP_PRESERVED_DATA_CUT (C-Interface function) - -@item void YAP_cut_succeed( void ); -@findex YAP_cut_succeed (C-Interface function) - -@item void YAP_cut_fail( void ); -@findex YAP_cut_fail (C-Interface function) - -@end table - - - -As an example we will consider implementing in C a predicate @code{n100(N)} -which, when called with an instantiated argument should succeed if that -argument is a numeral less or equal to 100, and, when called with an -uninstantiated argument, should provide, by backtracking, all the positive -integers less or equal to 100. - - To do that we first declare a structure, which can only consist -of Prolog terms, containing the information to be preserved on backtracking -and a pointer variable to a structure of that type. - -@example -#include "YAPInterface.h" - -static int start_n100(void); -static int continue_n100(void); - -typedef struct @{ - YAP_Term next_solution; - @} n100_data_type; - -n100_data_type *n100_data; -@end example - -We now write the @code{C} function to handle the first call: - -@example -static int start_n100(void) -@{ - YAP_Term t = YAP_ARG1; - YAP_PRESERVE_DATA(n100_data,n100_data_type); - if(YAP_IsVarTerm(t)) @{ - n100_data->next_solution = YAP_MkIntTerm(0); - return continue_n100(); - @} - if(!YAP_IsIntTerm(t) || YAP_IntOfTerm(t)<0 || YAP_IntOfTerm(t)>100) @{ - YAP_cut_fail(); - @} else @{ - YAP_cut_succeed(); - @} -@} - -@end example - -The routine starts by getting the dereference value of the argument. -The call to @code{YAP_PRESERVE_DATA} is used to initialize the memory -which will hold the information to be preserved across -backtracking. The first argument is the variable we shall use, and the -second its type. Note that we can only use @code{YAP_PRESERVE_DATA} -once, so often we will want the variable to be a structure. This data -is visible to the garbage collector, so it should consist of Prolog -terms, as in the example. It is also correct to store pointers to -objects external to YAP stacks, as the garbage collector will ignore -such references. - -If the argument of the predicate is a variable, the routine initializes the -structure to be preserved across backtracking with the information -required to provide the next solution, and exits by calling -@code{continue_n100} to provide that solution. - -If the argument was not a variable, the routine then checks if it was an -integer, and if so, if its value is positive and less than 100. In that -case it exits, denoting success, with @code{YAP_cut_succeed}, or -otherwise exits with @code{YAP_cut_fail} denoting failure. - -The reason for using for using the functions @code{YAP_cut_succeed} and -@code{YAP_cut_fail} instead of just returning a non-zero value in the -first case, and zero in the second case, is that otherwise, if -backtracking occurred later, the routine @code{continue_n100} would be -called to provide additional solutions. - -The code required for the second function is -@example -static int continue_n100(void) -@{ - int n; - YAP_Term t; - YAP_Term sol = YAP_ARG1; - YAP_PRESERVED_DATA(n100_data,n100_data_type); - n = YAP_IntOfTerm(n100_data->next_solution); - if( n == 100) @{ - t = YAP_MkIntTerm(n); - YAP_Unify(sol,t); - YAP_cut_succeed(); - @} - else @{ - YAP_Unify(sol,n100_data->next_solution); - n100_data->next_solution = YAP_MkIntTerm(n+1); - return(TRUE); - @} -@} -@end example - -Note that again the macro @code{YAP_PRESERVED_DATA} is used at the -beginning of the function to access the data preserved from the previous -solution. Then it checks if the last solution was found and in that -case exits with @code{YAP_cut_succeed} in order to cut any further -backtracking. If this is not the last solution then we save the value -for the next solution in the data structure and exit normally with 1 -denoting success. Note also that in any of the two cases we use the -function @code{YAP_unify} to bind the argument of the call to the value -saved in @code{ n100_state->next_solution}. - - -Note also that the only correct way to signal failure in a backtrackable -predicate is to use the @code{YAP_cut_fail} macro. - -Backtrackable predicates should be declared to YAP, in a way -similar to what happened with deterministic ones, but using instead a -call to -@example - -@end example -@noindent - In this example, we would have something like - -@example -void -init_n100(void) -@{ - YAP_UserBackCutCPredicate("n100", start_n100, continue_n100, cut_n100, 1, 1); -@} -@end example -The argument before last is the predicate's arity. Notice again the -last argument to the call. function argument gives the extra space we -want to use for @code{PRESERVED_DATA}. Space is given in cells, where -a cell is the same size as a pointer. The garbage collector has access -to this space, hence users should use it either to store terms or to -store pointers to objects outside the stacks. - -The code for @code{cut_n100} could be: -@example -static int cut_n100(void) -@{ - YAP_PRESERVED_DATA_CUT(n100_data,n100_data_type*); - - fprintf("n100 cut with counter %ld\n", YAP_IntOfTerm(n100_data->next_solution)); - return TRUE; -@} -@end example -Notice that we have to use @code{YAP_PRESERVED_DATA_CUT}: this is -because the Prolog engine is at a different state during cut. - -If no work is required at cut, we can use: -@example -void -init_n100(void) -@{ - YAP_UserBackCutCPredicate("n100", start_n100, continue_n100, NULL, 1, 1); -@} -@end example -in this case no code is executed at cut time. - -@node Loading Objects, Save&Rest, Writing C, C-Interface -@section Loading Object Files - -The primitive predicate -@table @code -@item load_foreign_files(@var{Files},@var{Libs},@var{InitRoutine}) -@end table -@noindent -should be used, from inside YAP, to load object files produced by the C -compiler. The argument @var{ObjectFiles} should be a list of atoms -specifying the object files to load, @var{Libs} is a list (possibly -empty) of libraries to be passed to the unix loader (@code{ld}) and -InitRoutine is the name of the C routine (to be called after the files -are loaded) to perform the necessary declarations to YAP of the -predicates defined in the files. - -YAP will search for @var{ObjectFiles} in the current directory first. If -it cannot find them it will search for the files using the environment -variable: -@table @code -@item YAPLIBDIR -@findex YAPLIBDIR -@noindent -@end table -if defined, or in the default library. - -YAP also supports the SWI-Prolog interface to loading foreign code: - -@table @code -@item open_shared_object(+@var{File}, -@var{Handle}) -@findex open_shared_object/2 -@snindex open_shared_object/2 -@cnindex open_shared_object/2 - File is the name of a shared object file (called dynamic load - library in MS-Windows). This file is attached to the current process - and @var{Handle} is unified with a handle to the library. Equivalent to - @code{open_shared_object(File, [], Handle)}. See also - @code{load_foreign_library/1} and @code{load_foreign_library/2}. - - On errors, an exception @code{shared_object}(@var{Action}, - @var{Message}) is raised. @var{Message} is the return value from - dlerror(). - -@item open_shared_object(+@var{File}, -@var{Handle}, +@var{Options}) -@findex open_shared_object/3 -@snindex open_shared_object/3 -@cnindex open_shared_object/3 - As @code{open_shared_object/2}, but allows for additional flags to - be passed. @var{Options} is a list of atoms. @code{now} implies the - symbols are - resolved immediately rather than lazily (default). @code{global} implies - symbols of the loaded object are visible while loading other shared - objects (by default they are local). Note that these flags may not - be supported by your operating system. Check the documentation of - @code{dlopen()} or equivalent on your operating system. Unsupported - flags are silently ignored. - -@item close_shared_object(+@var{Handle}) -@findex close_shared_object/1 -@snindex close_shared_object/1 -@cnindex close_shared_object/1 - Detach the shared object identified by @var{Handle}. - -@item call_shared_object_function(+@var{Handle}, +@var{Function}) -@findex call_shared_object_function/2 -@snindex call_shared_object_function/2 -@cnindex call_shared_object_function/2 - Call the named function in the loaded shared library. The function - is called without arguments and the return-value is - ignored. In SWI-Prolog, normally this function installs foreign - language predicates using calls to @code{PL_register_foreign()}. -@end table - -@node Save&Rest, YAP4 Notes, Loading Objects, C-Interface -@section Saving and Restoring - -@comment The primitive predicates @code{save} and @code{restore} will save and restore -@comment object code loaded with @code{load_foreign_files/3}. However, the values of -@comment any non-static data created by the C files loaded will not be saved nor -@comment restored. - -YAP4 currently does not support @code{save} and @code{restore} for object code -loaded with @code{load_foreign_files/3}. We plan to support save and restore -in future releases of YAP. - -@node YAP4 Notes, , Save&Rest, C-Interface -@section Changes to the C-Interface in YAP4 - -YAP4 includes several changes over the previous @code{load_foreign_files/3} -interface. These changes were required to support the new binary code -formats, such as ELF used in Solaris2 and Linux. -@itemize @bullet -@item All Names of YAP objects now start with @var{YAP_}. This is -designed to avoid clashes with other code. Use @code{YAPInterface.h} to -take advantage of the new interface. @code{c_interface.h} is still -available if you cannot port the code to the new interface. - -@item Access to elements in the new interface always goes through -@emph{functions}. This includes access to the argument registers, -@code{YAP_ARG1} to @code{YAP_ARG16}. This change breaks code such as -@code{unify(&ARG1,&t)}, which is nowadays: -@example -@{ - YAP_Unify(ARG1, t); -@} -@end example - -@item @code{cut_fail()} and @code{cut_succeed()} are now functions. - -@item The use of @code{Deref} is deprecated. All functions that return -Prolog terms, including the ones that access arguments, already -dereference their arguments. - -@item Space allocated with PRESERVE_DATA is ignored by garbage -collection and stack shifting. As a result, any pointers to a Prolog -stack object, including some terms, may be corrupted after garbage -collection or stack shifting. Prolog terms should instead be stored as -arguments to the backtrackable procedure. - -@end itemize - -@node YAPLibrary, Compatibility, C-Interface, Top -@section Using YAP as a Library - -YAP can be used as a library to be called from other -programs. To do so, you must first create the YAP library: -@example -make library -make install_library -@end example -This will install a file @code{libyap.a} in @var{LIBDIR} and the Prolog -headers in @var{INCLUDEDIR}. The library contains all the functionality -available in YAP, except the foreign function loader and for -@code{YAP}'s startup routines. - -To actually use this library you must follow a five step process: - -@enumerate -@item - You must initialize the YAP environment. A single function, -@code{YAP_FastInit} asks for a contiguous chunk in your memory space, fills -it in with the data-base, and sets up YAP's stacks and -execution registers. You can use a saved space from a standard system by -calling @code{save_program/1}. - -@item You then have to prepare a query to give to -YAP. A query is a Prolog term, and you just have to use the same -functions that are available in the C-interface. - -@item You can then use @code{YAP_RunGoal(query)} to actually evaluate your -query. The argument is the query term @code{query}, and the result is 1 -if the query succeeded, and 0 if it failed. - -@item You can use the term destructor functions to check how -arguments were instantiated. - -@item If you want extra solutions, you can use -@code{YAP_RestartGoal()} to obtain the next solution. - -@end enumerate - -The next program shows how to use this system. We assume the saved -program contains two facts for the procedure @t{b}: - -@example -@cartouche -#include -#include "YAP/YAPInterface.h" - - -int -main(int argc, char *argv[]) @{ - if (YAP_FastInit("saved_state") == YAP_BOOT_ERROR) - exit(1); - if (YAP_RunGoal(YAP_MkAtomTerm(YAP_LookupAtom("do")))) @{ - printf("Success\n"); - while (YAP_RestartGoal()) - printf("Success\n"); - @} - printf("NO\n"); -@} -@end cartouche -@end example - -The program first initializes YAP, calls the query for the -first time and succeeds, and then backtracks twice. The first time -backtracking succeeds, the second it fails and exits. - -To compile this program it should be sufficient to do: - -@example -cc -o exem -I../YAP4.3.0 test.c -lYAP -lreadline -lm -@end example - -You may need to adjust the libraries and library paths depending on the -Operating System and your installation of YAP. - -Note that YAP4.3.0 provides the first version of the interface. The -interface may change and improve in the future. - -The following C-functions are available from YAP: - -@itemize @bullet -@item YAP_CompileClause(@code{YAP_Term} @var{Clause}) -@findex YAP_CompileClause/1 -Compile the Prolog term @var{Clause} and assert it as the last clause -for the corresponding procedure. - -@item @code{int} YAP_ContinueGoal(@code{void}) -@findex YAP_ContinueGoal/0 -Continue execution from the point where it stopped. - -@item @code{void} YAP_Error(@code{int} @var{ID},@code{YAP_Term} @var{Cause},@code{char *} @var{error_description}) -@findex YAP_Error/1 -Generate an YAP System Error with description given by the string -@var{error_description}. @var{ID} is the error ID, if known, or -@code{0}. @var{Cause} is the term that caused the crash. - -@item @code{void} YAP_Exit(@code{int} @var{exit_code}) -@findex YAP_Exit/1 -Exit YAP immediately. The argument @var{exit_code} gives the error code -and is supposed to be 0 after successful execution in Unix and Unix-like -systems. - -@item @code{YAP_Term} YAP_GetValue(@code{Atom} @var{at}) -@findex YAP_GetValue/1 -Return the term @var{value} associated with the atom @var{at}. If no -such term exists the function will return the empty list. - -@item YAP_FastInit(@code{char *} @var{SavedState}) -@findex YAP_FastInit/1 -Initialize a copy of YAP from @var{SavedState}. The copy is -monolithic and currently must be loaded at the same address where it was -saved. @code{YAP_FastInit} is a simpler version of @code{YAP_Init}. - -@item YAP_Init(@var{InitInfo}) -@findex YAP_Init/1 -Initialize YAP. The arguments are in a @code{C} -structure of type @code{YAP_init_args}. - -The fields of @var{InitInfo} are @code{char *} @var{SavedState}, -@code{int} @var{HeapSize}, @code{int} @var{StackSize}, @code{int} -@var{TrailSize}, @code{int} @var{NumberofWorkers}, @code{int} -@var{SchedulerLoop}, @code{int} @var{DelayedReleaseLoad}, @code{int} -@var{argc}, @code{char **} @var{argv}, @code{int} @var{ErrorNo}, and -@code{char *} @var{ErrorCause}. The function returns an integer, which -indicates the current status. If the result is @code{YAP_BOOT_ERROR} -booting failed. - -If @var{SavedState} is not NULL, try to open and restore the file -@var{SavedState}. Initially YAP will search in the current directory. If -the saved state does not exist in the current directory YAP will use -either the default library directory or the directory given by the -environment variable @code{YAPLIBDIR}. Note that currently -the saved state must be loaded at the same address where it was saved. - -If @var{HeapSize} is different from 0 use @var{HeapSize} as the minimum -size of the Heap (or code space). If @var{StackSize} is different from 0 -use @var{HeapSize} as the minimum size for the Stacks. If -@var{TrailSize} is different from 0 use @var{TrailSize} as the minimum -size for the Trails. - -The @var{NumberofWorkers}, @var{NumberofWorkers}, and -@var{DelayedReleaseLoad} are only of interest to the or-parallel system. - -The argument count @var{argc} and string of arguments @var{argv} -arguments are to be passed to user programs as the arguments used to -call YAP. - -If booting failed you may consult @code{ErrorNo} and @code{ErrorCause} -for the cause of the error, or call -@code{YAP_Error(ErrorNo,0L,ErrorCause)} to do default processing. - - -@item @code{void} YAP_PutValue(@code{Atom} @var{at}, @code{YAP_Term} @var{value}) -@findex YAP_PutValue/2 -Associate the term @var{value} with the atom @var{at}. The term -@var{value} must be a constant. This functionality is used by YAP as a -simple way for controlling and communicating with the Prolog run-time. - -@item @code{YAP_Term} YAP_Read(@code{IOSTREAM *Stream}) -@findex YAP_Read -Parse a @var{Term} from the stream @var{Stream}. - -@item @code{YAP_Term} YAP_Write(@code{YAP_Term} @var{t}) -@findex YAP_CopyTerm -Copy a Term @var{t} and all associated constraints. May call the garbage -collector and returns @code{0L} on error (such as no space being -available). - -@item @code{void} YAP_Write(@code{YAP_Term} @var{t}, @code{IOSTREAM} @var{stream}, @code{int} @var{flags}) -@findex YAP_Write/3 -Write a Term @var{t} using the stream @var{stream} to output -characters. The term is written according to a mask of the following -flags in the @code{flag} argument: @code{YAP_WRITE_QUOTED}, -@code{YAP_WRITE_HANDLE_VARS}, @code{YAP_WRITE_USE_PORTRAY}, and @code{YAP_WRITE_IGNORE_OPS}. - -@item @code{int} YAP_WriteBuffer(@code{YAP_Term} @var{t}, @code{char *} @var{buff}, @code{size_t} @var{size}, @code{int} @var{flags}) -@findex YAP_WriteBuffer -Write a YAP_Term @var{t} to buffer @var{buff} with size -@var{size}. The term is written -according to a mask of the following flags in the @code{flag} -argument: @code{YAP_WRITE_QUOTED}, @code{YAP_WRITE_HANDLE_VARS}, -@code{YAP_WRITE_USE_PORTRAY}, and @code{YAP_WRITE_IGNORE_OPS}. The -function will fail if it does not have enough space in the buffer. - -@item @code{char *} YAP_WriteDynamicBuffer(@code{YAP_Term} @var{t}, @code{char *} @var{buff}, @code{size_t} @var{size}, @code{size_t} @var{*lengthp}, @code{size_t} @var{*encodingp}, @code{int} @var{flags}) -@findex YAP_WriteDynamicBuffer/6 -Write a YAP_Term @var{t} to buffer @var{buff} with size -@var{size}. The code will allocate an extra buffer if @var{buff} is -@code{NULL} or if @code{buffer} does not have enough room. The -variable @code{lengthp} is assigned the size of the resulting buffer, -and @code{encodingp} will receive the type of encoding (currently only @code{PL_ENC_ISO_LATIN_1} and @code{PL_ENC_WCHAR} are supported) - -@item @code{void} YAP_InitConsult(@code{int} @var{mode}, @code{char *} @var{filename}) -@findex YAP_InitConsult/2 -Enter consult mode on file @var{filename}. This mode maintains a few -data-structures internally, for instance to know whether a predicate -before or not. It is still possible to execute goals in consult mode. - -If @var{mode} is @code{TRUE} the file will be reconsulted, otherwise -just consulted. In practice, this function is most useful for -bootstrapping Prolog, as otherwise one may call the Prolog predicate -@code{compile/1} or @code{consult/1} to do compilation. - -Note that it is up to the user to open the file @var{filename}. The -@code{YAP_InitConsult} function only uses the file name for internal -bookkeeping. - -@item @code{void} YAP_EndConsult(@code{void}) -@findex YAP_EndConsult/0 -Finish consult mode. - -@end itemize - -Some observations: - -@itemize @bullet -@item The system will core dump if you try to load the saved state in a -different address from where it was made. This may be a problem if -your program uses @code{mmap}. This problem will be addressed in future -versions of YAP. - -@item Currently, the YAP library will pollute the name -space for your program. - -@item The initial library includes the complete YAP system. In -the future we plan to split this library into several smaller libraries -(e.g. if you do not want to perform Input/Output). - -@item You can generate your own saved states. Look at the -@code{boot.yap} and @code{init.yap} files. - -@end itemize - -@node Compatibility, Operators, YAPLibrary, Top -@chapter Compatibility with Other Prolog systems - -YAP has been designed to be as compatible as possible with -other Prolog systems, and initially with C-Prolog. More recent work on -YAP has included features initially proposed for the Quintus -and SICStus Prolog systems. - -Developments since @code{YAP4.1.6} we have striven at making -YAP compatible with the ISO-Prolog standard. - -@menu -* C-Prolog:: Compatibility with the C-Prolog interpreter -* SICStus Prolog:: Compatibility with the SICStus Prolog system -* ISO Prolog:: Compatibility with the ISO Prolog standard -@end menu - -@node C-Prolog, SICStus Prolog, , Compatibility -@section Compatibility with the C-Prolog interpreter - -@menu -C-Prolog Compatibility -* Major Differences with C-Prolog:: Major Differences between YAP and C-Prolog -* Fully C-Prolog Compatible:: YAP predicates fully compatible with -C-Prolog -* Not Strictly C-Prolog Compatible:: YAP predicates not strictly as C-Prolog -* Not in C-Prolog:: YAP predicates not available in C-Prolog -* Not in YAP:: C-Prolog predicates not available in YAP -@end menu - -@node Major Differences with C-Prolog, Fully C-Prolog Compatible, , C-Prolog -@subsection Major Differences between YAP and C-Prolog. - -YAP includes several extensions over the original C-Prolog system. Even -so, most C-Prolog programs should run under YAP without changes. - -The most important difference between YAP and C-Prolog is that, being -YAP a compiler, some changes should be made if predicates such as -@code{assert}, @code{clause} and @code{retract} are used. First -predicates which will change during execution should be declared as -@code{dynamic} by using commands like: - -@example -:- dynamic f/n. -@end example - -@noindent where @code{f} is the predicate name and n is the arity of the -predicate. Note that several such predicates can be declared in a -single command: -@example - :- dynamic f/2, ..., g/1. -@end example - -Primitive predicates such as @code{retract} apply only to dynamic -predicates. Finally note that not all the C-Prolog primitive predicates -are implemented in YAP. They can easily be detected using the -@code{unknown} system predicate provided by YAP. - -Last, by default YAP enables character escapes in strings. You can -disable the special interpretation for the escape character by using: -@example -:- yap_flag(character_escapes,off). -@end example -@noindent -or by using: -@example -:- yap_flag(language,cprolog). -@end example - -@node Fully C-Prolog Compatible, Not Strictly C-Prolog Compatible, Major Differences with C-Prolog, C-Prolog -@subsection YAP predicates fully compatible with C-Prolog - -These are the Prolog built-ins that are fully compatible in both -C-Prolog and YAP: - -@printindex cy - -@node Not Strictly C-Prolog Compatible, Not in C-Prolog, Fully C-Prolog Compatible, C-Prolog -@subsection YAP predicates not strictly compatible with C-Prolog - -These are YAP built-ins that are also available in C-Prolog, but -that are not fully compatible: - -@printindex ca - -@node Not in C-Prolog, Not in YAP, Not Strictly C-Prolog Compatible, C-Prolog -@subsection YAP predicates not available in C-Prolog - -These are YAP built-ins not available in C-Prolog. - -@printindex cn - -@node Not in YAP, , Not in C-Prolog, C-Prolog -@subsection YAP predicates not available in C-Prolog - -These are C-Prolog built-ins not available in YAP: - -@table @code -@item 'LC' -The following Prolog text uses lower case letters. - -@item 'NOLC' -The following Prolog text uses upper case letters only. -@end table - -@node SICStus Prolog, ISO Prolog, C-Prolog, Compatibility -@section Compatibility with the Quintus and SICStus Prolog systems - -The Quintus Prolog system was the first Prolog compiler to use Warren's -Abstract Machine. This system was very influential in the Prolog -community. Quintus Prolog implemented compilation into an abstract -machine code, which was then emulated. Quintus Prolog also included -several new built-ins, an extensive library, and in later releases a -garbage collector. The SICStus Prolog system, developed at SICS (Swedish -Institute of Computer Science), is an emulator based Prolog system -largely compatible with Quintus Prolog. SICStus Prolog has evolved -through several versions. The current version includes several -extensions, such as an object implementation, co-routining, and -constraints. - -Recent work in YAP has been influenced by work in Quintus and -SICStus Prolog. Wherever possible, we have tried to make YAP -compatible with recent versions of these systems, and specifically of -SICStus Prolog. You should use -@example -:- yap_flag(language, sicstus). -@end example -@noindent -for maximum compatibility with SICStus Prolog. - -@menu -SICStus Compatibility -* Major Differences with SICStus:: Major Differences between YAP and SICStus Prolog -* Fully SICStus Compatible:: YAP predicates fully compatible with -SICStus Prolog -* Not Strictly SICStus Compatible:: YAP predicates not strictly as -SICStus Prolog -* Not in SICStus Prolog:: YAP predicates not available in SICStus Prolog -@end menu - -@node Major Differences with SICStus, Fully SICStus Compatible, , SICStus Prolog -@subsection Major Differences between YAP and SICStus Prolog. - -Both YAP and SICStus Prolog obey the Edinburgh Syntax and are based on -the WAM. Even so, there are quite a few important differences: - -@itemize @bullet -@item Differently from SICStus Prolog, YAP does not have a -notion of interpreted code. All code in YAP is compiled. - -@item YAP does not support an intermediate byte-code -representation, so the @code{fcompile/1} and @code{load/1} built-ins are -not available in YAP. - -@item YAP implements escape sequences as in the ISO standard. SICStus -Prolog implements Unix-like escape sequences. - -@item YAP implements @code{initialization/1} as per the ISO -standard. Use @code{prolog_initialization/1} for the SICStus Prolog -compatible built-in. - -@item Prolog flags are different in SICStus Prolog and in YAP. - -@item The SICStus Prolog @code{on_exception/3} and -@code{raise_exception} built-ins correspond to the ISO built-ins -@code{catch/3} and @code{throw/1}. - -@item The following SICStus Prolog v3 built-ins are not (currently) -implemented in YAP (note that this is only a partial list): -@code{file_search_path/2}, -@code{stream_interrupt/3}, @code{reinitialize/0}, @code{help/0}, -@code{help/1}, @code{trimcore/0}, @code{load_files/1}, -@code{load_files/2}, and @code{require/1}. - - The previous list is incomplete. We also cannot guarantee full -compatibility for other built-ins (although we will try to address any -such incompatibilities). Last, SICStus Prolog is an evolving system, so -one can be expect new incompatibilities to be introduced in future -releases of SICStus Prolog. - -@item YAP allows asserting and abolishing static code during -execution through the @code{assert_static/1} and @code{abolish/1} -built-ins. This is not allowed in Quintus Prolog or SICStus Prolog. - -@item The socket predicates, although designed to be compatible with -SICStus Prolog, are built-ins, not library predicates, in YAP. - -@item This list is incomplete. - -@end itemize - -The following differences only exist if the @code{language} flag is set -to @code{yap} (the default): - -@itemize @bullet -@item The @code{consult/1} predicate in YAP follows C-Prolog -semantics. That is, it adds clauses to the data base, even for -preexisting procedures. This is different from @code{consult/1} in -SICStus Prolog or SWI-Prolog. - -@cindex logical update semantics -@item -By default, the data-base in YAP follows "logical update semantics", as -Quintus Prolog or SICStus Prolog do. Previous versions followed -"immediate update semantics". The difference is depicted in the next -example: - -@example -:- dynamic a/1. - -?- assert(a(1)). - -?- retract(a(X)), X1 is X +1, assertz(a(X)). -@end example -With immediate semantics, new clauses or entries to the data base are -visible in backtracking. In this example, the first call to -@code{retract/1} will succeed. The call to @strong{assertz/1} will then -succeed. On backtracking, the system will retry -@code{retract/1}. Because the newly asserted goal is visible to -@code{retract/1}, it can be retracted from the data base, and -@code{retract(a(X))} will succeed again. The process will continue -generating integers for ever. Immediate semantics were used in C-Prolog. - -With logical update semantics, any additions or deletions of clauses -for a goal -@emph{will not affect previous activations of the goal}. In the example, -the call to @code{assertz/1} will not see the -update performed by the @code{assertz/1}, and the query will have a -single solution. - -Calling @code{yap_flag(update_semantics,logical)} will switch -YAP to use logical update semantics. - -@item @code{dynamic/1} is a built-in, not a directive, in YAP. - -@item By default, YAP fails on undefined predicates. To follow default -SICStus Prolog use: -@example -:- yap_flag(unknown,error). -@end example - -@item By default, directives in YAP can be called from the top level. - -@end itemize - -@node Fully SICStus Compatible, Not Strictly SICStus Compatible, Major Differences with SICStus, SICStus Prolog -@subsection YAP predicates fully compatible with SICStus Prolog - -These are the Prolog built-ins that are fully compatible in both SICStus -Prolog and YAP: - -@printindex sy - -@node Not Strictly SICStus Compatible, Not in SICStus Prolog, Fully SICStus Compatible, SICStus Prolog -@subsection YAP predicates not strictly compatible with SICStus Prolog - -These are YAP built-ins that are also available in SICStus Prolog, but -that are not fully compatible: - -@printindex sa - -@node Not in SICStus Prolog, , Not Strictly SICStus Compatible, SICStus Prolog -@subsection YAP predicates not available in SICStus Prolog - -These are YAP built-ins not available in SICStus Prolog. - -@printindex sn - - -@node ISO Prolog, , SICStus Prolog, Compatibility -@section Compatibility with the ISO Prolog standard - -The Prolog standard was developed by ISO/IEC JTC1/SC22/WG17, the -international standardization working group for the programming language -Prolog. The book "Prolog: The Standard" by Deransart, Ed-Dbali and -Cervoni gives a complete description of this standard. Development in -YAP from YAP4.1.6 onwards have striven at making YAP -compatible with ISO Prolog. As such: - -@itemize @bullet -@item YAP now supports all of the built-ins required by the -ISO-standard, and, -@item Error-handling is as required by the standard. -@end itemize - -YAP by default is not fully ISO standard compliant. You can set the -@code{language} flag to @code{iso} to obtain very good -compatibility. Setting this flag changes the following: - -@itemize @bullet -@item By default, YAP uses "immediate update semantics" for its -database, and not "logical update semantics", as per the standard, -(@pxref{SICStus Prolog}). This affects @code{assert/1}, -@code{retract/1}, and friends. - -Calling @code{set_prolog_flag(update_semantics,logical)} will switch -YAP to use logical update semantics. - -@item By default, YAP implements the -@code{atom_chars/2}(@pxref{Testing Terms}), and -@code{number_chars/2}, (@pxref{Testing Terms}), -built-ins as per the original Quintus Prolog definition, and -not as per the ISO definition. - -Calling @code{set_prolog_flag(to_chars_mode,iso)} will switch -YAP to use the ISO definition for -@code{atom_chars/2} and @code{number_chars/2}. - -@item By default, YAP allows executable goals in directives. In ISO mode -most directives can only be called from top level (the exceptions are -@code{set_prolog_flag/2} and @code{op/3}). - -@item Error checking for meta-calls under ISO Prolog mode is stricter -than by default. - -@item The @code{strict_iso} flag automatically enables the ISO Prolog -standard. This feature should disable all features not present in the -standard. - -@end itemize - -The following incompatibilities between YAP and the ISO standard are -known to still exist: - -@itemize @bullet - -@item Currently, YAP does not handle overflow errors in integer -operations, and handles floating-point errors only in some -architectures. Otherwise, YAP follows IEEE arithmetic. - -@end itemize - -Please inform the authors on other incompatibilities that may still -exist. - -@node Operators, Predicate Index, Compatibility, Top -@section Summary of YAP Predefined Operators - - - The Prolog syntax caters for operators of three main kinds: - -@itemize @bullet -@item -prefix; -@item -infix; -@item -postfix. -@end itemize - - Each operator has precedence in the range 1 to 1200, and this -precedence is used to disambiguate expressions where the structure of the -term denoted is not made explicit using brackets. The operator of higher -precedence is the main functor. - - If there are two operators with the highest precedence, the ambiguity -is solved analyzing the types of the operators. The possible infix types are: -@var{xfx}, @var{xfy}, and @var{yfx}. - - With an operator of type @var{xfx} both sub-expressions must have lower -precedence than the operator itself, unless they are bracketed (which -assigns to them zero precedence). With an operator type @var{xfy} only the -left-hand sub-expression must have lower precedence. The opposite happens -for @var{yfx} type. - - A prefix operator can be of type @var{fx} or @var{fy}. -A postfix operator can be of type @var{xf} or @var{yf}. -The meaning of the notation is analogous to the above. -@example -a + b * c -@end example -@noindent -means -@example -a + (b * c) -@end example -@noindent -as + and * have the following types and precedences: -@example -:-op(500,yfx,'+'). -:-op(400,yfx,'*'). -@end example - -Now defining -@example -:-op(700,xfy,'++'). -:-op(700,xfx,'=:='). -a ++ b =:= c -@end example -@noindent means -@example -a ++ (b =:= c) -@end example - - -The following is the list of the declarations of the predefined operators: - -@example -:-op(1200,fx,['?-', ':-']). -:-op(1200,xfx,[':-','-->']). -:-op(1150,fx,[block,dynamic,mode,public,multifile,meta_predicate, - sequential,table,initialization]). -:-op(1100,xfy,[';','|']). -:-op(1050,xfy,->). -:-op(1000,xfy,','). -:-op(999,xfy,'.'). -:-op(900,fy,['\+', not]). -:-op(900,fx,[nospy, spy]). -:-op(700,xfx,[@@>=,@@=<,@@<,@@>,<,=,>,=:=,=\=,\==,>=,=<,==,\=,=..,is]). -:-op(500,yfx,['\/','/\','+','-']). -:-op(500,fx,['+','-']). -:-op(400,yfx,['<<','>>','//','*','/']). -:-op(300,xfx,mod). -:-op(200,xfy,['^','**']). -:-op(50,xfx,same). -@end example - -@node Predicate Index, Concept Index, Operators, Top -@unnumbered Predicate Index -@printindex fn - -@node Concept Index, , Predicate Index, Top -@unnumbered Concept Index -@printindex cp - -@contents - -@bye diff --git a/docs/yapdocs.md b/docs/yapdocs.md deleted file mode 100644 index 9e652881c..000000000 --- a/docs/yapdocs.md +++ /dev/null @@ -1,15665 +0,0 @@ -/** - -@defgroup YAPControl Control Predicates -@ingroup YAPBuiltins -@{ - - -*/ - - -/** @pred true is iso - - -Succeeds once. - - -*/ - -/** @pred fail is iso - - -Always fails. - - -*/ - -/** @pred false is iso - - -The same as fail. - - -*/ - -/** @pred repeat is iso -bprolqSucceeds repeatedly. - -In the next example, `repeat` is used as an efficient way to implement -a loop. The next example reads all terms in a file: -~~~~~~~~~~~~~ - a :- repeat, read(X), write(X), nl, X=end_of_file, !. -~~~~~~~~~~~~~ -the loop is effectively terminated by the cut-goal, when the test-goal -`X=end` succeeds. While the test fails, the goals `read(X)`, -`write(X)`, and `nl` are executed repeatedly, because -backtracking is caught by the `repeat` goal. - -The built-in `repeat/0` could be defined in Prolog by: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - repeat. - repeat :- repeat. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The predicate between/3 can be used to iterate for a pre-defined -number of steps. - -*/ - -/** @pred call(+ _P_) is iso -Meta-call predicate. - -If _P_ is instantiated to an atom or a compound term, the goal `call( -_P_)` is executed as if the clause was originally written as _P_ -instead as call( _P_ ), except that any "cut" occurring in _P_ only -cuts alternatives in the execution of _P_. - - -*/ - -/** @pred incore(+ _P_) - - -The same as call/1. - - -*/ - -/** @pred call(+ _Closure_,...,? _Ai_,...) is iso - - -Meta-call where _Closure_ is a closure that is converted into a goal by -appending the _Ai_ additional arguments. The number of arguments varies -between 0 and 10. - - -*/ - -/** @pred call_with_args(+ _Name_,...,? _Ai_,...) - - -Meta-call where _Name_ is the name of the procedure to be called and -the _Ai_ are the arguments. The number of arguments varies between 0 -and 10. New code should use `call/N` for better portability. - -If _Name_ is a complex term, then call_with_args/n behaves as -call/n: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred + _P_ - -The same as `call( _P_)`. This feature has been kept to provide -compatibility with C-Prolog. When compiling a goal, YAP -generates a `call( _X_)` whenever a variable _X_ is found as -a goal. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - a(X) :- X. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -is converted to: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - a(X) :- call(X). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred if(? _G_,? _H_,? _I_) - -Call goal _H_ once per each solution of goal _H_. If goal - _H_ has no solutions, call goal _I_. - -The built-in `if/3` is similar to `-\>/3`, with the difference -that it will backtrack over the test goal. Consider the following -small data-base: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -a(1). b(a). c(x). -a(2). b(b). c(y). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Execution of an `if/3` query will proceed as follows: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- if(a(X),b(Y),c(Z)). - -X = 1, -Y = a ? ; - -X = 1, -Y = b ? ; - -X = 2, -Y = a ? ; - -X = 2, -Y = b ? ; - -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The system will backtrack over the two solutions for `a/1` and the -two solutions for `b/1`, generating four solutions. - -Cuts are allowed inside the first goal _G_, but they will only prune -over _G_. - -If you want _G_ to be deterministic you should use if-then-else, as -it is both more efficient and more portable. - - -*/ - -/** @pred once(: _G_) is iso - - -Execute the goal _G_ only once. The predicate is defined by: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - once(G) :- call(G), !. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that cuts inside once/1 can only cut the other goals inside -once/1. - - -*/ - -/** @pred forall(: _Cond_,: _Action_) - - -For all alternative bindings of _Cond_ _Action_ can be -proven. The example verifies that all arithmetic statements in the list - _L_ are correct. It does not say which is wrong if one proves wrong. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), - Result =:= Formula). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred ignore(: _Goal_) - - -Calls _Goal_ as once/1, but succeeds, regardless of whether -`Goal` succeeded or not. Defined as: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -ignore(Goal) :- - Goal, !. -ignore(_). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred abort - - -Abandons the execution of the current goal and returns to top level. All -break levels (see break/0 below) are terminated. It is mainly -used during debugging or after a serious execution error, to return to -the top-level. - - -*/ - -/** @pred break - - -Suspends the execution of the current goal and creates a new execution -level similar to the top level, displaying the following message: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - [ Break (level ) ] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -telling the depth of the break level just entered. To return to the -previous level just type the end-of-file character or call the -end_of_file predicate. This predicate is especially useful during -debugging. - - -*/ - -/** @pred halt is iso - - -Halts Prolog, and exits to the calling application. In YAP, -halt/0 returns the exit code `0`. - - -*/ - -/** @pred halt(+ _I_) is iso - -Halts Prolog, and exits to the calling application returning the code -given by the integer _I_. - - -*/ - -/** @pred catch( : _Goal_,+ _Exception_,+ _Action_) is iso - - -The goal `catch( _Goal_, _Exception_, _Action_)` tries to -execute goal _Goal_. If during its execution, _Goal_ throws an -exception _E'_ and this exception unifies with _Exception_, the -exception is considered to be caught and _Action_ is executed. If -the exception _E'_ does not unify with _Exception_, control -again throws the exception. - -The top-level of YAP maintains a default exception handler that -is responsible to capture uncaught exceptions. - - -*/ - -/** @pred throw(+ _Ball_) is iso - - -The goal `throw( _Ball_)` throws an exception. Execution is -stopped, and the exception is sent to the ancestor goals until reaching -a matching catch/3, or until reaching top-level. - - -*/ - -/** @pred garbage_collect - - -The goal `garbage_collect` forces a garbage collection. - - -*/ - -/** @pred garbage_collect_atoms - - -The goal `garbage_collect` forces a garbage collection of the atoms -in the data-base. Currently, only atoms are recovered. - - -*/ - -/** @pred gc - - -The goal `gc` enables garbage collection. The same as -`yap_flag(gc,on)`. - - -*/ - -/** @pred nogc - - -The goal `nogc` disables garbage collection. The same as -`yap_flag(gc,off)`. - - -*/ - -/** @pred grow_heap(+ _Size_) -Increase heap size _Size_ kilobytes. - - -*/ - -/** @pred grow_stack(+ _Size_) - - -Increase stack size _Size_ kilobytes - - -@} */ - -/** @defgroup Undefined_Procedures Handling Undefined Procedures -@ingroup YAPBuiltins -@{ - -A predicate in a module is said to be undefined if there are no clauses -defining the predicate, and if the predicate has not been declared to be -dynamic. What YAP does when trying to execute undefined predicates can -be specified in three different ways: - - + By setting an YAP flag, through the yap_flag/2 or -set_prolog_flag/2 built-ins. This solution generalizes the -ISO standard. - + By using the unknown/2 built-in (this solution is -compatible with previous releases of YAP). - + By defining clauses for the hook predicate -`user:unknown_predicate_handler/3`. This solution is compatible -with SICStus Prolog. - - -In more detail: - - - -*/ - -/** @pred unknown(- _O_,+ _N_) - - -Specifies an handler to be called is a program tries to call an -undefined static procedure _P_. - -The arity of _N_ may be zero or one. If the arity is `0`, the -new action must be one of `fail`, `warning`, or -`error`. If the arity is `1`, _P_ is an user-defined -handler and at run-time, the argument to the handler _P_ will be -unified with the undefined goal. Note that _N_ must be defined prior -to calling unknown/2, and that the single argument to _N_ must -be unbound. - -In YAP, the default action is to `fail` (note that in the ISO -Prolog standard the default action is `error`). - -After defining `undefined/1` by: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -undefined(A) :- format('Undefined predicate: ~w~n',[A]), fail. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -and executing the goal: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -unknown(U,undefined(X)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -a call to a predicate for which no clauses were defined will result in -the output of a message of the form: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Undefined predicate: user:xyz(A1,A2) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -followed by the failure of that call. - - -*/ - -/** @pred yap_flag(unknown,+ _SPEC_) - -Alternatively, one can use yap_flag/2, -current_prolog_flag/2, or set_prolog_flag/2, to set this -functionality. In this case, the first argument for the built-ins should -be `unknown`, and the second argument should be either -`error`, `warning`, `fail`, or a goal. - - -*/ - -/** @pred user:unknown_predicate_handler(+G,+M,?NG) - - -The user may also define clauses for -`user:unknown_predicate_handler/3` hook predicate. This -user-defined procedure is called before any system processing for the -undefined procedure, with the first argument _G_ set to the current -goal, and the second _M_ set to the current module. The predicate - _G_ will be called from within the user module. - -If `user:unknown_predicate_handler/3` succeeds, the system will -execute _NG_. If `user:unknown_predicate_handler/3` fails, the -system will execute default action as specified by unknown/2. - - -*/ - -/** @pred exception(+ _Exception_, + _Context_, - _Action_) - - -Dynamic predicate, normally not defined. Called by the Prolog system on run-time exceptions that can be repaired `just-in-time'. The values for _Exception_ are described below. See also catch/3 and throw/1. -If this hook predicate succeeds it must instantiate the _Action_ argument to the atom `fail` to make the operation fail silently, `retry` to tell Prolog to retry the operation or `error` to make the system generate an exception. The action `retry` only makes sense if this hook modified the environment such that the operation can now succeed without error. - - + undefined_predicate - _Context_ is instantiated to a predicate-indicator ( _Module:Name/Arity_). If the predicate fails Prolog will generate an existence_error exception. The hook is intended to implement alternatives to the SWI built-in autoloader, such as autoloading code from a database. Do not use this hook to suppress existence errors on predicates. See also `unknown`. - + undefined_global_variable - _Context_ is instantiated to the name of the missing global variable. The hook must call nb_setval/2 or b_setval/2 before returning with the action retry. - - - - - -@} */ - -/** @defgroup Messages Message Handling -@ingroup YAPBuiltins -@{ - -The interaction between YAP and the user relies on YAP's ability to -portray messages. These messages range from prompts to error -information. All message processing is performed through the builtin -print_message/2, in two steps: - - + The message is processed into a list of commands - + The commands in the list are sent to the `format/3` builtin -in sequence. - - -The first argument to print_message/2 specifies the importance of -the message. The options are: - - + error -error handling - + warning -compilation and run-time warnings, - + informational -generic informational messages - + help -help messages (not currently implemented in YAP) - + query -query used in query processing (not currently implemented in YAP) - + silent -messages that do not produce output but that can be intercepted by hooks. - - -The next table shows the main predicates and hooks associated to message -handling in YAP: - - -*/ - -/** @pred print_message(+ _Kind_, _Term_) - -The predicate print_message/2 is used to print messages, notably from -exceptions in a human-readable format. _Kind_ is one of -`informational`, `banner`, `warning`, `error`, -`help` or `silent`. A human-readable message is printed to -the stream user_error. - -If the Prolog flag verbose is `silent`, messages with - _Kind_ `informational`, or `banner` are treated as -silent.@c See \\cmdlineoption{-q}. - -This predicate first translates the _Term_ into a list of `message -lines' (see print_message_lines/3 for details). Next it will -call the hook message_hook/3 to allow the user intercepting the -message. If message_hook/3 fails it will print the message unless - _Kind_ is silent. - -If you need to report errors from your own predicates, we advise you to -stick to the existing error terms if you can; but should you need to -invent new ones, you can define corresponding error messages by -asserting clauses for `prolog:message/2`. You will need to declare -the predicate as multifile. - - -*/ - -/** @pred print_message_lines(+ _Stream_, + _Prefix_, + _Lines_) - - -Print a message (see print_message/2) that has been translated to -a list of message elements. The elements of this list are: - - + `\`-`\` -Where _Format_ is an atom and _Args_ is a list -of format argument. Handed to `format/3`. - + `flush` -If this appears as the last element, _Stream_ is flushed -(see `flush_output/1`) and no final newline is generated. - + `at_same_line` -If this appears as first element, no prefix is printed for -the first line and the line-position is not forced to 0 -(see `format/1`, `~N`). - + `\` -Handed to `format/3` as `format(Stream, Format, [])`. - + nl -A new line is started and if the message is not complete -the _Prefix_ is printed too. - - - -*/ - -/** @pred user:message_hook(+ _Term_, + _Kind_, + _Lines_) - - -Hook predicate that may be define in the module `user` to intercept -messages from print_message/2. _Term_ and _Kind_ are the -same as passed to print_message/2. _Lines_ is a list of -format statements as described with print_message_lines/3. - -This predicate should be defined dynamic and multifile to allow other -modules defining clauses for it too. - - -*/ - -/** @pred message_to_string(+ _Term_, - _String_) - - -Translates a message-term into a string object. Primarily intended for SWI-Prolog emulation. - - - -@} */ - -/** @defgroup Testing_Terms Predicates on terms -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred var( _T_) is iso - - -Succeeds if _T_ is currently a free variable, otherwise fails. - - -*/ - -/** @pred atom( _T_) is iso - - -Succeeds if and only if _T_ is currently instantiated to an atom. - - -*/ - -/** @pred atomic(T) is iso - - -Checks whether _T_ is an atomic symbol (atom or number). - - -*/ - -/** @pred compound( _T_) is iso - - -Checks whether _T_ is a compound term. - - -*/ - -/** @pred db_reference( _T_) - - -Checks whether _T_ is a database reference. - - -*/ - -/** @pred float( _T_) is iso - - -Checks whether _T_ is a floating point number. - - -*/ - -/** @pred rational( _T_) - - -Checks whether `T` is a rational number. - - -*/ - -/** @pred integer( _T_) is iso - - -Succeeds if and only if _T_ is currently instantiated to an integer. - - -*/ - -/** @pred nonvar( _T_) is iso - - -The opposite of `var( _T_)`. - - -*/ - -/** @pred number( _T_) is iso - - -Checks whether `T` is an integer, rational or a float. - - -*/ - -/** @pred primitive( _T_) - - -Checks whether _T_ is an atomic term or a database reference. - - -*/ - -/** @pred simple( _T_) - - -Checks whether _T_ is unbound, an atom, or a number. - - -*/ - -/** @pred callable( _T_) is iso - - -Checks whether _T_ is a callable term, that is, an atom or a -compound term. - - -*/ - -/** @pred numbervars( _T_,+ _N1_,- _Nn_) - - -Instantiates each variable in term _T_ to a term of the form: -`'$VAR'( _I_)`, with _I_ increasing from _N1_ to _Nn_. - - -*/ - -/** @pred unnumbervars( _T_,+ _NT_) - - -Replace every `'$VAR'( _I_)` by a free variable. - - -*/ - -/** @pred ground( _T_) is iso - - -Succeeds if there are no free variables in the term _T_. - - -*/ - -/** @pred acyclic_term( _T_) is iso - - -Succeeds if there are loops in the term _T_, that is, it is an infinite term. - - -*/ - -/** @pred arg(+ _N_,+ _T_, _A_) is iso - - -Succeeds if the argument _N_ of the term _T_ unifies with - _A_. The arguments are numbered from 1 to the arity of the term. - -The current version will generate an error if _T_ or _N_ are -unbound, if _T_ is not a compound term, of if _N_ is not a positive -integer. Note that previous versions of YAP would fail silently -under these errors. - - -*/ - -/** @pred functor( _T_, _F_, _N_) is iso - - -The top functor of term _T_ is named _F_ and has arity _N_. - -When _T_ is not instantiated, _F_ and _N_ must be. If - _N_ is 0, _F_ must be an atomic symbol, which will be unified -with _T_. If _N_ is not 0, then _F_ must be an atom and - _T_ becomes instantiated to the most general term having functor - _F_ and arity _N_. If _T_ is instantiated to a term then - _F_ and _N_ are respectively unified with its top functor name -and arity. - -In the current version of YAP the arity _N_ must be an -integer. Previous versions allowed evaluable expressions, as long as the -expression would evaluate to an integer. This feature is not available -in the ISO Prolog standard. - - -*/ - -/** @pred _T_ =.. _L_ is iso - - -The list _L_ is built with the functor and arguments of the term - _T_. If _T_ is instantiated to a variable, then _L_ must be -instantiated either to a list whose head is an atom, or to a list -consisting of just a number. - - -*/ - -/** @pred _X_ = _Y_ is iso - - -Tries to unify terms _X_ and _Y_. - - -*/ - -/** @pred _X_ \\= _Y_ is iso - - -Succeeds if terms _X_ and _Y_ are not unifiable. - - -*/ - -/** @pred unify_with_occurs_check(?T1,?T2) is iso - - -Obtain the most general unifier of terms _T1_ and _T2_, if there -is one. - -This predicate implements the full unification algorithm. An example:n - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -will succeed with the bindings `A = b` and `Z = f(B)`. On the -other hand: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -would fail, because `Z` is not unifiable with `f(Z)`. Note that -`(=)/2` would succeed for the previous examples, giving the following -bindings `A = b` and `Z = f(Z)`. - - -*/ - -/** @pred copy_term(? _TI_,- _TF_) is iso - - -Term _TF_ is a variant of the original term _TI_, such that for -each variable _V_ in the term _TI_ there is a new variable _V'_ -in term _TF_. Notice that: - - + suspended goals and attributes for attributed variables in _TI_ are also duplicated; - + ground terms are shared between the new and the old term. - -If you do not want any sharing to occur please use -duplicate_term/2. - - -*/ - -/** @pred duplicate_term(? _TI_,- _TF_) - - -Term _TF_ is a variant of the original term _TI_, such that -for each variable _V_ in the term _TI_ there is a new variable - _V'_ in term _TF_, and the two terms do not share any -structure. All suspended goals and attributes for attributed variables -in _TI_ are also duplicated. - -Also refer to copy_term/2. - - -*/ - -/** @pred is_list(+ _List_) - - -True when _List_ is a proper list. That is, _List_ -is bound to the empty list (nil) or a term with functor '.' and arity 2. - - -*/ - -/** @pred ? _Term1_ =@= ? _Term2_ - - - -Same as variant/2, succeeds if _Term1_ and _Term2_ are variant terms. - - -*/ - -/** @pred subsumes_term(? _Subsumer_, ? _Subsumed_) - - - -Succeed if _Submuser_ subsumes _Subsuned_ but does not bind any -variable in _Subsumer_. - - -*/ - -/** @pred term_subsumer(? _T1_, ? _T2_, ? _Subsumer_) - - - -Succeed if _Subsumer_ unifies with the least general -generalization over _T1_ and - _T2_. - - -*/ - -/** @pred term_variables(? _Term_, - _Variables_) is iso - - - -Unify _Variables_ with the list of all variables of term - _Term_. The variables occur in the order of their first -appearance when traversing the term depth-first, left-to-right. - - -*/ - -/** @pred rational_term_to_tree(? _TI_,- _TF_) - - -The term _TF_ is a tree representation (without cycles) for the -Prolog term _TI_. Loops are replaced by terms of the form -`_LOOP_( _LevelsAbove_)` where _LevelsAbove_ is the size of -the loop. - - -*/ - -/** @pred tree_to_rational_term(? _TI_,- _TF_) - - -Inverse of rational_term_to_tree/2. The term _TI_ is a tree representation (without -cycles) for the Prolog term _TF_. Loops replace terms of the form -`_LOOP_( _LevelsAbove_)` where _LevelsAbove_ is the size of -the loop. - - - - -@} */ - -/** @defgroup Predicates_on_Atoms Predicates on Atoms -@ingroup YAPBuiltins -@{ - -The following predicates are used to manipulate atoms: - - - -*/ - -/** @pred name( _A_, _L_) - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ will -be unified with an atomic symbol and _L_ with the list of the ASCII -codes for the characters of the external representation of _A_. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - name(yap,L). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -will return: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - L = [121,97,112]. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -and - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - name(3,L). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -will return: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - L = [51]. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred atom_chars(? _A_,? _L_) is iso - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ must -be unifiable with an atom, and the argument _L_ with the list of the -characters of _A_. - - -*/ - -/** @pred atom_codes(? _A_,? _L_) is iso - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ will -be unified with an atom and _L_ with the list of the ASCII -codes for the characters of the external representation of _A_. - - -*/ - -/** @pred atom_concat(+ _As_,? _A_) - - -The predicate holds when the first argument is a list of atoms, and the -second unifies with the atom obtained by concatenating all the atoms in -the first list. - - -*/ - -/** @pred atomic_concat(+ _As_,? _A_) - - -The predicate holds when the first argument is a list of atomic terms, and -the second unifies with the atom obtained by concatenating all the -atomic terms in the first list. The first argument thus may contain -atoms or numbers. - - -*/ - -/** @pred atomic_list_concat(+ _As_,? _A_) - - -The predicate holds when the first argument is a list of atomic terms, and -the second unifies with the atom obtained by concatenating all the -atomic terms in the first list. The first argument thus may contain -atoms or numbers. - - -*/ - -/** @pred atomic_list_concat(? _As_,+ _Separator_,? _A_) - -Creates an atom just like atomic_list_concat/2, but inserts - _Separator_ between each pair of atoms. For example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- atomic_list_concat([gnu, gnat], ', ', A). - -A = 'gnu, gnat' -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -YAP emulates the SWI-Prolog version of this predicate that can also be -used to split atoms by instantiating _Separator_ and _Atom_ as -shown below. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- atomic_list_concat(L, -, 'gnu-gnat'). - -L = [gnu, gnat] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred atom_length(+ _A_,? _I_) is iso - - -The predicate holds when the first argument is an atom, and the second -unifies with the number of characters forming that atom. - - -*/ - -/** @pred atom_concat(? _A1_,? _A2_,? _A12_) is iso - -The predicate holds when the third argument unifies with an atom, and -the first and second unify with atoms such that their representations -concatenated are the representation for _A12_. - -If _A1_ and _A2_ are unbound, the built-in will find all the atoms -that concatenated give _A12_. - - -*/ - -/** @pred number_chars(? _I_,? _L_) is iso - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _I_ must -be unifiable with a number, and the argument _L_ with the list of the -characters of the external representation of _I_. - - -*/ - -/** @pred number_codes(? _A_,? _L_) is iso - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ -will be unified with a number and _L_ with the list of the ASCII -codes for the characters of the external representation of _A_. - - -*/ - -/** @pred atom_number(? _Atom_,? _Number_) - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). If the argument - _Atom_ is an atom, _Number_ must be the number corresponding -to the characters in _Atom_, otherwise the characters in - _Atom_ must encode a number _Number_. - - -*/ - -/** @pred number_atom(? _I_,? _L_) - - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _I_ must -be unifiable with a number, and the argument _L_ must be unifiable -with an atom representing the number. - - -*/ - -/** @pred sub_atom(+ _A_,? _Bef_, ? _Size_, ? _After_, ? _At_out_) is iso - - -True when _A_ and _At_out_ are atoms such that the name of - _At_out_ has size _Size_ and is a sub-string of the name of - _A_, such that _Bef_ is the number of characters before and - _After_ the number of characters afterwards. - -Note that _A_ must always be known, but _At_out_ can be unbound when -calling this built-in. If all the arguments for sub_atom/5 but _A_ -are unbound, the built-in will backtrack through all possible -sub-strings of _A_. - - - - -@} */ - -/** @defgroup Predicates_on_Characters Predicates on Characters -@ingroup YAPBuiltins -@{ - -The following predicates are used to manipulate characters: - - - -*/ - -/** @pred char_code(? _A_,? _I_) is iso - - -The built-in succeeds with _A_ bound to character represented as an -atom, and _I_ bound to the character code represented as an -integer. At least, one of either _A_ or _I_ must be bound before -the call. - - -*/ - -/** @pred char_type(? _Char_, ? _Type_) - - -Tests or generates alternative _Types_ or _Chars_. The -character-types are inspired by the standard `C` -`\` primitives. - - + alnum - _Char_ is a letter (upper- or lowercase) or digit. - - + alpha - _Char_ is a letter (upper- or lowercase). - - + csym - _Char_ is a letter (upper- or lowercase), digit or the underscore (_). These are valid C- and Prolog symbol characters. - - + csymf - _Char_ is a letter (upper- or lowercase) or the underscore (_). These are valid first characters for C- and Prolog symbols - - + ascii - _Char_ is a 7-bits ASCII character (0..127). - - + white - _Char_ is a space or tab. E.i. white space inside a line. - - + cntrl - _Char_ is an ASCII control-character (0..31). - - + digit - _Char_ is a digit. - - + digit( _Weight_) - _Char_ is a digit with value _Weight_. I.e. `char_type(X, digit(6))` yields `X = '6'`. Useful for parsing numbers. - - + xdigit( _Weight_) - _Char_ is a hexa-decimal digit with value _Weight_. I.e. char_type(a, xdigit(X) yields X = '10'. Useful for parsing numbers. - - + graph - _Char_ produces a visible mark on a page when printed. Note that the space is not included! - - + lower - _Char_ is a lower-case letter. - - + lower(Upper) - _Char_ is a lower-case version of _Upper_. Only true if _Char_ is lowercase and _Upper_ uppercase. - - + to_lower(Upper) - _Char_ is a lower-case version of Upper. For non-letters, or letter without case, _Char_ and Lower are the same. See also upcase_atom/2 and downcase_atom/2. - - + upper - _Char_ is an upper-case letter. - - + upper(Lower) - _Char_ is an upper-case version of Lower. Only true if _Char_ is uppercase and Lower lowercase. - - + to_upper(Lower) - _Char_ is an upper-case version of Lower. For non-letters, or letter without case, _Char_ and Lower are the same. See also upcase_atom/2 and downcase_atom/2. - - + punct - _Char_ is a punctuation character. This is a graph character that is not a letter or digit. - - + space - _Char_ is some form of layout character (tab, vertical-tab, newline, etc.). - - + end_of_file - _Char_ is -1. - - + end_of_line - _Char_ ends a line (ASCII: 10..13). - - + newline - _Char_ is a the newline character (10). - - + period - _Char_ counts as the end of a sentence (.,!,?). - - + quote - _Char_ is a quote-character (", ', `). - - + paren(Close) - _Char_ is an open-parenthesis and Close is the corresponding close-parenthesis. - - - + code_type(? _Code_, ? _Type_) - - -As char_type/2, but uses character-codes rather than -one-character atoms. Please note that both predicates are as -flexible as possible. They handle either representation if the -argument is instantiated and only will instantiate with an integer -code or one-character atom depending of the version used. See also -the prolog-flag double_quotes and the built-in predicates -atom_chars/2 and atom_codes/2. - - - - -@} */ - -/** @defgroup Comparing_Terms Comparing Terms -@ingroup YAPBuiltins -@{ - -The following predicates are used to compare and order terms, using the -standard ordering: - - + -variables come before numbers, numbers come before atoms which in turn -come before compound terms, i.e.: variables @\< numbers @\< atoms @\< -compound terms. - + -Variables are roughly ordered by "age" (the "oldest" variable is put -first); - + -Floating point numbers are sorted in increasing order; - + -Rational numbers are sorted in increasing order; - + -Integers are sorted in increasing order; - + -Atoms are sorted in lexicographic order; - + -Compound terms are ordered first by arity of the main functor, then by -the name of the main functor, and finally by their arguments in -left-to-right order. - - - - - -*/ - -/** @pred compare( _C_, _X_, _Y_) is iso - - -As a result of comparing _X_ and _Y_, _C_ may take one of -the following values: - - + -`=` if _X_ and _Y_ are identical; - + -`\<` if _X_ precedes _Y_ in the defined order; - + -`\>` if _Y_ precedes _X_ in the defined order; - - - + _X_ == _Y_ is iso - - -Succeeds if terms _X_ and _Y_ are strictly identical. The -difference between this predicate and =/2 is that, if one of the -arguments is a free variable, it only succeeds when they have already -been unified. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- X == Y. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -fails, but, - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- X = Y, X == Y. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -succeeds. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- X == 2. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -fails, but, - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- X = 2, X == 2. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -succeeds. - - -*/ - -/** @pred _X_ \\== _Y_ is iso - - -Terms _X_ and _Y_ are not strictly identical. - - -*/ - -/** @pred _X_ @\< _Y_ is iso - - -Term _X_ precedes term _Y_ in the standard order. - - -*/ - -/** @pred _X_ @=\< _Y_ is iso - - -Term _X_ does not follow term _Y_ in the standard order. - - -*/ - -/** @pred _X_ @\> _Y_ is iso - - -Term _X_ follows term _Y_ in the standard order. - - -*/ - -/** @pred _X_ @\>= _Y_ is iso - - -Term _X_ does not precede term _Y_ in the standard order. - - -*/ - -/** @pred sort(+ _L_,- _S_) is iso - - -Unifies _S_ with the list obtained by sorting _L_ and merging -identical (in the sense of `==`) elements. - - -*/ - -/** @pred keysort(+ _L_, _S_) is iso - - -Assuming L is a list of the form ` _Key_- _Value_`, -`keysort(+ _L_, _S_)` unifies _S_ with the list obtained -from _L_, by sorting its elements according to the value of - _Key_. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- keysort([3-a,1-b,2-c,1-a,1-b],S). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -would return: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -S = [1-b,1-a,1-b,2-c,3-a] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred predsort(+ _Pred_, + _List_, - _Sorted_) - - -Sorts similar to sort/2, but determines the order of two terms by -calling _Pred_(- _Delta_, + _E1_, + _E2_) . This call must -unify _Delta_ with one of `\<`, `\>` or `=`. If -built-in predicate compare/3 is used, the result is the same as -sort/2. - - -*/ - -/** @pred length(? _L_,? _S_) - - -Unify the well-defined list _L_ with its length. The procedure can -be used to find the length of a pre-defined list, or to build a list -of length _S_. - - - - -@} */ - -/** @defgroup Arithmetic Arithmetic -@ingroup YAPBuiltins -@{ - -@copydoc arithmetic - - * See @ref arithmetic_preds for the predicates that implement arithment - - * See @ref arithmetic_cmps for the arithmetic comparisons supported in YAP - - * See @ref arithmetic_operators for how to call arithmetic operations in YAP - - -@} */ - -/** @defgroup InputOutput Input/Output Predicates -@ingroup YAPBuiltins -@{ - -Some of the Input/Output predicates described below will in certain conditions -provide error messages and abort only if the file_errors flag is set. -If this flag is cleared the same predicates will just fail. Details on -setting and clearing this flag are given under 7.7. - - -@} */ - -/** @defgroup Streams_and_Files Handling Streams and Files -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred open(+ _F_,+ _M_,- _S_) is iso - - -Opens the file with name _F_ in mode _M_ ('read', 'write' or -'append'), returning _S_ unified with the stream name. - -At most, there are 17 streams opened at the same time. Each stream is -either an input or an output stream but not both. There are always 3 -open streams: user_input for reading, user_output for writing -and user_error for writing. If there is no ambiguity, the atoms -user_input and user_output may be referred to as `user`. - -The `file_errors` flag controls whether errors are reported when in -mode 'read' or 'append' the file _F_ does not exist or is not -readable, and whether in mode 'write' or 'append' the file is not -writable. - - + open(+ _F_,+ _M_,- _S_,+ _Opts_) is iso - -Opens the file with name _F_ in mode _M_ ('read', 'write' or -'append'), returning _S_ unified with the stream name, and following -these options: - - - - + type(+ _T_) is iso -Specify whether the stream is a `text` stream (default), or a -`binary` stream. - - + reposition(+ _Bool_) is iso -Specify whether it is possible to reposition the stream (`true`), or -not (`false`). By default, YAP enables repositioning for all -files, except terminal files and sockets. - - + eof_a -*/ - -/** @pred n(+ _Action_) is iso -Specify the action to take if attempting to input characters from a -stream where we have previously found an `end_of_file`. The possible -actions are `error`, that raises an error, `reset`, that tries to -reset the stream and is used for `tty` type files, and `eof_code`, -which generates a new `end_of_file` (default for non-tty files). - - + alias(+ _Name_) is iso -Specify an alias to the stream. The alias Name must be an atom. The -alias can be used instead of the stream descriptor for every operation -concerning the stream. - -The operation will fail and give an error if the alias name is already -in use. YAP allows several aliases for the same file, but only -one is returned by stream_property/2 - - + bom(+ _Bool_) -If present and `true`, a BOM (Byte Order Mark) was -detected while opening the file for reading or a BOM was written while -opening the stream. See BOM for details. - - + encoding(+ _Encoding_) -Set the encoding used for text. See Encoding for an overview of -wide character and encoding issues. - - + representation_errors(+ _Mode_) -Change the behaviour when writing characters to the stream that cannot -be represented by the encoding. The behaviour is one of `error` -(throw and Input/Output error exception), `prolog` (write `\\u...\\` -escape code or `xml` (write `\&#...;` XML character entity). -The initial mode is `prolog` for the user streams and -`error` for all other streams. See also Encoding. - - + expand_filename(+ _Mode_) -If _Mode_ is `true` then do filename expansion, then ask Prolog -to do file name expansion before actually trying to opening the file: -this includes processing `~` characters and processing `$` -environment variables at the beginning of the file. Otherwise, just try -to open the file using the given name. - -The default behavior is given by the Prolog flag -open_expands_filename. - - - - -*/ - -/** @pred close(+ _S_) is iso - - -Closes the stream _S_. If _S_ does not stand for a stream -currently opened an error is reported. The streams user_input, -user_output, and user_error can never be closed. - - -*/ - -/** @pred close(+ _S_,+ _O_) is iso - -Closes the stream _S_, following options _O_. - -The only valid options are `force(true)` and `force(false)`. -YAP currently ignores these options. - - -*/ - -/** @pred time_file(+ _File_,- _Time_) - - -Unify the last modification time of _File_ with - _Time_. _Time_ is a floating point number expressing the seconds -elapsed since Jan 1, 1970. - - -*/ - -/** @pred access_file(+ _F_,+ _M_) - -Is the file accessible? - - -*/ - -/** @pred file_base_name(+ _Name_,- _FileName_) - - -Give the path a full path _FullPath_ extract the _FileName_. - - -*/ - -/** @pred file_name_extension(? _Base_,? _Extension_, ? _Name_) - - - -This predicate is used to add, remove or test filename extensions. The -main reason for its introduction is to deal with different filename -properties in a portable manner. If the file system is -case-insensitive, testing for an extension will be done -case-insensitive too. _Extension_ may be specified with or -without a leading dot (.). If an _Extension_ is generated, it -will not have a leading dot. - - -*/ - -/** @pred current_stream( _F_, _M_, _S_) - - -Defines the relation: The stream _S_ is opened on the file _F_ -in mode _M_. It might be used to obtain all open streams (by -backtracking) or to access the stream for a file _F_ in mode - _M_, or to find properties for a stream _S_. Notice that some -streams might not be associated to a file: in this case YAP tries to -return the file number. If that is not available, YAP unifies _F_ -with _S_. - - -*/ - -/** @pred is_stream( _S_) - - -Succeeds if _S_ is a currently open stream. - - -*/ - -/** @pred flush_output is iso - - -Send out all data in the output buffer of the current output stream. - - -*/ - -/** @pred flush_output(+ _S_) is iso - -Send all data in the output buffer for stream _S_. - - -*/ - -/** @pred set_input(+ _S_) is iso - - -Set stream _S_ as the current input stream. Predicates like read/1 -and get/1 will start using stream _S_. - - -*/ - -/** @pred set_output(+ _S_) is iso - - -Set stream _S_ as the current output stream. Predicates like -write/1 and put/1 will start using stream _S_. - - -*/ - -/** @pred stream_select(+ _STREAMS_,+ _TIMEOUT_,- _READSTREAMS_) - - -Given a list of open _STREAMS_ opened in read mode and a _TIMEOUT_ -return a list of streams who are now available for reading. - -If the _TIMEOUT_ is instantiated to `off`, -stream_select/3 will wait indefinitely for a stream to become -open. Otherwise the timeout must be of the form `SECS:USECS` where -`SECS` is an integer gives the number of seconds to wait for a timeout -and `USECS` adds the number of micro-seconds. - -This built-in is only defined if the system call `select` is -available in the system. - - -*/ - -/** @pred current_input(- _S_) is iso - - -Unify _S_ with the current input stream. - - -*/ - -/** @pred current_output(- _S_) is iso - - -Unify _S_ with the current output stream. - - -*/ - -/** @pred at_end_of_stream is iso - - -Succeed if the current stream has stream position end-of-stream or -past-end-of-stream. - - -*/ - -/** @pred at_end_of_stream(+ _S_) is iso - -Succeed if the stream _S_ has stream position end-of-stream or -past-end-of-stream. Note that _S_ must be a readable stream. - - -*/ - -/** @pred set_stream_position(+ _S_, + _POS_) is iso - - -Given a stream position _POS_ for a stream _S_, set the current -stream position for _S_ to be _POS_. - - -*/ - -/** @pred stream_property(? _Stream_,? _Prop_) is iso - - - -Obtain the properties for the open streams. If the first argument is -unbound, the procedure will backtrack through all open -streams. Otherwise, the first argument must be a stream term (you may -use `current_stream` to obtain a current stream given a file name). - -The following properties are recognized: - - - - + file_name( _P_) -An atom giving the file name for the current stream. The file names are -user_input, user_output, and user_error for the -standard streams. - - + mode( _P_) -The mode used to open the file. It may be one of `append`, -`read`, or `write`. - - + input -The stream is readable. - - + output -The stream is writable. - - + alias( _A_) -ISO-Prolog primitive for stream aliases. YAP returns one of the -existing aliases for the stream. - - + position( _P_) -A term describing the position in the stream. - - + end_of_stream( _E_) -Whether the stream is `at` the end of stream, or it has found the -end of stream and is `past`, or whether it has `not` yet -reached the end of stream. - - + eof_action( _A_) -The action to take when trying to read after reaching the end of -stream. The action may be one of `error`, generate an error, -`eof_code`, return character code `-1`, or `reset` the -stream. - - + reposition( _B_) -Whether the stream can be repositioned or not, that is, whether it is -seekable. - - + type( _T_) -Whether the stream is a `text` stream or a `binary` stream. - - + bom(+ _Bool_) -If present and `true`, a BOM (Byte Order Mark) was -detected while opening the file for reading or a BOM was written while -opening the stream. See BOM for details. - - + encoding(+ _Encoding_) -Query the encoding used for text. See Encoding for an -overview of wide character and encoding issues in YAP. - - + representation_errors(+ _Mode_) -Behaviour when writing characters to the stream that cannot be -represented by the encoding. The behaviour is one of `error` -(throw and Input/Output error exception), `prolog` (write `\\u...\\` -escape code or `xml` (write `\&#...;` XML character entity). -The initial mode is `prolog` for the user streams and -`error` for all other streams. See also Encoding and -`open/4`. - - - - + current_line_number(- _LineNumber_) - - -Unify _LineNumber_ with the line number for the current stream. - - -*/ - -/** @pred current_line_number(+ _Stream_,- _LineNumber_) - -Unify _LineNumber_ with the line number for the _Stream_. - - -*/ - -/** @pred line_count(+ _Stream_,- _LineNumber_) - - -Unify _LineNumber_ with the line number for the _Stream_. - - -*/ - -/** @pred character_count(+ _Stream_,- _CharacterCount_) - - -Unify _CharacterCount_ with the number of characters written to or -read to _Stream_. - - -*/ - -/** @pred line_position(+ _Stream_,- _LinePosition_) - - -Unify _LinePosition_ with the position on current text stream - _Stream_. - - -*/ - -/** @pred stream_position(+ _Stream_,- _StreamPosition_) - - -Unify _StreamPosition_ with the packaged information of position on -current stream _Stream_. Use stream_position_data/3 to -retrieve information on character or line count. - - -*/ - -/** @pred stream_position_data(+ _Field_,+ _StreamPosition_,- _Info_) - - -Given the packaged stream position term _StreamPosition_, unify - _Info_ with _Field_ `line_count`, `byte_count`, or -`char_count`. - - - - -@} */ - -/** @defgroup ChYProlog_File_Handling C-Prolog File Handling -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred tell(+ _S_) - - -If _S_ is a currently opened stream for output, it becomes the -current output stream. If _S_ is an atom it is taken to be a -filename. If there is no output stream currently associated with it, -then it is opened for output, and the new output stream created becomes -the current output stream. If it is not possible to open the file, an -error occurs. If there is a single opened output stream currently -associated with the file, then it becomes the current output stream; if -there are more than one in that condition, one of them is chosen. - -Whenever _S_ is a stream not currently opened for output, an error -may be reported, depending on the state of the file_errors flag. The -predicate just fails, if _S_ is neither a stream nor an atom. - - -*/ - -/** @pred telling(- _S_) - - -The current output stream is unified with _S_. - - -*/ - -/** @pred told - - -Closes the current output stream, and the user's terminal becomes again -the current output stream. It is important to remember to close streams -after having finished using them, as the maximum number of -simultaneously opened streams is 17. - - -*/ - -/** @pred see(+ _S_) - - -If _S_ is a currently opened input stream then it is assumed to be -the current input stream. If _S_ is an atom it is taken as a -filename. If there is no input stream currently associated with it, then -it is opened for input, and the new input stream thus created becomes -the current input stream. If it is not possible to open the file, an -error occurs. If there is a single opened input stream currently -associated with the file, it becomes the current input stream; if there -are more than one in that condition, then one of them is chosen. - -When _S_ is a stream not currently opened for input, an error may be -reported, depending on the state of the `file_errors` flag. If - _S_ is neither a stream nor an atom the predicates just fails. - - -*/ - -/** @pred seeing(- _S_) - - -The current input stream is unified with _S_. - - -*/ - -/** @pred seen - - -Closes the current input stream (see 6.7.). - - - - -@} */ - -/** @defgroup InputOutput_of_Terms Handling Input/Output of Terms -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred read(- _T_) is iso - - -Reads the next term from the current input stream, and unifies it with - _T_. The term must be followed by a dot ('.') and any blank-character -as previously defined. The syntax of the term must match the current -declarations for operators (see op). If the end-of-stream is reached, - _T_ is unified with the atom `end_of_file`. Further reads from of -the same stream may cause an error failure (see open/3). - - + read_term(- _T_,+ _Options_) is iso - - -Reads term _T_ from the current input stream with execution -controlled by the following options: - - - - -*/ - -/** @pred term_position(- _Position_) - -Unify _Position_ with a term describing the position of the stream -at the start of parse. Use stream_position_data/3 to obtain extra -information. - - + singletons(- _Names_) - -Unify _Names_ with a list of the form _Name=Var_, where - _Name_ is the name of a non-anonymous singleton variable in the -original term, and `Var` is the variable's representation in -YAP. -The variables occur in left-to-right traversal order. - - + syntax_errors(+ _Val_) - -Control action to be taken after syntax errors. See yap_flag/2 -for detailed information. - - + variable -*/ - -/** @pred es(- _Names_) - -Unify _Names_ with a list of the form _Name=Var_, where _Name_ is -the name of a non-anonymous variable in the original term, and _Var_ -is the variable's representation in YAP. -The variables occur in left-to-right traversal order. - - + variables(- _Names_) - -Unify _Names_ with a list of the variables in term _T_. -The variables occur in left-to-right traversal order. - - - - + char_conversion(+ _IN_,+ _OUT_) is iso - - -While reading terms convert unquoted occurrences of the character - _IN_ to the character _OUT_. Both _IN_ and _OUT_ must be -bound to single characters atoms. - -Character conversion only works if the flag `char_conversion` is -on. This is default in the `iso` and `sicstus` language -modes. As an example, character conversion can be used for instance to -convert characters from the ISO-LATIN-1 character set to ASCII. - -If _IN_ is the same character as _OUT_, char_conversion/2 -will remove this conversion from the table. - - -*/ - -/** @pred current_char_conversion(? _IN_,? _OUT_) is iso - - -If _IN_ is unbound give all current character -translations. Otherwise, give the translation for _IN_, if one -exists. - - -*/ - -/** @pred write( _T_) is iso - - -The term _T_ is written to the current output stream according to -the operator declarations in force. - - -*/ - -/** @pred writeln( _T_) is iso - - -Same as write/1 followed by nl/0. - - -*/ - -/** @pred display(+ _T_) - - -Displays term _T_ on the current output stream. All Prolog terms are -written in standard parenthesized prefix notation. - - -*/ - -/** @pred write_canonical(+ _T_) is iso - - -Displays term _T_ on the current output stream. Atoms are quoted -when necessary, and operators are ignored, that is, the term is written -in standard parenthesized prefix notation. - - -*/ - -/** @pred write_term(+ _T_, + _Opts_) is iso - - -Displays term _T_ on the current output stream, according to the -following options: - - + quoted(+ _Bool_) is iso -If `true`, quote atoms if this would be necessary for the atom to -be recognized as an atom by YAP's parser. The default value is -`false`. - - + ignore_ops(+ _Bool_) is iso -If `true`, ignore operator declarations when writing the term. The -default value is `false`. - - + numbervars(+ _Bool_) is iso -If `true`, output terms of the form -`'$VAR'(N)`, where _N_ is an integer, as a sequence of capital -letters. The default value is `false`. - - + portrayed(+ _Bool_) -If `true`, use portray/1 to portray bound terms. The default -value is `false`. - - + portray(+ _Bool_) -If `true`, use portray/1 to portray bound terms. The default -value is `false`. - - + max_depth(+ _Depth_) -If `Depth` is a positive integer, use Depth as -the maximum depth to portray a term. The default is `0`, that is, -unlimited depth. - - + priority(+ _Piority_) -If `Priority` is a positive integer smaller than `1200`, -give the context priority. The default is `1200`. - - + cycles(+ _Bool_) -Do not loop in rational trees (default). - - - -*/ - -/** @pred writeq( _T_) is iso - - -Writes the term _T_, quoting names to make the result acceptable to -the predicate 'read' whenever necessary. - - -*/ - -/** @pred print( _T_) - - -Prints the term _T_ to the current output stream using write/1 -unless T is bound and a call to the user-defined predicate -`portray/1` succeeds. To do pretty printing of terms the user should -define suitable clauses for `portray/1` and use print/1. - - -*/ - -/** @pred format(+ _T_,+ _L_) - - -Print formatted output to the current output stream. The arguments in -list _L_ are output according to the string or atom _T_. - -A control sequence is introduced by a `w`. The following control -sequences are available in YAP: - - - - + '~~' -Print a single tilde. - - + '~a' -The next argument must be an atom, that will be printed as if by `write`. - - + '~Nc' -The next argument must be an integer, that will be printed as a -character code. The number _N_ is the number of times to print the -character (default 1). - - + '~Ne' - + '~NE' - + '~Nf' - + '~Ng' - + '~NG' -The next argument must be a floating point number. The float _F_, the number - _N_ and the control code `c` will be passed to `printf` as: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - printf("%s.Nc", F) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -As an example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("~8e, ~8E, ~8f, ~8g, ~8G~w", - [3.14,3.14,3.14,3.14,3.14,3.14]). -3.140000e+00, 3.140000E+00, 3.140000, 3.14, 3.143.14 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~Nd' -The next argument must be an integer, and _N_ is the number of digits -after the decimal point. If _N_ is `0` no decimal points will be -printed. The default is _N = 0_. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("~2d, ~d",[15000, 15000]). -150.00, 15000 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~ND' -Identical to `'~Nd'`, except that commas are used to separate groups -of three digits. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("~2D, ~D",[150000, 150000]). -1,500.00, 150,000 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~i' -Ignore the next argument in the list of arguments: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format('The ~i met the boregrove',[mimsy]). -The met the boregrove -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~k' -Print the next argument with `write_canonical`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("Good night ~k",a+[1,2]). -Good night +(a,[1,2]) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~Nn' -Print _N_ newlines (where _N_ defaults to 1). - - + '~NN' -Print _N_ newlines if at the beginning of the line (where _N_ -defaults to 1). - - + '~Nr' -The next argument must be an integer, and _N_ is interpreted as a -radix, such that `2 \<= N \<= 36` (the default is 8). - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("~2r, 0x~16r, ~r", - [150000, 150000, 150000]). -100100100111110000, 0x249f0, 444760 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that the letters `a-z` denote digits larger than 9. - - + '~NR' -Similar to '~NR'. The next argument must be an integer, and _N_ is -interpreted as a radix, such that `2 \<= N \<= 36` (the default is 8). - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("~2r, 0x~16r, ~r", - [150000, 150000, 150000]). -100100100111110000, 0x249F0, 444760 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The only difference is that letters `A-Z` denote digits larger than 9. - - + '~p' -Print the next argument with print/1: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("Good night ~p",a+[1,2]). -Good night a+[1,2] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~q' -Print the next argument with writeq/1: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("Good night ~q",'Hello'+[1,2]). -Good night 'Hello'+[1,2] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~Ns' -The next argument must be a list of character codes. The system then -outputs their representation as a string, where _N_ is the maximum -number of characters for the string ( _N_ defaults to the length of the -string). - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("The ~s are ~4s",["woods","lovely"]). -The woods are love -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + '~w' -Print the next argument with write/1: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- format("Good night ~w",'Hello'+[1,2]). -Good night Hello+[1,2] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -The number of arguments, `N`, may be given as an integer, or it -may be given as an extra argument. The next example shows a small -procedure to write a variable number of `a` characters: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -write_many_as(N) :- - format("~*c",[N,0'a]). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The format/2 built-in also allows for formatted output. One can -specify column boundaries and fill the intermediate space by a padding -character: - - + '~N|' -Set a column boundary at position _N_, where _N_ defaults to the -current position. - - + '~N+' -Set a column boundary at _N_ characters past the current position, where - _N_ defaults to `8`. - - + '~Nt' -Set padding for a column, where _N_ is the fill code (default is -`SPC`). - - - -The next example shows how to align columns and padding. We first show -left-alignment: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- format("~n*Hello~16+*~n",[]). -*Hello * -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that we reserve 16 characters for the column. - -The following example shows how to do right-alignment: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- format("*~tHello~16+*~n",[]). -* Hello* - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The `~t` escape sequence forces filling before `Hello`. - -We next show how to do centering: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- format("*~tHello~t~16+*~n",[]). -* Hello * -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The two `~t` escape sequence force filling both before and after -`Hello`. Space is then evenly divided between the right and the -left sides. - - -*/ - -/** @pred format(+ _T_) - -Print formatted output to the current output stream. - - -*/ - -/** @pred format(+ _S_,+ _T_,+ _L_) - -Print formatted output to stream _S_. - - -*/ - -/** @pred with_output_to(+ _Ouput_,: _Goal_) - - -Run _Goal_ as once/1, while characters written to the current -output are sent to _Output_. The predicate is SWI-Prolog -specific. - -Applications should generally avoid creating atoms by breaking and -concatenating other atoms as the creation of large numbers of -intermediate atoms generally leads to poor performance, even more so in -multi-threaded applications. This predicate supports creating -difference-lists from character data efficiently. The example below -defines the DCG rule `term/3` to insert a term in the output: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - term(Term, In, Tail) :- - with_output_to(codes(In, Tail), write(Term)). - -?- phrase(term(hello), X). - -X = [104, 101, 108, 108, 111] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + A Stream handle or alias -Temporary switch current output to the given stream. Redirection using with_output_to/2 guarantees the original output is restored, also if Goal fails or raises an exception. See also call_cleanup/2. - + atom(- _Atom_) -Create an atom from the emitted characters. Please note the remark above. - + string(- _String_) -Create a string-object (not supported in YAP). - + codes(- _Codes_) -Create a list of character codes from the emitted characters, similar to atom_codes/2. - + codes(- _Codes_, - _Tail_) -Create a list of character codes as a difference-list. - + chars(- _Chars_) -Create a list of one-character-atoms codes from the emitted characters, similar to atom_chars/2. - + chars(- _Chars_, - _Tail_) -Create a list of one-character-atoms as a difference-list. - - - - - -@} */ - -/** @defgroup InputOutput_of_Characters Handling Input/Output of Characters -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred put(+ _N_) - - -Outputs to the current output stream the character whose ASCII code is - _N_. The character _N_ must be a legal ASCII character code, an -expression yielding such a code, or a list in which case only the first -element is used. - - -*/ - -/** @pred put_byte(+ _N_) is iso - - -Outputs to the current output stream the character whose code is - _N_. The current output stream must be a binary stream. - - -*/ - -/** @pred put_char(+ _N_) is iso - - -Outputs to the current output stream the character who is used to build -the representation of atom `A`. The current output stream must be a -text stream. - - -*/ - -/** @pred put_code(+ _N_) is iso - - -Outputs to the current output stream the character whose ASCII code is - _N_. The current output stream must be a text stream. The character - _N_ must be a legal ASCII character code, an expression yielding such -a code, or a list in which case only the first element is used. - - -*/ - -/** @pred get(- _C_) - - -The next non-blank character from the current input stream is unified -with _C_. Blank characters are the ones whose ASCII codes are not -greater than 32. If there are no more non-blank characters in the -stream, _C_ is unified with -1. If `end_of_stream` has already -been reached in the previous reading, this call will give an error message. - - -*/ - -/** @pred get0(- _C_) - - -The next character from the current input stream is consumed, and then -unified with _C_. There are no restrictions on the possible -values of the ASCII code for the character, but the character will be -internally converted by YAP. - - -*/ - -/** @pred get_byte(- _C_) is iso - - -If _C_ is unbound, or is a character code, and the current stream is a -binary stream, read the next byte from the current stream and unify its -code with _C_. - - -*/ - -/** @pred get_char(- _C_) is iso - - -If _C_ is unbound, or is an atom representation of a character, and -the current stream is a text stream, read the next character from the -current stream and unify its atom representation with _C_. - - -*/ - -/** @pred get_code(- _C_) is iso - - -If _C_ is unbound, or is the code for a character, and -the current stream is a text stream, read the next character from the -current stream and unify its code with _C_. - - -*/ - -/** @pred peek_byte(- _C_) is iso - - -If _C_ is unbound, or is a character code, and the current stream is a -binary stream, read the next byte from the current stream and unify its -code with _C_, while leaving the current stream position unaltered. - - -*/ - -/** @pred peek_char(- _C_) is iso - - -If _C_ is unbound, or is an atom representation of a character, and -the current stream is a text stream, read the next character from the -current stream and unify its atom representation with _C_, while -leaving the current stream position unaltered. - - -*/ - -/** @pred peek_code(- _C_) is iso - - -If _C_ is unbound, or is the code for a character, and -the current stream is a text stream, read the next character from the -current stream and unify its code with _C_, while -leaving the current stream position unaltered. - - -*/ - -/** @pred skip(+ _N_) - - -Skips input characters until the next occurrence of the character with -ASCII code _N_. The argument to this predicate can take the same forms -as those for `put` (see 6.11). - - -*/ - -/** @pred tab(+ _N_) - - -Outputs _N_ spaces to the current output stream. - - -*/ - -/** @pred nl is iso - - -Outputs a new line to the current output stream. - - - - -@} */ - -/** @defgroup InputOutput_for_Streams Input/Output Predicates applied to Streams -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred read(+ _S_,- _T_) is iso - -Reads term _T_ from the stream _S_ instead of from the current input -stream. - - -*/ - -/** @pred read_term(+ _S_,- _T_,+ _Options_) is iso - -Reads term _T_ from stream _S_ with execution controlled by the -same options as read_term/2. - - -*/ - -/** @pred write(+ _S_, _T_) is iso - -Writes term _T_ to stream _S_ instead of to the current output -stream. - - -*/ - -/** @pred write_canonical(+ _S_,+ _T_) is iso - -Displays term _T_ on the stream _S_. Atoms are quoted when -necessary, and operators are ignored. - - -*/ - -/** @pred write_term(+ _S_, + _T_, + _Opts_) is iso - -Displays term _T_ on the current output stream, according to the same -options used by `write_term/3`. - - -*/ - -/** @pred writeq(+ _S_, _T_) is iso - -As writeq/1, but the output is sent to the stream _S_. - - -*/ - -/** @pred display(+ _S_, _T_) - -Like display/1, but using stream _S_ to display the term. - - -*/ - -/** @pred print(+ _S_, _T_) - -Prints term _T_ to the stream _S_ instead of to the current output -stream. - - -*/ - -/** @pred put(+ _S_,+ _N_) - -As `put(N)`, but to stream _S_. - - -*/ - -/** @pred put_byte(+ _S_,+ _N_) is iso - -As `put_byte(N)`, but to binary stream _S_. - - -*/ - -/** @pred put_char(+ _S_,+ _A_) is iso - -As `put_char(A)`, but to text stream _S_. - - -*/ - -/** @pred put_code(+ _S_,+ _N_) is iso - -As `put_code(N)`, but to text stream _S_. - - -*/ - -/** @pred get(+ _S_,- _C_) - -The same as `get(C)`, but from stream _S_. - - -*/ - -/** @pred get0(+ _S_,- _C_) - -The same as `get0(C)`, but from stream _S_. - - -*/ - -/** @pred get_byte(+ _S_,- _C_) is iso - -If _C_ is unbound, or is a character code, and the stream _S_ is a -binary stream, read the next byte from that stream and unify its -code with _C_. - - -*/ - -/** @pred get_char(+ _S_,- _C_) is iso - -If _C_ is unbound, or is an atom representation of a character, and -the stream _S_ is a text stream, read the next character from that -stream and unify its representation as an atom with _C_. - - -*/ - -/** @pred get_code(+ _S_,- _C_) is iso - -If _C_ is unbound, or is a character code, and the stream _S_ is a -text stream, read the next character from that stream and unify its -code with _C_. - - -*/ - -/** @pred peek_byte(+ _S_,- _C_) is iso - -If _C_ is unbound, or is a character code, and _S_ is a binary -stream, read the next byte from the current stream and unify its code -with _C_, while leaving the current stream position unaltered. - - -*/ - -/** @pred peek_char(+ _S_,- _C_) is iso - -If _C_ is unbound, or is an atom representation of a character, and -the stream _S_ is a text stream, read the next character from that -stream and unify its representation as an atom with _C_, while leaving -the current stream position unaltered. - - -*/ - -/** @pred peek_code(+ _S_,- _C_) is iso - -If _C_ is unbound, or is an atom representation of a character, and -the stream _S_ is a text stream, read the next character from that -stream and unify its representation as an atom with _C_, while leaving -the current stream position unaltered. - - -*/ - -/** @pred skip(+ _S_,- _C_) - -Like skip/1, but using stream _S_ instead of the current -input stream. - - -*/ - -/** @pred tab(+ _S_,+ _N_) - -The same as tab/1, but using stream _S_. - - -*/ - -/** @pred nl(+ _S_) is iso - -Outputs a new line to stream _S_. - - - - -@} */ - -/** @defgroup ChYProlog_to_Terminal Compatible C-Prolog predicates for Terminal Input/Output -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred ttyput(+ _N_) - - -As `put(N)` but always to user_output. - - -*/ - -/** @pred ttyget(- _C_) - - -The same as `get(C)`, but from stream user_input. - - -*/ - -/** @pred ttyget0(- _C_) - - -The same as `get0(C)`, but from stream user_input. - - -*/ - -/** @pred ttyskip(- _C_) - - -Like skip/1, but always using stream user_input. -stream. - - -*/ - -/** @pred ttytab(+ _N_) - - -The same as tab/1, but using stream user_output. - - -*/ - -/** @pred ttynl - - -Outputs a new line to stream user_output. - - - - -@} */ - -/** @defgroup InputOutput_Control Controlling Input/Output -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred exists(+ _F_) - - -Checks if file _F_ exists in the current directory. - - + nofileerrors - - -Switches off the file_errors flag, so that the predicates see/1, -tell/1, open/3 and close/1 just fail, instead of producing -an error message and aborting whenever the specified file cannot be -opened or closed. - - + fileerrors - - -Switches on the file_errors flag so that in certain error conditions -Input/Output predicates will produce an appropriated message and abort. - - + always_prompt_user - - -Force the system to prompt the user even if the user_input stream -is not a terminal. This command is useful if you want to obtain -interactive control from a pipe or a socket. - - - - -@} */ - -/** @defgroup Sockets Using Sockets From YAP -@ingroup YAPBuiltins -@{ - -YAP includes a SICStus Prolog compatible socket interface. In YAP-6.3 -this uses the `clib` package to emulate the old low level interface that -provides direct access to the major socket system calls. These calls -can be used both to open a new connection in the network or connect to -a networked server. Socket connections are described as read/write -streams, and standard Input/Output built-ins can be used to write on or read -from sockets. The following calls are available: - - - - -*/ - -/** @pred socket(+ _DOMAIN_,+ _TYPE_,+ _PROTOCOL_,- _SOCKET_) - - -Corresponds to the BSD system call `socket`. Create a socket for -domain _DOMAIN_ of type _TYPE_ and protocol - _PROTOCOL_. Both _DOMAIN_ and _TYPE_ should be atoms, -whereas _PROTOCOL_ must be an integer. -The new socket object is -accessible through a descriptor bound to the variable _SOCKET_. - -The current implementation of YAP accepts socket -domains `'AF_INET'` and `'AF_UNIX'`. -Socket types depend on the -underlying operating system, but at least the following types are -supported: `'SOCK_STREAM'` and `'SOCK_DGRAM'` (untested in 6.3). - - -*/ - -/** @pred socket(+ _DOMAIN_,- _SOCKET_) - - -Call socket/4 with _TYPE_ bound to `'SOCK_STREAM'` and - _PROTOCOL_ bound to `0`. - - -*/ - -/** @pred socket_close(+ _SOCKET_) - - - -Close socket _SOCKET_. Note that sockets used in -`socket_connect` (that is, client sockets) should not be closed with -`socket_close`, as they will be automatically closed when the -corresponding stream is closed with close/1 or `close/2`. - - -*/ - -/** @pred socket_bind(+ _SOCKET_, ? _PORT_) - - - -Interface to system call `bind`, as used for servers: bind socket -to a port. Port information depends on the domain: - - + 'AF_UNIX'(+ _FILENAME_) (unsupported) - + 'AF_FILE'(+ _FILENAME_) -use file name _FILENAME_ for UNIX or local sockets. - - + 'AF_INET'(? _HOST_,?PORT) -If _HOST_ is bound to an atom, bind to host _HOST_, otherwise -if unbound bind to local host ( _HOST_ remains unbound). If port - _PORT_ is bound to an integer, try to bind to the corresponding -port. If variable _PORT_ is unbound allow operating systems to -choose a port number, which is unified with _PORT_. - - - - -*/ - -/** @pred socket_connect(+ _SOCKET_, + _PORT_, - _STREAM_) - - - -Interface to system call `connect`, used for clients: connect -socket _SOCKET_ to _PORT_. The connection results in the -read/write stream _STREAM_. - -Port information depends on the domain: - - + 'AF_UNIX'(+ _FILENAME_) - + 'AF_FILE'(+ _FILENAME_) -connect to socket at file _FILENAME_. - - + 'AF_INET'(+ _HOST_,+ _PORT_) -Connect to socket at host _HOST_ and port _PORT_. - - - -*/ - -/** @pred socket_listen(+ _SOCKET_, + _LENGTH_) - - -Interface to system call `listen`, used for servers to indicate -willingness to wait for connections at socket _SOCKET_. The -integer _LENGTH_ gives the queue limit for incoming connections, -and should be limited to `5` for portable applications. The socket -must be of type `SOCK_STREAM` or `SOCK_SEQPACKET`. - - -*/ - -/** @pred socket_accept(+ _SOCKET_, - _CLIENT_, - _STREAM_) - - -Interface to system call `accept`, used for servers to wait for -connections at socket _SOCKET_. The stream descriptor _STREAM_ -represents the resulting connection. If the socket belongs to the -domain `'AF_INET'`, _CLIENT_ unifies with an atom containing -the IP address for the client in numbers and dots notation. - - -*/ - -/** @pred socket_accept(+ _SOCKET_, - _STREAM_) - -Accept a connection but do not return client information. - - -*/ - -/** @pred socket_buffering(+ _SOCKET_, - _MODE_, - _OLD_, + _NEW_) - - -Set buffering for _SOCKET_ in `read` or `write` - _MODE_. _OLD_ is unified with the previous status, and _NEW_ -receives the new status which may be one of `unbuf` or -`fullbuf`. - - -*/ - -/** @pred socket_select(+ _SOCKETS_, - _NEWSTREAMS_, + _TIMEOUT_, - -+ _STREAMS_, - _READSTREAMS_) [unsupported in YAP-6.3] - -Interface to system call `select`, used for servers to wait for -connection requests or for data at sockets. The variable - _SOCKETS_ is a list of form _KEY-SOCKET_, where _KEY_ is -an user-defined identifier and _SOCKET_ is a socket descriptor. The -variable _TIMEOUT_ is either `off`, indicating execution will -wait until something is available, or of the form _SEC-USEC_, where - _SEC_ and _USEC_ give the seconds and microseconds before -socket_select/5 returns. The variable _SOCKETS_ is a list of -form _KEY-STREAM_, where _KEY_ is an user-defined identifier -and _STREAM_ is a stream descriptor - -Execution of socket_select/5 unifies _READSTREAMS_ from - _STREAMS_ with readable data, and _NEWSTREAMS_ with a list of -the form _KEY-STREAM_, where _KEY_ was the key for a socket -with pending data, and _STREAM_ the stream descriptor resulting -from accepting the connection. - - -*/ - -/** @pred current_host(? _HOSTNAME_) - -Unify _HOSTNAME_ with an atom representing the fully qualified -hostname for the current host. Also succeeds if _HOSTNAME_ is bound -to the unqualified hostname. - - -*/ - -/** @pred hostname_address(? _HOSTNAME_,? _IP_ADDRESS_) - - _HOSTNAME_ is an host name and _IP_ADDRESS_ its IP -address in number and dots notation. - - - - -@} */ - -/** @defgroup Database Using the Clausal Data Base -@ingroup YAPBuiltins -@{ - -Predicates in YAP may be dynamic or static. By default, when -consulting or reconsulting, predicates are assumed to be static: -execution is faster and the code will probably use less space. -Static predicates impose some restrictions: in general there can be no -addition or removal of clauses for a procedure if it is being used in the -current execution. - -Dynamic predicates allow programmers to change the Clausal Data Base with -the same flexibility as in C-Prolog. With dynamic predicates it is -always possible to add or remove clauses during execution and the -semantics will be the same as for C-Prolog. But the programmer should be -aware of the fact that asserting or retracting are still expensive operations, -and therefore he should try to avoid them whenever possible. - - - - -*/ - -/** @pred dynamic + _P_ - - -Declares predicate _P_ or list of predicates [ _P1_,..., _Pn_] -as a dynamic predicate. _P_ must be written in form: - _name/arity_. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- dynamic god/1. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -a more convenient form can be used: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- dynamic son/3, father/2, mother/2. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -or, equivalently, - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- dynamic [son/3, father/2, mother/2]. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note: - -a predicate is assumed to be dynamic when -asserted before being defined. - - -*/ - -/** @pred dynamic_predicate(+ _P_,+ _Semantics_) - - -Declares predicate _P_ or list of predicates [ _P1_,..., _Pn_] -as a dynamic predicate following either `logical` or -`immediate` semantics. - - -*/ - -/** @pred compile_predicates(: _ListOfNameArity_) - - - -Compile a list of specified dynamic predicates (see dynamic/1 and -assert/1 into normal static predicates. This call tells the -Prolog environment the definition will not change anymore and further -calls to assert/1 or retract/1 on the named predicates -raise a permission error. This predicate is designed to deal with parts -of the program that is generated at runtime but does not change during -the remainder of the program execution. - - - - -@} */ - -/** @defgroup Modifying_the_Database Modification of the Data Base -@ingroup YAPBuiltins -@{ - -These predicates can be used either for static or for dynamic -predicates: - - - - -*/ - -/** @pred assert(+ _C_) - - -Same as assertz/1. Adds clause _C_ to the program. If the predicate is undefined, -declare it as dynamic. New code should use assertz/1 for better portability. - -Most Prolog systems only allow asserting clauses for dynamic -predicates. This is also as specified in the ISO standard. YAP allows -asserting clauses for static predicates, as long as the predicate is not -in use and the language flag is cprolog. Note that this feature is -deprecated, if you want to assert clauses for static procedures you -should use assert_static/1. - - -*/ - -/** @pred asserta(+ _C_) is iso - - -Adds clause _C_ to the beginning of the program. If the predicate is -undefined, declare it as dynamic. - - -*/ - -/** @pred assertz(+ _C_) is iso - - -Adds clause _C_ to the end of the program. If the predicate is -undefined, declare it as dynamic. - -Most Prolog systems only allow asserting clauses for dynamic -predicates. This is also as specified in the ISO standard. YAP allows -asserting clauses for static predicates. The current version of YAP -supports this feature, but this feature is deprecated and support may go -away in future versions. - - -*/ - -/** @pred abolish(+ _PredSpec_) is iso - - -Deletes the predicate given by _PredSpec_ from the database. If - _PredSpec_ is an unbound variable, delete all predicates for the -current module. The -specification must include the name and arity, and it may include module -information. Under iso language mode this built-in will only abolish -dynamic procedures. Under other modes it will abolish any procedures. - - -*/ - -/** @pred abolish(+ _P_,+ _N_) - -Deletes the predicate with name _P_ and arity _N_. It will remove -both static and dynamic predicates. - - -*/ - -/** @pred assert_static(: _C_) - - -Adds clause _C_ to a static procedure. Asserting a static clause -for a predicate while choice-points for the predicate are available has -undefined results. - - -*/ - -/** @pred asserta_static(: _C_) - - -Adds clause _C_ to the beginning of a static procedure. - - -*/ - -/** @pred assertz_static(: _C_) - - -Adds clause _C_ to the end of a static procedure. Asserting a -static clause for a predicate while choice-points for the predicate are -available has undefined results. - - - -The following predicates can be used for dynamic predicates and for -static predicates, if source mode was on when they were compiled: - - - - -*/ - -/** @pred clause(+ _H_, _B_) is iso - - -A clause whose head matches _H_ is searched for in the -program. Its head and body are respectively unified with _H_ and - _B_. If the clause is a unit clause, _B_ is unified with - _true_. - -This predicate is applicable to static procedures compiled with -`source` active, and to all dynamic procedures. - - -*/ - -/** @pred clause(+ _H_, _B_,- _R_) - -The same as clause/2, plus _R_ is unified with the -reference to the clause in the database. You can use instance/2 -to access the reference's value. Note that you may not use -erase/1 on the reference on static procedures. - - -*/ - -/** @pred nth_clause(+ _H_, _I_,- _R_) - - -Find the _I_th clause in the predicate defining _H_, and give -a reference to the clause. Alternatively, if the reference _R_ is -given the head _H_ is unified with a description of the predicate -and _I_ is bound to its position. - - - -The following predicates can only be used for dynamic predicates: - - - - -*/ - -/** @pred retract(+ _C_) is iso - - -Erases the first clause in the program that matches _C_. This -predicate may also be used for the static predicates that have been -compiled when the source mode was `on`. For more information on -source/0 ( (see Setting the Compiler)). - - -*/ - -/** @pred retractall(+ _G_) is iso - - -Retract all the clauses whose head matches the goal _G_. Goal - _G_ must be a call to a dynamic predicate. - - - - -@} */ - -/** @defgroup Looking_at_the_Database Looking at the Data Base -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred listing - - -Lists in the current output stream all the clauses for which source code -is available (these include all clauses for dynamic predicates and -clauses for static predicates compiled when source mode was `on`). - - -*/ - -/** @pred listing(+ _P_) - -Lists predicate _P_ if its source code is available. - - -*/ - -/** @pred portray_clause(+ _C_) - - -Write clause _C_ as if written by listing/0. - - -*/ - -/** @pred portray_clause(+ _S_,+ _C_) - -Write clause _C_ on stream _S_ as if written by listing/0. - - -*/ - -/** @pred current_atom( _A_) - - -Checks whether _A_ is a currently defined atom. It is used to find all -currently defined atoms by backtracking. - - -*/ - -/** @pred current_predicate( _F_) is iso - - - _F_ is the predicate indicator for a currently defined user or -library predicate. _F_ is of the form _Na/Ar_, where the atom - _Na_ is the name of the predicate, and _Ar_ its arity. - - -*/ - -/** @pred current_predicate( _A_, _P_) - -Defines the relation: _P_ is a currently defined predicate whose -name is the atom _A_. - - -*/ - -/** @pred system_predicate( _A_, _P_) - - -Defines the relation: _P_ is a built-in predicate whose name -is the atom _A_. - - -*/ - -/** @pred predicate_property( _P_, _Prop_) is iso - - -For the predicates obeying the specification _P_ unify _Prop_ -with a property of _P_. These properties may be: - - + built_in - -true for built-in predicates, - + dynamic -true if the predicate is dynamic - + static - -true if the predicate is static - + meta_predicate( _M_) - -true if the predicate has a meta_predicate declaration _M_. - + multifile - -true if the predicate was declared to be multifile - + imported_from( _Mod_) - -true if the predicate was imported from module _Mod_. - + exported - -true if the predicate is exported in the current module. - + public -true if the predicate is public; note that all dynamic predicates are -public. - + tabled - -true if the predicate is tabled; note that only static predicates can -be tabled in YAP. - + source (predicate_property flag) - -true if source for the predicate is available. - + number_of_clauses( _ClauseCount_) - -Number of clauses in the predicate definition. Always one if external -or built-in. - - - -*/ - -/** @pred predicate_statistics( _P_, _NCls_, _Sz_, _IndexSz_) - - -Given predicate _P_, _NCls_ is the number of clauses for - _P_, _Sz_ is the amount of space taken to store those clauses -(in bytes), and _IndexSz_ is the amount of space required to store -indices to those clauses (in bytes). - - -*/ - -/** @pred predicate_erased_statistics( _P_, _NCls_, _Sz_, _IndexSz_) - - -Given predicate _P_, _NCls_ is the number of erased clauses for - _P_ that could not be discarded yet, _Sz_ is the amount of space -taken to store those clauses (in bytes), and _IndexSz_ is the amount -of space required to store indices to those clauses (in bytes). - - - - -@} */ - -/** @defgroup Database_References Using Data Base References -@ingroup YAPBuiltins -@{ - -Data Base references are a fast way of accessing terms. The predicates -erase/1 and `instance/1` also apply to these references and may -sometimes be used instead of retract/1 and clause/2. - - - - -*/ - -/** @pred assert(+ _C_,- _R_) - -The same as `assert(C)` ( (see Modifying the Database)) but -unifies _R_ with the database reference that identifies the new -clause, in a one-to-one way. Note that `asserta/2` only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - - -*/ - -/** @pred asserta(+ _C_,- _R_) - -The same as `asserta(C)` but unifying _R_ with -the database reference that identifies the new clause, in a -one-to-one way. Note that `asserta/2` only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - - -*/ - -/** @pred assertz(+ _C_,- _R_) - -The same as `assertz(C)` but unifying _R_ with -the database reference that identifies the new clause, in a -one-to-one way. Note that `asserta/2` only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - - -*/ - -/** @pred retract(+ _C_,- _R_) - -Erases from the program the clause _C_ whose -database reference is _R_. The predicate must be dynamic. - - - - -@} */ - -/** @defgroup Internal_Database Internal Data Base -@ingroup YAPBuiltins -@{ - -Some programs need global information for, e.g. counting or collecting -data obtained by backtracking. As a rule, to keep this information, the -internal data base should be used instead of asserting and retracting -clauses (as most novice programmers do), . -In YAP (as in some other Prolog systems) the internal data base (i.d.b. -for short) is faster, needs less space and provides a better insulation of -program and data than using asserted/retracted clauses. -The i.d.b. is implemented as a set of terms, accessed by keys that -unlikely what happens in (non-Prolog) data bases are not part of the -term. Under each key a list of terms is kept. References are provided so that -terms can be identified: each term in the i.d.b. has a unique reference -(references are also available for clauses of dynamic predicates). - - - - -*/ - -/** @pred recorda(+ _K_, _T_,- _R_) - - -Makes term _T_ the first record under key _K_ and unifies _R_ -with its reference. - - -*/ - -/** @pred recordz(+ _K_, _T_,- _R_) - - -Makes term _T_ the last record under key _K_ and unifies _R_ -with its reference. - - -*/ - -/** @pred recorda_at(+ _R0_, _T_,- _R_) - - -Makes term _T_ the record preceding record with reference - _R0_, and unifies _R_ with its reference. - - -*/ - -/** @pred recordz_at(+ _R0_, _T_,- _R_) - - -Makes term _T_ the record following record with reference - _R0_, and unifies _R_ with its reference. - - -*/ - -/** @pred recordaifnot(+ _K_, _T_,- _R_) - - -If a term equal to _T_ up to variable renaming is stored under key - _K_ fail. Otherwise, make term _T_ the first record under key - _K_ and unify _R_ with its reference. - - -*/ - -/** @pred recordzifnot(+ _K_, _T_,- _R_) - - -If a term equal to _T_ up to variable renaming is stored under key - _K_ fail. Otherwise, make term _T_ the first record under key - _K_ and unify _R_ with its reference. - -This predicate is YAP specific. - - -*/ - -/** @pred recorded(+ _K_, _T_, _R_) - - -Searches in the internal database under the key _K_, a term that -unifies with _T_ and whose reference matches _R_. This -built-in may be used in one of two ways: - - + _K_ may be given, in this case the built-in will return all -elements of the internal data-base that match the key. - + _R_ may be given, if so returning the key and element that -match the reference. - - - -*/ - -/** @pred erase(+ _R_) - - -The term referred to by _R_ is erased from the internal database. If -reference _R_ does not exist in the database, `erase` just fails. - - -*/ - -/** @pred erased(+ _R_) - - -Succeeds if the object whose database reference is _R_ has been -erased. - - -*/ - -/** @pred instance(+ _R_,- _T_) - - -If _R_ refers to a clause or a recorded term, _T_ is unified -with its most general instance. If _R_ refers to an unit clause - _C_, then _T_ is unified with ` _C_ :- true`. When - _R_ is not a reference to an existing clause or to a recorded term, -this goal fails. - - -*/ - -/** @pred eraseall(+ _K_) - - -All terms belonging to the key `K` are erased from the internal -database. The predicate always succeeds. - - -*/ - -/** @pred current_key(? _A_,? _K_) - - -Defines the relation: _K_ is a currently defined database key whose -name is the atom _A_. It can be used to generate all the keys for -the internal data-base. - - -*/ - -/** @pred nth_instance(? _Key_,? _Index_,? _R_) - - -Fetches the _Index_nth entry in the internal database under the key - _Key_. Entries are numbered from one. If the key _Key_ or the - _Index_ are bound, a reference is unified with _R_. Otherwise, -the reference _R_ must be given, and YAP will find -the matching key and index. - - -*/ - -/** @pred nth_instance(? _Key_,? _Index_, _T_,? _R_) - -Fetches the _Index_nth entry in the internal database under the key - _Key_. Entries are numbered from one. If the key _Key_ or the - _Index_ are bound, a reference is unified with _R_. Otherwise, -the reference _R_ must be given, and YAP will find -the matching key and index. - - -*/ - -/** @pred key_statistics(+ _K_,- _Entries_,- _Size_,- _IndexSize_) - - -Returns several statistics for a key _K_. Currently, it says how -many entries we have for that key, _Entries_, what is the -total size spent on entries, _Size_, and what is the amount of -space spent in indices. - - -*/ - -/** @pred key_statistics(+ _K_,- _Entries_,- _TotalSize_) - -Returns several statistics for a key _K_. Currently, it says how -many entries we have for that key, _Entries_, what is the -total size spent on this key. - - -*/ - -/** @pred get_value(+ _A_,- _V_) - - -In YAP, atoms can be associated with constants. If one such -association exists for atom _A_, unify the second argument with the -constant. Otherwise, unify _V_ with `[]`. - -This predicate is YAP specific. - - -*/ - -/** @pred set_value(+ _A_,+ _C_) - - -Associate atom _A_ with constant _C_. - -The `set_value` and `get_value` built-ins give a fast alternative to -the internal data-base. This is a simple form of implementing a global -counter. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - read_and_increment_counter(Value) :- - get_value(counter, Value), - Value1 is Value+1, - set_value(counter, Value1). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This predicate is YAP specific. - - - -There is a strong analogy between the i.d.b. and the way dynamic -predicates are stored. In fact, the main i.d.b. predicates might be -implemented using dynamic predicates: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -recorda(X,T,R) :- asserta(idb(X,T),R). -recordz(X,T,R) :- assertz(idb(X,T),R). -recorded(X,T,R) :- clause(idb(X,T),R). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We can take advantage of this, the other way around, as it is quite -easy to write a simple Prolog interpreter, using the i.d.b.: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -asserta(G) :- recorda(interpreter,G,_). -assertz(G) :- recordz(interpreter,G,_). -retract(G) :- recorded(interpreter,G,R), !, erase(R). -call(V) :- var(V), !, fail. -call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B). -call(G) :- recorded(interpreter,G,_). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In YAP, much attention has been given to the implementation of the -i.d.b., especially to the problem of accelerating the access to terms kept in -a large list under the same key. Besides using the key, YAP uses an internal -lookup function, transparent to the user, to find only the terms that might -unify. For instance, in a data base containing the terms - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -b -b(a) -c(d) -e(g) -b(X) -e(h) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -stored under the key k/1, when executing the query - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- recorded(k(_),c(_),R). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -`recorded` would proceed directly to the third term, spending almost the -time as if `a(X)` or `b(X)` was being searched. -The lookup function uses the functor of the term, and its first three -arguments (when they exist). So, `recorded(k(_),e(h),_)` would go -directly to the last term, while `recorded(k(_),e(_),_)` would find -first the fourth term, and then, after backtracking, the last one. - -This mechanism may be useful to implement a sort of hierarchy, where -the functors of the terms (and eventually the first arguments) work as -secondary keys. - -In the YAP's i.d.b. an optimized representation is used for -terms without free variables. This results in a faster retrieval of terms -and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b. - - -@} */ - -/** @defgroup BlackBoard The Blackboard -@ingroup YAPBuiltins -@{ - -YAP implements a blackboard in the style of the SICStus Prolog -blackboard. The blackboard uses the same underlying mechanism as the -internal data-base but has several important differences: - - + It is module aware, in contrast to the internal data-base. - + Keys can only be atoms or integers, and not compound terms. - + A single term can be stored per key. - + An atomic update operation is provided; this is useful for -parallelism. - - - - -*/ - -/** @pred bb_put(+ _Key_,? _Term_) - - -Store term table _Term_ in the blackboard under key _Key_. If a -previous term was stored under key _Key_ it is simply forgotten. - - -*/ - -/** @pred bb_get(+ _Key_,? _Term_) - - -Unify _Term_ with a term stored in the blackboard under key - _Key_, or fail silently if no such term exists. - - -*/ - -/** @pred bb_delete(+ _Key_,? _Term_) - - -Delete any term stored in the blackboard under key _Key_ and unify -it with _Term_. Fail silently if no such term exists. - - -*/ - -/** @pred bb_update(+ _Key_,? _Term_,? _New_) - - -Atomically unify a term stored in the blackboard under key _Key_ -with _Term_, and if the unification succeeds replace it by - _New_. Fail silently if no such term exists or if unification fails. - - - - -@} */ - -/** @defgroup Sets Collecting Solutions to a Goal -@ingroup YAPBuiltins -@{ - -When there are several solutions to a goal, if the user wants to collect all -the solutions he may be led to use the data base, because backtracking will -forget previous solutions. - -YAP allows the programmer to choose from several system -predicates instead of writing his own routines. findall/3 gives you -the fastest, but crudest solution. The other built-in predicates -post-process the result of the query in several different ways: - - - - -*/ - -/** @pred findall( _T_,+ _G_,- _L_) is iso - - -Unifies _L_ with a list that contains all the instantiations of the -term _T_ satisfying the goal _G_. - -With the following program: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -a(2,1). -a(1,1). -a(2,2). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -the answer to the query - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -findall(X,a(X,Y),L). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -would be: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -X = _32 -Y = _33 -L = [2,1,2]; -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred findall( _T_,+ _G_,+ _L_,- _L0_) - -Similar to findall/3, but appends all answers to list _L0_. - - -*/ - -/** @pred all( _T_,+ _G_,- _L_) - - -Similar to `findall( _T_, _G_, _L_)` but eliminate -repeated elements. Thus, assuming the same clauses as in the above -example, the reply to the query - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -all(X,a(X,Y),L). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -would be: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -X = _32 -Y = _33 -L = [2,1]; -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that all/3 will fail if no answers are found. - - -*/ - -/** @pred bagof( _T_,+ _G_,- _L_) is iso - - -For each set of possible instances of the free variables occurring in - _G_ but not in _T_, generates the list _L_ of the instances of - _T_ satisfying _G_. Again, assuming the same clauses as in the -examples above, the reply to the query - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -bagof(X,a(X,Y),L). - -would be: -X = _32 -Y = 1 -L = [2,1]; -X = _32 -Y = 2 -L = [2]; -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred setof( _X_,+ _P_,- _B_) is iso - - -Similar to `bagof( _T_, _G_, _L_)` but sorts list - _L_ and keeping only one copy of each element. Again, assuming the -same clauses as in the examples above, the reply to the query - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -setof(X,a(X,Y),L). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -would be: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -X = _32 -Y = 1 -L = [1,2]; -X = _32 -Y = 2 -L = [2]; -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup Grammars Grammar Rules -@ingroup YAPBuiltins -@{ - -Grammar rules in Prolog are both a convenient way to express definite -clause grammars and an extension of the well known context-free grammars. - -A grammar rule is of the form: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -head --> body -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -where both \a head and \a body are sequences of one or more items -linked by the standard conjunction operator ','. - -Items can be: - - + -a non-terminal symbol may be either a complex term or an atom. - + -a terminal symbol may be any Prolog symbol. Terminals are -written as Prolog lists. - + -an empty body is written as the empty list '[ ]'. - + -extra conditions may be inserted as Prolog procedure calls, by being -written inside curly brackets '{' and '}'. - + -the left side of a rule consists of a nonterminal and an optional list -of terminals. - + -alternatives may be stated in the right-hand side of the rule by using -the disjunction operator ';'. - + -the cut and conditional symbol ('-\>') may be inserted in the -right hand side of a grammar rule - - -Grammar related built-in predicates: - - - - -*/ - -/** @pred expand_term( _T_,- _X_) - - - -This predicate is used by YAP for preprocessing each top level -term read when consulting a file and before asserting or executing it. -It rewrites a term _T_ to a term _X_ according to the following -rules: first try term_expansion/2 in the current module, and then try to use the user defined predicate -`user:term_expansion/2`. If this call fails then the translating process -for DCG rules is applied, together with the arithmetic optimizer -whenever the compilation of arithmetic expressions is in progress. - - -*/ - -/** @pred _CurrentModule_:term_expansion( _T_,- _X_), user:term_expansion( _T_,- _X_) - - -This user-defined predicate is called by `expand_term/3` to -preprocess all terms read when consulting a file. If it succeeds: - - + -If _X_ is of the form `:- G` or `?- G`, it is processed as -a directive. - + -If _X_ is of the form `'$source_location'( _File_, _Line_): _Clause_` it is processed as if from `File` and line `Line`. - - + -If _X_ is a list, all terms of the list are asserted or processed -as directives. - + The term _X_ is asserted instead of _T_. - - - -*/ - -/** @pred _CurrentModule_:goal_expansion(+ _G_,+ _M_,- _NG_), user:goal_expansion(+ _G_,+ _M_,- _NG_) - - -YAP now supports goal_expansion/3. This is an user-defined -procedure that is called after term expansion when compiling or -asserting goals for each sub-goal in a clause. The first argument is -bound to the goal and the second to the module under which the goal - _G_ will execute. If goal_expansion/3 succeeds the new -sub-goal _NG_ will replace _G_ and will be processed in the same -way. If goal_expansion/3 fails the system will use the default -rules. - - -*/ - -/** @pred phrase(+ _P_, _L_, _R_) - - -This predicate succeeds when the difference list ` _L_- _R_` -is a phrase of type _P_. - - -*/ - -/** @pred phrase(+ _P_, _L_) - -This predicate succeeds when _L_ is a phrase of type _P_. The -same as `phrase(P,L,[])`. - -Both this predicate and the previous are used as a convenient way to -start execution of grammar rules. - - -*/ - -/** @pred 'C'( _S1_, _T_, _S2_) - - -This predicate is used by the grammar rules compiler and is defined as -`'C'([H|T],H,T)`. - - - - -@} */ - -/** @defgroup OS Access to Operating System Functionality -@ingroup YAPBuiltins -@{ - -The following built-in predicates allow access to underlying -Operating System functionality: - - - - -*/ - -/** @pred cd(+ _D_) - - -Changes the current directory (on UNIX environments). - - -*/ - -/** @pred cd - -Changes the current directory (on UNIX environments) to the user's home directory. - - -*/ - -/** @pred environ(+ _E_,- _S_) - - - - - -Given an environment variable _E_ this predicate unifies the second argument _S_ with its value. - - -*/ - -/** @pred getcwd(- _D_) - - -Unify the current directory, represented as an atom, with the argument - _D_. - - -*/ - -/** @pred pwd - - -Prints the current directory. - - -*/ - -/** @pred ls - - -Prints a list of all files in the current directory. - - -*/ - -/** @pred putenv(+ _E_,+ _S_) - - -Set environment variable _E_ to the value _S_. If the -environment variable _E_ does not exist, create a new one. Both the -environment variable and the value must be atoms. - - -*/ - -/** @pred rename(+ _F_,+ _G_) - - -Renames file _F_ to _G_. - - -*/ - -/** @pred sh - - -Creates a new shell interaction. - - -*/ - -/** @pred system(+ _S_) - - -Passes command _S_ to the Bourne shell (on UNIX environments) or the -current command interpreter in WIN32 environments. - - -*/ - -/** @pred unix(+ _S_) - - -Access to Unix-like functionality: - - + argv/1 -Return a list of arguments to the program. These are the arguments that -follow a `--`, as in the usual Unix convention. - + cd/0 -Change to home directory. - + cd/1 -Change to given directory. Acceptable directory names are strings or -atoms. - + environ/2 -If the first argument is an atom, unify the second argument with the -value of the corresponding environment variable. - + getcwd/1 -Unify the first argument with an atom representing the current directory. - + putenv/2 -Set environment variable _E_ to the value _S_. If the -environment variable _E_ does not exist, create a new one. Both the -environment variable and the value must be atoms. - + shell/1 -Execute command under current shell. Acceptable commands are strings or -atoms. - + system/1 -Execute command with `/bin/sh`. Acceptable commands are strings or -atoms. - + shell/0 -Execute a new shell. - - - -*/ - -/** @pred working_directory(- _CurDir_,? _NextDir_) - - -Fetch the current directory at _CurDir_. If _NextDir_ is bound -to an atom, make its value the current working directory. - - -*/ - -/** @pred alarm(+ _Seconds_,+ _Callable_,+ _OldAlarm_) - - -Arranges for YAP to be interrupted in _Seconds_ seconds, or in -[ _Seconds_| _MicroSeconds_]. When interrupted, YAP will execute - _Callable_ and then return to the previous execution. If - _Seconds_ is `0`, no new alarm is scheduled. In any event, -any previously set alarm is canceled. - -The variable _OldAlarm_ unifies with the number of seconds remaining -until any previously scheduled alarm was due to be delivered, or with -`0` if there was no previously scheduled alarm. - -Note that execution of _Callable_ will wait if YAP is -executing built-in predicates, such as Input/Output operations. - -The next example shows how _alarm/3_ can be used to implement a -simple clock: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -loop :- loop. - -ticker :- write('.'), flush_output, - get_value(tick, yes), - alarm(1,ticker,_). - -:- set_value(tick, yes), alarm(1,ticker,_), loop. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The clock, `ticker`, writes a dot and then checks the flag -`tick` to see whether it can continue ticking. If so, it calls -itself again. Note that there is no guarantee that the each dot -corresponds a second: for instance, if the YAP is waiting for -user input, `ticker` will wait until the user types the entry in. - -The next example shows how alarm/3 can be used to guarantee that -a certain procedure does not take longer than a certain amount of time: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -loop :- loop. - -:- catch((alarm(10, throw(ball), _),loop), - ball, - format('Quota exhausted.~n',[])). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In this case after `10` seconds our `loop` is interrupted, -`ball` is thrown, and the handler writes `Quota exhausted`. -Execution then continues from the handler. - -Note that in this case `loop/0` always executes until the alarm is -sent. Often, the code you are executing succeeds or fails before the -alarm is actually delivered. In this case, you probably want to disable -the alarm when you leave the procedure. The next procedure does exactly so: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -once_with_alarm(Time,Goal,DoOnAlarm) :- - catch(execute_once_with_alarm(Time, Goal), alarm, DoOnAlarm). - -execute_once_with_alarm(Time, Goal) :- - alarm(Time, alarm, _), - ( call(Goal) -> alarm(0, alarm, _) ; alarm(0, alarm, _), fail). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The procedure `once_with_alarm/3` has three arguments: -the _Time_ to wait before the alarm is -sent; the _Goal_ to execute; and the goal _DoOnAlarm_ to execute -if the alarm is sent. It uses catch/3 to handle the case the -`alarm` is sent. Then it starts the alarm, calls the goal - _Goal_, and disables the alarm on success or failure. - - -*/ - -/** @pred on_signal(+ _Signal_,? _OldAction_,+ _Callable_) - - -Set the interrupt handler for soft interrupt _Signal_ to be - _Callable_. _OldAction_ is unified with the previous handler. - -Only a subset of the software interrupts (signals) can have their -handlers manipulated through on_signal/3. -Their POSIX names, YAP names and default behavior is given below. -The "YAP name" of the signal is the atom that is associated with -each signal, and should be used as the first argument to -on_signal/3. It is chosen so that it matches the signal's POSIX -name. - -on_signal/3 succeeds, unless when called with an invalid -signal name or one that is not supported on this platform. No checks -are made on the handler provided by the user. - - + sig_up (Hangup) -SIGHUP in Unix/Linux; Reconsult the initialization files -~/.yaprc, ~/.prologrc and ~/prolog.ini. - + sig_usr1 and sig_usr2 (User signals) -SIGUSR1 and SIGUSR2 in Unix/Linux; Print a message and halt. - - -A special case is made, where if _Callable_ is bound to -`default`, then the default handler is restored for that signal. - -A call in the form `on_signal( _S_, _H_, _H_)` can be used -to retrieve a signal's current handler without changing it. - -It must be noted that although a signal can be received at all times, -the handler is not executed while YAP is waiting for a query at the -prompt. The signal will be, however, registered and dealt with as soon -as the user makes a query. - -Please also note, that neither POSIX Operating Systems nor YAP guarantee -that the order of delivery and handling is going to correspond with the -order of dispatch. - - - - -@} */ - -/** @defgroup Term_Modification Term Modification -@ingroup YAPBuiltins -@{ - -It is sometimes useful to change the value of instantiated -variables. Although, this is against the spirit of logic programming, it -is sometimes useful. As in other Prolog systems, YAP has -several primitives that allow updating Prolog terms. Note that these -primitives are also backtrackable. - -The `setarg/3` primitive allows updating any argument of a Prolog -compound terms. The `mutable` family of predicates provides -mutable variables. They should be used instead of `setarg/3`, -as they allow the encapsulation of accesses to updatable -variables. Their implementation can also be more efficient for long -deterministic computations. - - - -*/ - -/** @pred setarg(+ _I_,+ _S_,? _T_) - - -Set the value of the _I_th argument of term _S_ to term _T_. - - -*/ - -/** @pred create_mutable(+ _D_,- _M_) - - -Create new mutable variable _M_ with initial value _D_. - - -*/ - -/** @pred is_mutable(? _D_) - - -Holds if _D_ is a mutable term. - - -*/ - -/** @pred get_mutable(? _D_,+ _M_) - - -Unify the current value of mutable term _M_ with term _D_. - - -*/ - -/** @pred update_mutable(+ _D_,+ _M_) - - -Set the current value of mutable term _M_ to term _D_. - - - -@} */ - -/** @defgroup Global_Variables Global Variables -@ingroup YAPBuiltins -@{ - -Global variables are associations between names (atoms) and -terms. They differ in various ways from storing information using -assert/1 or recorda/3. - - + The value lives on the Prolog (global) stack. This implies that -lookup time is independent from the size of the term. This is -particularly interesting for large data structures such as parsed XML -documents or the CHR global constraint store. - - + They support both global assignment using nb_setval/2 and -backtrackable assignment using b_setval/2. - - + Only one value (which can be an arbitrary complex Prolog term) -can be associated to a variable at a time. - - + Their value cannot be shared among threads. Each thread has its own -namespace and values for global variables. - - -Currently global variables are scoped globally. We may consider module -scoping in future versions. Both b_setval/2 and -nb_setval/2 implicitly create a variable if the referenced name -does not already refer to a variable. - -Global variables may be initialised from directives to make them -available during the program lifetime, but some considerations are -necessary for saved-states and threads. Saved-states to not store -global variables, which implies they have to be declared with -initialization/1 to recreate them after loading the saved -state. Each thread has its own set of global variables, starting with -an empty set. Using `thread_initialization/1` to define a global -variable it will be defined, restored after reloading a saved state -and created in all threads that are created after the -registration. Finally, global variables can be initialised using the -exception hook called exception/3. The latter technique is used -by CHR. - - - -*/ - -/** @pred b_setval(+ _Name_, + _Value_) - - -Associate the term _Value_ with the atom _Name_ or replaces -the currently associated value with _Value_. If _Name_ does -not refer to an existing global variable a variable with initial value -[] is created (the empty list). On backtracking the assignment is -reversed. - - -*/ - -/** @pred b_getval(+ _Name_, - _Value_) - - -Get the value associated with the global variable _Name_ and unify -it with _Value_. Note that this unification may further -instantiate the value of the global variable. If this is undesirable -the normal precautions (double negation or copy_term/2) must be -taken. The b_getval/2 predicate generates errors if _Name_ is not -an atom or the requested variable does not exist. - -Notice that for compatibility with other systems _Name_ must be already associated with a term: otherwise the system will generate an error. - - -*/ - -/** @pred nb_setval(+ _Name_, + _Value_) - - -Associates a copy of _Value_ created with duplicate_term/2 with -the atom _Name_. Note that this can be used to set an initial -value other than `[]` prior to backtrackable assignment. - - -*/ - -/** @pred nb_getval(+ _Name_, - _Value_) - - -The nb_getval/2 predicate is a synonym for b_getval/2, -introduced for compatibility and symmetry. As most scenarios will use -a particular global variable either using non-backtrackable or -backtrackable assignment, using nb_getval/2 can be used to -document that the variable is used non-backtrackable. - - -*/ - -/** @pred nb_linkval(+ _Name_, + _Value_) - - -Associates the term _Value_ with the atom _Name_ without -copying it. This is a fast special-purpose variation of nb_setval/2 -intended for expert users only because the semantics on backtracking -to a point before creating the link are poorly defined for compound -terms. The principal term is always left untouched, but backtracking -behaviour on arguments is undone if the original assignment was -trailed and left alone otherwise, which implies that the history that -created the term affects the behaviour on backtracking. Please -consider the following example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -demo_nb_linkval :- - T = nice(N), - ( N = world, - nb_linkval(myvar, T), - fail - ; nb_getval(myvar, V), - writeln(V) - ). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred nb_set_shared_val(+ _Name_, + _Value_) - - -Associates the term _Value_ with the atom _Name_, but sharing -non-backtrackable terms. This may be useful if you want to rewrite a -global variable so that the new copy will survive backtracking, but -you want to share structure with the previous term. - -The next example shows the differences between the three built-ins: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B). -A = a(_A), -B = t(_B,a(_C)) ? - -?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B). - -?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B). -A = a(_A), -B = t(C,a(_A)) ? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred nb_setarg(+{Arg], + _Term_, + _Value_) - - - -Assigns the _Arg_-th argument of the compound term _Term_ with -the given _Value_ as setarg/3, but on backtracking the assignment -is not reversed. If _Term_ is not atomic, it is duplicated using -duplicate_term/2. This predicate uses the same technique as -nb_setval/2. We therefore refer to the description of -nb_setval/2 for details on non-backtrackable assignment of -terms. This predicate is compatible to GNU-Prolog -`setarg(A,T,V,false)`, removing the type-restriction on - _Value_. See also nb_linkarg/3. Below is an example for -counting the number of solutions of a goal. Note that this -implementation is thread-safe, reentrant and capable of handling -exceptions. Realising these features with a traditional implementation -based on assert/retract or flag/3 is much more complicated. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - succeeds_n_times(Goal, Times) :- - Counter = counter(0), - ( Goal, - arg(1, Counter, N0), - N is N0 + 1, - nb_setarg(1, Counter, N), - fail - ; arg(1, Counter, Times) - ). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred nb_set_shared_arg(+ _Arg_, + _Term_, + _Value_) - - - -As nb_setarg/3, but like nb_linkval/2 it does not -duplicate the global sub-terms in _Value_. Use with extreme care -and consult the documentation of nb_linkval/2 before use. - - -*/ - -/** @pred nb_linkarg(+ _Arg_, + _Term_, + _Value_) - - - -As nb_setarg/3, but like nb_linkval/2 it does not -duplicate _Value_. Use with extreme care and consult the -documentation of nb_linkval/2 before use. - - -*/ - -/** @pred nb_current(? _Name_, ? _Value_) - - -Enumerate all defined variables with their value. The order of -enumeration is undefined. - - -*/ - -/** @pred nb_delete(+ _Name_) - - -Delete the named global variable. - - -Global variables have been introduced by various Prolog -implementations recently. We follow the implementation of them in -SWI-Prolog, itself based on hProlog by Bart Demoen. - -GNU-Prolog provides a rich set of global variables, including -arrays. Arrays can be implemented easily in YAP and SWI-Prolog using -functor/3 and `setarg/3` due to the unrestricted arity of -compound terms. - - -@} */ - -/** @defgroup Profiling Profiling Prolog Programs -@ingroup YAPBuiltins -@{ - -YAP includes two profilers. The count profiler keeps information on the -number of times a predicate was called. This information can be used to -detect what are the most commonly called predicates in the program. The -count profiler can be compiled by setting YAP's flag profiling -to `on`. The time-profiler is a `gprof` profiler, and counts -how many ticks are being spent on specific predicates, or on other -system functions such as internal data-base accesses or garbage collects. - -The YAP profiling sub-system is currently under -development. Functionality for this sub-system will increase with newer -implementation. - - -@} */ - -/** @defgroup The_Count_Profiler The Count Profiler -@ingroup YAPBuiltins -@{ - - *Notes:* - -The count profiler works by incrementing counters at procedure entry or -backtracking. It provides exact information: - - + Profiling works for both static and dynamic predicates. - + Currently only information on entries and retries to a predicate -are maintained. This may change in the future. - + As an example, the following user-level program gives a list of -the most often called procedures in a program. The procedure -`list_profile` shows all procedures, irrespective of module, and -the procedure `list_profile/1` shows the procedures being used in -a specific module. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -list_profile :- - % get number of calls for each profiled procedure - setof(D-[M:P|D1],(current_module(M),profile_data(M:P,calls,D),profile_data(M:P,retries,D1)),LP), - % output so that the most often called - % predicates will come last: - write_profile_data(LP). - -list_profile(Module) :- - % get number of calls for each profiled procedure - setof(D-[Module:P|D1],(profile_data(Module:P,calls,D),profile_data(Module:P,retries,D1)),LP), - % output so that the most often called - % predicates will come last: - write_profile_data(LP). - -write_profile_data([]). -write_profile_data([D-[M:P|R]|SLP]) :- - % swap the two calls if you want the most often - % called predicates first. - format('~a:~w: ~32+~t~d~12+~t~d~12+~n', [M,P,D,R]), - write_profile_data(SLP). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -These are the current predicates to access and clear profiling data: - - - -*/ - -/** @pred profile_data(? _Na/Ar_, ? _Parameter_, - _Data_) - - -Give current profile data on _Parameter_ for a predicate described -by the predicate indicator _Na/Ar_. If any of _Na/Ar_ or - _Parameter_ are unbound, backtrack through all profiled predicates -or stored parameters. Current parameters are: - - + calls -Number of times a procedure was called. - - + retries -Number of times a call to the procedure was backtracked to and retried. - - - + profile_reset - - -Reset all profiling information. - - - - -@} */ - -/** @defgroup Tick_Profiler Tick Profiler -@ingroup YAPBuiltins -@{ - -The tick profiler works by interrupting the Prolog code every so often -and checking at each point the code was. The profiler must be able to -retrace the state of the abstract machine at every moment. The major -advantage of this approach is that it gives the actual amount of time -being spent per procedure, or whether garbage collection dominates -execution time. The major drawback is that tracking down the state of -the abstract machine may take significant time, and in the worst case -may slow down the whole execution. - -The following procedures are available: - - + profinit - - -Initialise the data-structures for the profiler. Unnecessary for -dynamic profiler. - - + profon - - -Start profiling. - - + profoff - - -Stop profiling. - - -*/ - -/** @pred showprofres - - -Show profiling info. - - -*/ - -/** @pred showprofres( _N_) - -Show profiling info for the top-most _N_ predicates. - - - -The showprofres/0 and `showprofres/1` predicates call a user-defined multifile hook predicate, `user:prolog_predicate_name/2`, that can be used for converting a possibly explicitly-qualified callable term into an atom that will used when printing the profiling information. - - -@} */ - -/** @defgroup Call_Counting Counting Calls -@ingroup YAPBuiltins -@{ - -Predicates compiled with YAP's flag call_counting set to -`on` update counters on the numbers of calls and of -retries. Counters are actually decreasing counters, so that they can be -used as timers. Three counters are available: - - + `calls`: number of predicate calls since execution started or since -system was reset; - + `retries`: number of retries for predicates called since -execution started or since counters were reset; - + `calls_and_retries`: count both on predicate calls and -retries. - -These counters can be used to find out how many calls a certain -goal takes to execute. They can also be used as timers. - -The code for the call counters piggybacks on the profiling -code. Therefore, activating the call counters also activates the profiling -counters. - -These are the predicates that access and manipulate the call counters: - - - -*/ - -/** @pred call_count_data(- _Calls_, - _Retries_, - _CallsAndRetries_) - - -Give current call count data. The first argument gives the current value -for the _Calls_ counter, next the _Retries_ counter, and last -the _CallsAndRetries_ counter. - - + call_count_reset - - -Reset call count counters. All timers are also reset. - -
    • dynamic arrays are a different way to access compound terms -created during the execution. Like any other terms, any bindings to -these terms and eventually the terms themselves will be destroyed during -backtracking. Our goal in supporting dynamic arrays is twofold. First, -they provide an alternative to the standard arg/3 -built-in. Second, because dynamic arrays may have name that are globally -visible, a dynamic array can be visible from any point in the -program. In more detail, the clause - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -g(X) :- array_element(a,2,X). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -will succeed as long as the programmer has used the built-in array/2 -to create an array term with at least 3 elements in the current -environment, and the array was associated with the name `a`. The -element `X` is a Prolog term, so one can bind it and any such -bindings will be undone when backtracking. Note that dynamic arrays do -not have a type: each element may be any Prolog term. - -The static arrays are an extension of the database. They provide -a compact way for manipulating data-structures formed by characters, -integers, or floats imperatively. They can also be used to provide -two-way communication between YAP and external programs through -shared memory. - -In order to efficiently manage space elements in a static array must -have a type. Currently, elements of static arrays in YAP should -have one of the following predefined types: - - + `byte`: an 8-bit signed character. - + `unsigned_byte`: an 8-bit unsigned character. - + `int`: Prolog integers. Size would be the natural size for -the machine's architecture. - + `float`: Prolog floating point number. Size would be equivalent -to a double in `C`. - + `atom`: a Prolog atom. - + `dbref`: an internal database reference. - + `term`: a generic Prolog term. Note that this will term will -not be stored in the array itself, but instead will be stored in the -Prolog internal database. - - -Arrays may be named or anonymous. Most arrays will be -named, that is associated with an atom that will be used to find -the array. Anonymous arrays do not have a name, and they are only of -interest if the `TERM_EXTENSIONS` compilation flag is enabled. In -this case, the unification and parser are extended to replace -occurrences of Prolog terms of the form `X[I]` by run-time calls to -array_element/3, so that one can use array references instead of -extra calls to arg/3. As an example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I]. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -should give the same results as: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -G(X,Y,Z,I,J) :- - array_element(X,I,E1), - array_element(Y,J,E2), - array_element(Z,I,E3), - E1 is E2+E3. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that the only limitation on array size are the stack size for -dynamic arrays; and, the heap size for static (not memory mapped) -arrays. Memory mapped arrays are limited by available space in the file -system and in the virtual memory space. - -The following predicates manipulate arrays: - - - - -*/ - -/** @pred array(+ _Name_, + _Size_) - - -Creates a new dynamic array. The _Size_ must evaluate to an -integer. The _Name_ may be either an atom (named array) or an -unbound variable (anonymous array). - -Dynamic arrays work as standard compound terms, hence space for the -array is recovered automatically on backtracking. - - -*/ - -/** @pred static_array(+ _Name_, + _Size_, + _Type_) - - -Create a new static array with name _Name_. Note that the _Name_ -must be an atom (named array). The _Size_ must evaluate to an -integer. The _Type_ must be bound to one of types mentioned -previously. - - -*/ - -/** @pred reset_static_array(+ _Name_) - - -Reset static array with name _Name_ to its initial value. - - -*/ - -/** @pred static_array_location(+ _Name_, - _Ptr_) - - -Give the location for a static array with name - _Name_. - - -*/ - -/** @pred static_array_properties(? _Name_, ? _Size_, ? _Type_) - - -Show the properties size and type of a static array with name - _Name_. Can also be used to enumerate all current -static arrays. - -This built-in will silently fail if the there is no static array with -that name. - - -*/ - -/** @pred static_array_to_term(? _Name_, ? _Term_) - - -Convert a static array with name - _Name_ to a compound term of name _Name_. - -This built-in will silently fail if the there is no static array with -that name. - - -*/ - -/** @pred mmapped_array(+ _Name_, + _Size_, + _Type_, + _File_) - - -Similar to static_array/3, but the array is memory mapped to file - _File_. This means that the array is initialized from the file, and -that any changes to the array will also be stored in the file. - -This built-in is only available in operating systems that support the -system call `mmap`. Moreover, mmapped arrays do not store generic -terms (type `term`). - - -*/ - -/** @pred close_static_array(+ _Name_) - - -Close an existing static array of name _Name_. The _Name_ must -be an atom (named array). Space for the array will be recovered and -further accesses to the array will return an error. - - -*/ - -/** @pred resize_static_array(+ _Name_, - _OldSize_, + _NewSize_) - - -Expand or reduce a static array, The _Size_ must evaluate to an -integer. The _Name_ must be an atom (named array). The _Type_ -must be bound to one of `int`, `dbref`, `float` or -`atom`. - -Note that if the array is a mmapped array the size of the mmapped file -will be actually adjusted to correspond to the size of the array. - - -*/ - -/** @pred array_element(+ _Name_, + _Index_, ? _Element_) - - -Unify _Element_ with _Name_[ _Index_]. It works for both -static and dynamic arrays, but it is read-only for static arrays, while -it can be used to unify with an element of a dynamic array. - - -*/ - -/** @pred update_array(+ _Name_, + _Index_, ? _Value_) - - -Attribute value _Value_ to _Name_[ _Index_]. Type -restrictions must be respected for static arrays. This operation is -available for dynamic arrays if `MULTI_ASSIGNMENT_VARIABLES` is -enabled (true by default). Backtracking undoes _update_array/3_ for -dynamic arrays, but not for static arrays. - -Note that update_array/3 actually uses `setarg/3` to update -elements of dynamic arrays, and `setarg/3` spends an extra cell for -every update. For intensive operations we suggest it may be less -expensive to unify each element of the array with a mutable terms and -to use the operations on mutable terms. - - -*/ - -/** @pred add_to_array_element(+ _Name_, + _Index_, , + _Number_, ? _NewValue_) - - -Add _Number_ _Name_[ _Index_] and unify _NewValue_ with -the incremented value. Observe that _Name_[ _Index_] must be an -number. If _Name_ is a static array the type of the array must be -`int` or `float`. If the type of the array is `int` you -only may add integers, if it is `float` you may add integers or -floats. If _Name_ corresponds to a dynamic array the array element -must have been previously bound to a number and `Number` can be -any kind of number. - -The `add_to_array_element/3` built-in actually uses -`setarg/3` to update elements of dynamic arrays. For intensive -operations we suggest it may be less expensive to unify each element -of the array with a mutable terms and to use the operations on mutable -terms. - - - - -@} */ - -/** @defgroup Preds Predicate Information -@ingroup YAPBuiltins -@{ - -Built-ins that return information on the current predicates and modules: - - - - -*/ - -/** @pred current_module( _M_) - - -Succeeds if _M_ are defined modules. A module is defined as soon as some -predicate defined in the module is loaded, as soon as a goal in the -module is called, or as soon as it becomes the current type-in module. - - -*/ - -/** @pred current_module( _M_, _F_) - -Succeeds if _M_ are current modules associated to the file _F_. - - - - -@} */ - -/** @defgroup Misc Miscellaneous -@ingroup YAPBuiltins -@{ - - - - -*/ - -/** @pred statistics/0 - - -Send to the current user error stream general information on space used and time -spent by the system. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- statistics. -memory (total) 4784124 bytes - program space 3055616 bytes: 1392224 in use, 1663392 free - 2228132 max - stack space 1531904 bytes: 464 in use, 1531440 free - global stack: 96 in use, 616684 max - local stack: 368 in use, 546208 max - trail stack 196604 bytes: 8 in use, 196596 free - - 0.010 sec. for 5 code, 2 stack, and 1 trail space overflows - 0.130 sec. for 3 garbage collections which collected 421000 bytes - 0.000 sec. for 0 atom garbage collections which collected 0 bytes - 0.880 sec. runtime - 1.020 sec. cputime - 25.055 sec. elapsed time - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The example shows how much memory the system spends. Memory is divided -into Program Space, Stack Space and Trail. In the example we have 3MB -allocated for program spaces, with less than half being actually -used. YAP also shows the maximum amount of heap space having been used -which was over 2MB. - -The stack space is divided into two stacks which grow against each -other. We are in the top level so very little stack is being used. On -the other hand, the system did use a lot of global and local stack -during the previous execution (we refer the reader to a WAM tutorial in -order to understand what are the global and local stacks). - -YAP also shows information on how many memory overflows and garbage -collections the system executed, and statistics on total execution -time. Cputime includes all running time, runtime excludes garbage -collection and stack overflow time. - - -*/ - -/** @pred statistics(? _Param_,- _Info_) - -Gives statistical information on the system parameter given by first -argument: - - - - + atoms - -`[ _NumberOfAtoms_, _SpaceUsedBy Atoms_]` - - -This gives the total number of atoms `NumberOfAtoms` and how much -space they require in bytes, _SpaceUsedBy Atoms_. - - + cputime - -`[ _Time since Boot_, _Time From Last Call to Cputime_]` - - -This gives the total cputime in milliseconds spent executing Prolog code, -garbage collection and stack shifts time included. - - + dynamic_code - -`[ _Clause Size_, _Index Size_, _Tree Index Size_, _Choice Point Instructions Size_, _Expansion Nodes Size_, _Index Switch Size_]` - - -Size of static code in YAP in bytes: _Clause Size_, the number of -bytes allocated for clauses, plus - _Index Size_, the number of bytes spent in the indexing code. The -indexing code is divided into main tree, _Tree Index Size_, -tables that implement choice-point manipulation, _Choice xsPoint Instructions Size_, tables that cache clauses for future expansion of the index -tree, _Expansion Nodes Size_, and -tables such as hash tables that select according to value, _Index Switch Size_. - - + garbage_collection - -`[ _Number of GCs_, _Total Global Recovered_, _Total Time Spent_]` - - -Number of garbage collections, amount of space recovered in kbytes, and -total time spent doing garbage collection in milliseconds. More detailed -information is available using `yap_flag(gc_trace,verbose)`. - - + global_stack - -`[ _Global Stack Used_, _Execution Stack Free_]` - - -Space in kbytes currently used in the global stack, and space available for -expansion by the local and global stacks. - - + local_stack - -`[ _Local Stack Used_, _Execution Stack Free_]` - - -Space in kbytes currently used in the local stack, and space available for -expansion by the local and global stacks. - - + heap - -`[ _Heap Used_, _Heap Free_]` - - -Total space in kbytes not recoverable -in backtracking. It includes the program code, internal data base, and, -atom symbol table. - - + program - -`[ _Program Space Used_, _Program Space Free_]` - - -Equivalent to heap. - - + runtime - -`[ _Time since Boot_, _Time From Last Call to Runtime_]` - - -This gives the total cputime in milliseconds spent executing Prolog -code, not including garbage collections and stack shifts. Note that -until YAP4.1.2 the runtime statistics would return time spent on -garbage collection and stack shifting. - - + stack_shifts - -`[ _Number of Heap Shifts_, _Number of Stack Shifts_, _Number of Trail Shifts_]` - - -Number of times YAP had to -expand the heap, the stacks, or the trail. More detailed information is -available using `yap_flag(gc_trace,verbose)`. - - + static_code - -`[ _Clause Size_, _Index Size_, _Tree Index Size_, _Expansion Nodes Size_, _Index Switch Size_]` - - -Size of static code in YAP in bytes: _Clause Size_, the number of -bytes allocated for clauses, plus - _Index Size_, the number of bytes spent in the indexing code. The -indexing code is divided into a main tree, _Tree Index Size_, table that cache clauses for future expansion of the index -tree, _Expansion Nodes Size_, and and -tables such as hash tables that select according to value, _Index Switch Size_. - - + trail - -`[ _Trail Used_, _Trail Free_]` - - -Space in kbytes currently being used and still available for the trail. - - + walltime - -`[ _Time since Boot_, _Time From Last Call to Walltime_]` - - -This gives the clock time in milliseconds since starting Prolog. - - - - -*/ - -/** @pred time(: _Goal_) - - -Prints the CPU time and the wall time for the execution of _Goal_. -Possible choice-points of _Goal_ are removed. Based on the SWI-Prolog -definition (minus reporting the number of inferences, which YAP currently -does not support). - - -*/ - -/** @pred yap_flag(? _Param_,? _Value_) - - -Set or read system properties for _Param_: - - - - + argv - - -Read-only flag. It unifies with a list of atoms that gives the -arguments to YAP after `--`. - - + agc_margin - -An integer: if this amount of atoms has been created since the last -atom-garbage collection, perform atom garbage collection at the first -opportunity. Initial value is 10,000. May be changed. A value of 0 -(zero) disables atom garbage collection. - - + associate - - - -Read-write flag telling a suffix for files associated to Prolog -sources. It is `yap` by default. - - + bounded is iso - - - -Read-only flag telling whether integers are bounded. The value depends -on whether YAP uses the GMP library or not. - - + profiling - - - -If `off` (default) do not compile call counting information for -procedures. If `on` compile predicates so that they calls and -retries to the predicate may be counted. Profiling data can be read through the -call_count_data/3 built-in. - - + char_conversion is iso - - -Writable flag telling whether a character conversion table is used when -reading terms. The default value for this flag is `off` except in -`sicstus` and `iso` language modes, where it is `on`. - - + character_escapes is iso - - -Writable flag telling whether a character escapes are enables, -`true`, or disabled, `false`. The default value for this flag is -`on`. - - + debug is iso - - - -If _Value_ is unbound, tell whether debugging is `true` or -`false`. If _Value_ is bound to `true` enable debugging, and if -it is bound to `false` disable debugging. - - + debugger_print_options - - - -If bound, set the argument to the `write_term/3` options the -debugger uses to write terms. If unbound, show the current options. - - + dialect - - - -Read-only flag that always returns `yap`. - - + discontiguous_warnings - - - -If _Value_ is unbound, tell whether warnings for discontiguous -predicates are `on` or -`off`. If _Value_ is bound to `on` enable these warnings, -and if it is bound to `off` disable them. The default for YAP is -`off`, unless we are in `sicstus` or `iso` mode. - - + dollar_as_lower_case - - - -If `off` (default) consider the character '$' a control character, if -`on` consider '$' a lower case character. - - + double_quotes is iso - - - -If _Value_ is unbound, tell whether a double quoted list of characters -token is converted to a list of atoms, `chars`, to a list of integers, -`codes`, or to a single atom, `atom`. If _Value_ is bound, set to -the corresponding behavior. The default value is `codes`. - - + executable - - -Read-only flag. It unifies with an atom that gives the -original program path. - - + fast - - - -If `on` allow fast machine code, if `off` (default) disable it. Only -available in experimental implementations. - - + fileerrors - - -If `on` `fileerrors` is `on`, if `off` (default) -`fileerrors` is disabled. - - + float_format - - -C-library `printf()` format specification used by write/1 and -friends to determine how floating point numbers are printed. The -default is `%.15g`. The specified value is passed to `printf()` -without further checking. For example, if you want less digits -printed, `%g` will print all floats using 6 digits instead of the -default 15. - - + gc - - -If `on` allow garbage collection (default), if `off` disable it. - - + gc_margin - - - -Set or show the minimum free stack before starting garbage -collection. The default depends on total stack size. - - + gc_trace - - -If `off` (default) do not show information on garbage collection -and stack shifts, if `on` inform when a garbage collection or stack -shift happened, if verbose give detailed information on garbage -collection and stack shifts. Last, if `very_verbose` give detailed -information on data-structures found during the garbage collection -process, namely, on choice-points. - - + generate_debugging_info - - -If `true` (default) generate debugging information for -procedures, including source mode. If `false` predicates no -information is generated, although debugging is still possible, and -source mode is disabled. - - + host_type - - -Return `configure` system information, including the machine-id -for which YAP was compiled and Operating System information. - - + index - - -If `on` allow indexing (default), if `off` disable it, if -`single` allow on first argument only. - - + index_sub_term_search_depth - - - -Maximum bound on searching sub-terms for indexing, if `0` (default) no bound. - - + informational_messages - - - -If `on` allow printing of informational messages, such as the ones -that are printed when consulting. If `off` disable printing -these messages. It is `on` by default except if YAP is booted with -the `-L` flag. - - + integer_rounding_function is iso - - - -Read-only flag telling the rounding function used for integers. Takes the value -`toward_zero` for the current version of YAP. - - + language - - - -Choose whether YAP is closer to C-Prolog, `cprolog`, iso-prolog, -`iso` or SICStus Prolog, `sicstus`. The current default is -`cprolog`. This flag affects update semantics, leashing mode, -style checking, handling calls to undefined procedures, how directives -are interpreted, when to use dynamic, character escapes, and how files -are consulted. - - + max_arity is iso - - - -Read-only flag telling the maximum arity of a functor. Takes the value -`unbounded` for the current version of YAP. - - + max_integer is iso - - - -Read-only flag telling the maximum integer in the -implementation. Depends on machine and Operating System -architecture, and on whether YAP uses the `GMP` multi-precision -library. If bounded is false, requests for max_integer -will fail. - - + max_tagged_integer - - - -Read-only flag telling the maximum integer we can store as a single -word. Depends on machine and Operating System -architecture. It can be used to find the word size of the current machine. - - + min_integer is iso - - -Read-only flag telling the minimum integer in the -implementation. Depends on machine and Operating System architecture, -and on whether YAP uses the `GMP` multi-precision library. If -bounded is false, requests for min_integer will fail. - - + min_tagged_integer - - - -Read-only flag telling the minimum integer we can store as a single -word. Depends on machine and Operating System -architecture. - - + n_of_integer_keys_in_bb - - - -Read or set the size of the hash table that is used for looking up the -blackboard when the key is an integer. - - + occurs_check - - - -Current read-only and set to `false`. - - + n_of_integer_keys_in_db - - - -Read or set the size of the hash table that is used for looking up the -internal data-base when the key is an integer. - - + open_expands_filename - - - -If `true` the open/3 builtin performs filename-expansion -before opening a file (SICStus Prolog like). If `false` it does not -(SWI-Prolog like). - - + open_shared_object - - - -If true, `open_shared_object/2` and friends are implemented, -providing access to shared libraries (`.so` files) or to dynamic link -libraries (`.DLL` files). - - + profiling - - - -If `off` (default) do not compile profiling information for -procedures. If `on` compile predicates so that they will output -profiling information. Profiling data can be read through the -profile_data/3 built-in. - - + prompt_alternatives_on(atom, changeable) - -SWI-Compatible option, determines prompting for alternatives in the Prolog toplevel. Default is groundness, YAP prompts for alternatives if and only if the query contains variables. The alternative, default in SWI-Prolog is determinism which implies the system prompts for alternatives if the goal succeeded while leaving choicepoints. - - + redefine_warnings - - - -If _Value_ is unbound, tell whether warnings for procedures defined -in several different files are `on` or -`off`. If _Value_ is bound to `on` enable these warnings, -and if it is bound to `off` disable them. The default for YAP is -`off`, unless we are in `sicstus` or `iso` mode. - - + shared_object_search_path - -Name of the environment variable used by the system to search for shared -objects. - - + shared_object_extension - -Suffix associated with loadable code. - - + single_var_warnings - - - -If _Value_ is unbound, tell whether warnings for singleton variables -are `on` or `off`. If _Value_ is bound to `on` enable -these warnings, and if it is bound to `off` disable them. The -default for YAP is `off`, unless we are in `sicstus` or -`iso` mode. - - + strict_iso - - - -If _Value_ is unbound, tell whether strict ISO compatibility mode -is `on` or `off`. If _Value_ is bound to `on` set -language mode to `iso` and enable strict mode. If _Value_ is -bound to `off` disable strict mode, and keep the current language -mode. The default for YAP is `off`. - -Under strict ISO Prolog mode all calls to non-ISO built-ins generate an -error. Compilation of clauses that would call non-ISO built-ins will -also generate errors. Pre-processing for grammar rules is also -disabled. Module expansion is still performed. - -Arguably, ISO Prolog does not provide all the functionality required -from a modern Prolog system. Moreover, because most Prolog -implementations do not fully implement the standard and because the -standard itself gives the implementor latitude in a few important -questions, such as the unification algorithm and maximum size for -numbers there is no guarantee that programs compliant with this mode -will work the same way in every Prolog and in every platform. We thus -believe this mode is mostly useful when investigating how a program -depends on a Prolog's platform specific features. - - + stack_dump_on_error - - - -If `on` show a stack dump when YAP finds an error. The default is -`off`. - - + syntax_errors - - -Control action to be taken after syntax errors while executing read/1, -`read/2`, or `read_term/3`: - - - - + dec10 - - -Report the syntax error and retry reading the term. - - + fail - - -Report the syntax error and fail (default). - - + error - - -Report the syntax error and generate an error. - - + quiet - - -Just fail - - - + system_options - - -This read only flag tells which options were used to compile -YAP. Currently it informs whether the system supports `big_numbers`, -`coroutining`, `depth_limit`, `low_level_tracer`, -`or-parallelism`, `rational_trees`, `readline`, `tabling`, -`threads`, or the `wam_profiler`. - - + tabling_mode - -Sets or reads the tabling mode for all tabled predicates. Please - (see Tabling) for the list of options. - - + to_chars_mode - - -Define whether YAP should follow `quintus`-like -semantics for the `atom_chars/1` or `number_chars/1` built-in, -or whether it should follow the ISO standard (`iso` option). - - + toplevel_hook - - - -+If bound, set the argument to a goal to be executed before entering the -top-level. If unbound show the current goal or `true` if none is -presented. Only the first solution is considered and the goal is not -backtracked into. - - + toplevel_print_options - - - -+If bound, set the argument to the `write_term/3` options used to write -terms from the top-level. If unbound, show the current options. - - + typein_module - - - -If bound, set the current working or type-in module to the argument, -which must be an atom. If unbound, unify the argument with the current -working module. - - + unix - -Read-only Boolean flag that unifies with `true` if YAP is -running on an Unix system. Defined if the C-compiler used to compile -this version of YAP either defines `__unix__` or `unix`. - - + unknown is iso - - -Corresponds to calling the unknown/2 built-in. Possible values -are `error`, `fail`, and `warning`. - - + update_semantics - - - -Define whether YAP should follow `immediate` update -semantics, as in C-Prolog (default), `logical` update semantics, -as in Quintus Prolog, SICStus Prolog, or in the ISO standard. There is -also an intermediate mode, `logical_assert`, where dynamic -procedures follow logical semantics but the internal data base still -follows immediate semantics. - - + user_error - - - -If the second argument is bound to a stream, set user_error to -this stream. If the second argument is unbound, unify the argument with -the current user_error stream. - -By default, the user_error stream is set to a stream -corresponding to the Unix `stderr` stream. - -The next example shows how to use this flag: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- open( '/dev/null', append, Error, - [alias(mauri_tripa)] ). - -Error = '$stream'(3) ? ; - -no - ?- set_prolog_flag(user_error, mauri_tripa). - -close(mauri_tripa). - -yes - ?- -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -We execute three commands. First, we open a stream in write mode and -give it an alias, in this case `mauri_tripa`. Next, we set -user_error to the stream via the alias. Note that after we did so -prompts from the system were redirected to the stream -`mauri_tripa`. Last, we close the stream. At this point, YAP -automatically redirects the user_error alias to the original -`stderr`. - - + user_flags - - - -Define the behaviour of set_prolog_flag/2 if the flag is not known. Values are `silent`, `warning` and `error`. The first two create the flag on-the-fly, with `warning` printing a message. The value `error` is consistent with ISO: it raises an existence error and does not create the flag. See also `create_prolog_flag/3`. The default is`error`, and developers are encouraged to use `create_prolog_flag/3` to create flags for their library. - - + user_input - - - -If the second argument is bound to a stream, set user_input to -this stream. If the second argument is unbound, unify the argument with -the current user_input stream. - -By default, the user_input stream is set to a stream -corresponding to the Unix `stdin` stream. - - + user_output - - - -If the second argument is bound to a stream, set user_output to -this stream. If the second argument is unbound, unify the argument with -the current user_output stream. - -By default, the user_output stream is set to a stream -corresponding to the Unix `stdout` stream. - - + verbose - - - -If `normal` allow printing of informational and banner messages, -such as the ones that are printed when consulting. If `silent` -disable printing these messages. It is `normal` by default except if -YAP is booted with the `-q` or `-L` flag. - - + verbose_load - - -If `true` allow printing of informational messages when -consulting files. If `false` disable printing these messages. It -is `normal` by default except if YAP is booted with the `-L` -flag. - - + version - - -Read-only flag that returns an atom with the current version of -YAP. - - + version_data - - -Read-only flag that reads a term of the form -`yap`( _Major_, _Minor_, _Patch_, _Undefined_), where - _Major_ is the major version, _Minor_ is the minor version, -and _Patch_ is the patch number. - - + windows - - - -Read-only boolean flag that unifies with tr `true` if YAP is -running on an Windows machine. - - + write_strings - - -Writable flag telling whether the system should write lists of -integers that are writable character codes using the list notation. It -is `on` if enables or `off` if disabled. The default value for -this flag is `off`. - - + max_workers - - -Read-only flag telling the maximum number of parallel processes. - - + max_threads - - -Read-only flag telling the maximum number of Prolog threads that can -be created. - - - - -*/ - -/** @pred current_prolog_flag(? _Flag_,- _Value_) is iso - - - -Obtain the value for a YAP Prolog flag. Equivalent to calling -yap_flag/2 with the second argument unbound, and unifying the -returned second argument with _Value_. - - -*/ - -/** @pred prolog_flag(? _Flag_,- _OldValue_,+ _NewValue_) - - - -Obtain the value for a YAP Prolog flag and then set it to a new -value. Equivalent to first calling current_prolog_flag/2 with the -second argument _OldValue_ unbound and then calling -set_prolog_flag/2 with the third argument _NewValue_. - - -*/ - -/** @pred set_prolog_flag(+ _Flag_,+ _Value_) is iso - - - -Set the value for YAP Prolog flag `Flag`. Equivalent to -calling yap_flag/2 with both arguments bound. - - -*/ - -/** @pred create_prolog_flag(+ _Flag_,+ _Value_,+ _Options_) - - - -Create a new YAP Prolog flag. _Options_ include `type(+Type)` and `access(+Access)` with _Access_ -one of `read_only` or `read_write` and _Type_ one of `boolean`, `integer`, `float`, `atom` -and `term` (that is, no type). - - -*/ - -/** @pred op(+ _P_,+ _T_,+ _A_) is iso - - -Defines the operator _A_ or the list of operators _A_ with type - _T_ (which must be one of `xfx`, `xfy`,`yfx`, -`xf`, `yf`, `fx` or `fy`) and precedence _P_ -(see appendix iv for a list of predefined operators). - -Note that if there is a preexisting operator with the same name and -type, this operator will be discarded. Also, `','` may not be defined -as an operator, and it is not allowed to have the same for an infix and -a postfix operator. - - -*/ - -/** @pred current_op( _P_, _T_, _F_) is iso - - -Defines the relation: _P_ is a currently defined operator of type - _T_ and precedence _P_. - - -*/ - -/** @pred prompt(- _A_,+ _B_) - - -Changes YAP input prompt from _A_ to _B_. - - -*/ - -/** @pred initialization - -Execute the goals defined by initialization/1. Only the first answer is -considered. - - -*/ - -/** @pred prolog_initialization( _G_) - - -Add a goal to be executed on system initialization. This is compatible -with SICStus Prolog's initialization/1. - - -*/ - -/** @pred version - -Write YAP's boot message. - - -*/ - -/** @pred version(- _Message_) - -Add a message to be written when yap boots or after aborting. It is not -possible to remove messages. - - -*/ - -/** @pred prolog_load_context(? _Key_, ? _Value_) - - -Obtain information on what is going on in the compilation process. The -following keys are available: - - - - + directory - - - -Full name for the directory where YAP is currently consulting the -file. - - + file - - - -Full name for the file currently being consulted. Notice that included -filed are ignored. - - + module - - - -Current source module. - - + source (prolog_load_context/2 option) - - - -Full name for the file currently being read in, which may be consulted, -reconsulted, or included. - - + stream - - - -Stream currently being read in. - - + term_position - - - -Stream position at the stream currently being read in. For SWI -compatibility, it is a term of the form -`'$stream_position'(0,Line,0,0,0)`. - - - + source_location(? _FileName_, ? _Line_) - - -SWI-compatible predicate. If the last term has been read from a physical file (i.e., not from the file user or a string), unify File with an absolute path to the file and Line with the line-number in the file. Please use prolog_load_context/2. - - + source_file(? _File_) - - -SWI-compatible predicate. True if _File_ is a loaded Prolog source file. - - + source_file(? _ModuleAndPred_,? _File_) - -SWI-compatible predicate. True if the predicate specified by _ModuleAndPred_ was loaded from file _File_, where _File_ is an absolute path name (see `absolute_file_name/2`). - - - -@section YAPLibrary Library Predicates - -Library files reside in the library_directory path (set by the -`LIBDIR` variable in the Makefile for YAP). Currently, -most files in the library are from the Edinburgh Prolog library. - - -@} */ - -/** @defgroup Aggregate Aggregate -@ingroup YAPLibrary -@{ - -This is the SWI-Prolog library based on the Quintus and SICStus 4 -library. @c To be done - Analysing the aggregation template. - - -This library provides aggregating operators over the solutions of a -predicate. The operations are a generalisation of the bagof/3, -setof/3 and findall/3 built-in predicates. The defined -aggregation operations are counting, computing the sum, minimum, -maximum, a bag of solutions and a set of solutions. We first give a -simple example, computing the country with the smallest area: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -smallest_country(Name, Area) :- - aggregate(min(A, N), country(N, A), min(Area, Name)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -There are four aggregation predicates, distinguished on two properties. - - - - @pred aggregate vs. aggregate_all -The aggregate predicates use setof/3 (aggregate/4) or bagof/3 -(aggregate/3), dealing with existential qualified variables -( _Var_/\\ _Goal_) and providing multiple solutions for the -remaining free variables in _Goal_. The aggregate_all/3 -predicate uses findall/3, implicitly qualifying all free variables -and providing exactly one solution, while aggregate_all/4 uses -sort/2 over solutions and Distinguish (see below) generated using -findall/3. - + The _Distinguish_ argument -The versions with 4 arguments provide a _Distinguish_ argument -that allow for keeping duplicate bindings of a variable in the -result. For example, if we wish to compute the total population of -all countries we do not want to lose results because two countries -have the same population. Therefore we use: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - aggregate(sum(P), Name, country(Name, P), Total) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - -All aggregation predicates support the following operator below in - _Template_. In addition, they allow for an arbitrary named compound -term where each of the arguments is a term from the list below. I.e. the -term `r(min(X), max(X))` computes both the minimum and maximum -binding for _X_. - - - - @pred count -Count number of solutions. Same as `sum(1)`. - + sum( _Expr_) -Sum of _Expr_ for all solutions. - + min( _Expr_) -Minimum of _Expr_ for all solutions. - + min( _Expr_, _Witness_) -A term min( _Min_, _Witness_), where _Min_ is the minimal version of _Expr_ -over all Solution and _Witness_ is any other template applied to -Solution that produced _Min_. If multiple solutions provide the same -minimum, _Witness_ corresponds to the first solution. - + max( _Expr_) -Maximum of _Expr_ for all solutions. - + max( _Expr_, _Witness_) -As min( _Expr_, _Witness_), but producing the maximum result. - + set( _X_) -An ordered set with all solutions for _X_. - + bag( _X_) -A list of all solutions for _X_. - - -The predicates are: - - - - @pred [nondet]aggregate(+ _Template_, : _Goal_, - _Result_) - - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate/3 version performs bagof/3 on _Goal_. - -*/ - -/** @pred [nondet]aggregate(+ _Template_, + _Discriminator_, : _Goal_, - _Result_) - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate/3 version performs setof/3 on _Goal_. - -*/ - -/** @pred [semidet]aggregate_all(+ _Template_, : _Goal_, - _Result_) - - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate_all/3 version performs findall/3 on _Goal_. - -*/ - -/** @pred [semidet]aggregate_all(+ _Template_, + _Discriminator_, : _Goal_, - _Result_) - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate_all/3 version performs findall/3 followed by sort/2 on - _Goal_. - -*/ - -/** @pred foreach(:Generator, : _Goal_) - - -True if the conjunction of instances of _Goal_ using the -bindings from Generator is true. Unlike forall/2, which runs a -failure-driven loop that proves _Goal_ for each solution of -Generator, foreach creates a conjunction. Each member of the -conjunction is a copy of _Goal_, where the variables it shares -with Generator are filled with the values from the corresponding -solution. - -The implementation executes forall/2 if _Goal_ does not contain -any variables that are not shared with Generator. - -Here is an example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - ?- foreach(between(1,4,X), dif(X,Y)), Y = 5. - Y = 5 - ?- foreach(between(1,4,X), dif(X,Y)), Y = 3. - No -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Notice that _Goal_ is copied repeatedly, which may cause -problems if attributed variables are involved. - - -*/ - -/** @pred [det]free_variables(:Generator, + _Template_, +VarList0, -VarList) - - -In order to handle variables properly, we have to find all the universally quantified variables in the Generator. All variables as yet unbound are universally quantified, unless - -
        - + they occur in the template - + they are bound by X/\\P, setof, or bagof -
      - -`free_variables(Generator, Template, OldList, NewList)` finds this set, using OldList as an accumulator. - - -The original author of this code was Richard O'Keefe. Jan Wielemaker -made some SWI-Prolog enhancements, sponsored by SecuritEase, -http://www.securitease.com. The code is public domain (from DEC10 library). - - - - - -@} */ - -/** @defgroup Apply Apply Macros -@ingroup YAPLibrary -@{ - -This library provides a SWI-compatible set of utilities for applying a -predicate to all elements of a list. The library just forwards -definitions from the `maplist` library. - - -@} */ - -/** @defgroup Association_Lists Association Lists -@ingroup YAPLibrary -@{ - -The following association list manipulation predicates are available -once included with the `use_module(library(assoc))` command. The -original library used Richard O'Keefe's implementation, on top of -unbalanced binary trees. The current code utilises code from the -red-black trees library and emulates the SICStus Prolog interface. - - -*/ - -/** @pred assoc_to_list(+ _Assoc_,? _List_) - - -Given an association list _Assoc_ unify _List_ with a list of -the form _Key-Val_, where the elements _Key_ are in ascending -order. - - -*/ - -/** @pred del_assoc(+ _Key_, + _Assoc_, ? _Val_, ? _NewAssoc_) - - -Succeeds if _NewAssoc_ is an association list, obtained by removing -the element with _Key_ and _Val_ from the list _Assoc_. - - -*/ - -/** @pred del_max_assoc(+ _Assoc_, ? _Key_, ? _Val_, ? _NewAssoc_) - - -Succeeds if _NewAssoc_ is an association list, obtained by removing -the largest element of the list, with _Key_ and _Val_ from the -list _Assoc_. - - -*/ - -/** @pred del_min_assoc(+ _Assoc_, ? _Key_, ? _Val_, ? _NewAssoc_) - - -Succeeds if _NewAssoc_ is an association list, obtained by removing -the smallest element of the list, with _Key_ and _Val_ -from the list _Assoc_. - - -*/ - -/** @pred empty_assoc(+ _Assoc_) - - -Succeeds if association list _Assoc_ is empty. - - -*/ - -/** @pred gen_assoc(+ _Assoc_,? _Key_,? _Value_) - - -Given the association list _Assoc_, unify _Key_ and _Value_ -with two associated elements. It can be used to enumerate all elements -in the association list. - - -*/ - -/** @pred get_assoc(+ _Key_,+ _Assoc_,? _Value_) - - -If _Key_ is one of the elements in the association list _Assoc_, -return the associated value. - - -*/ - -/** @pred get_assoc(+ _Key_,+ _Assoc_,? _Value_,+ _NAssoc_,? _NValue_) - - -If _Key_ is one of the elements in the association list _Assoc_, -return the associated value _Value_ and a new association list - _NAssoc_ where _Key_ is associated with _NValue_. - - -*/ - -/** @pred get_prev_assoc(+ _Key_,+ _Assoc_,? _Next_,? _Value_) - - -If _Key_ is one of the elements in the association list _Assoc_, -return the previous key, _Next_, and its value, _Value_. - - -*/ - -/** @pred get_next_assoc(+ _Key_,+ _Assoc_,? _Next_,? _Value_) - -If _Key_ is one of the elements in the association list _Assoc_, -return the next key, _Next_, and its value, _Value_. - - -*/ - -/** @pred is_assoc(+ _Assoc_) - - -Succeeds if _Assoc_ is an association list, that is, if it is a -red-black tree. - - -*/ - -/** @pred list_to_assoc(+ _List_,? _Assoc_) - - -Given a list _List_ such that each element of _List_ is of the -form _Key-Val_, and all the _Keys_ are unique, _Assoc_ is -the corresponding association list. - - -*/ - -/** @pred map_assoc(+ _Pred_,+ _Assoc_) - - -Succeeds if the unary predicate name _Pred_( _Val_) holds for every -element in the association list. - - -*/ - -/** @pred map_assoc(+ _Pred_,+ _Assoc_,? _New_) - -Given the binary predicate name _Pred_ and the association list - _Assoc_, _New_ in an association list with keys in _Assoc_, -and such that if _Key-Val_ is in _Assoc_, and _Key-Ans_ is in - _New_, then _Pred_( _Val_, _Ans_) holds. - - -*/ - -/** @pred max_assoc(+ _Assoc_,- _Key_,? _Value_) - - -Given the association list - _Assoc_, _Key_ in the largest key in the list, and _Value_ -the associated value. - - -*/ - -/** @pred min_assoc(+ _Assoc_,- _Key_,? _Value_) - - -Given the association list - _Assoc_, _Key_ in the smallest key in the list, and _Value_ -the associated value. - - -*/ - -/** @pred ord_list_to_assoc(+ _List_,? _Assoc_) - - -Given an ordered list _List_ such that each element of _List_ is -of the form _Key-Val_, and all the _Keys_ are unique, _Assoc_ is -the corresponding association list. - - -*/ - -/** @pred put_assoc(+ _Key_,+ _Assoc_,+ _Val_,+ _New_) - - -The association list _New_ includes and element of association - _key_ with _Val_, and all elements of _Assoc_ that did not -have key _Key_. - - - - -@} */ - -/** @defgroup AVL_Trees AVL Trees -@ingroup YAPLibrary -@{ - -AVL trees are balanced search binary trees. They are named after their -inventors, Adelson-Velskii and Landis, and they were the first -dynamically balanced trees to be proposed. The YAP AVL tree manipulation -predicates library uses code originally written by Martin van Emdem and -published in the Logic Programming Newsletter, Autumn 1981. A bug in -this code was fixed by Philip Vasey, in the Logic Programming -Newsletter, Summer 1982. The library currently only includes routines to -insert and lookup elements in the tree. Please try red-black trees if -you need deletion. - - -*/ - -/** @pred avl_new(+ _T_) - - -Create a new tree. - - -*/ - -/** @pred avl_insert(+ _Key_,? _Value_,+ _T0_,- _TF_) - - -Add an element with key _Key_ and _Value_ to the AVL tree - _T0_ creating a new AVL tree _TF_. Duplicated elements are -allowed. - - -*/ - -/** @pred avl_lookup(+ _Key_,- _Value_,+ _T_) - - -Lookup an element with key _Key_ in the AVL tree - _T_, returning the value _Value_. - - - - -@} */ - -/** @defgroup Exo_Intervals Exo Intervals -@ingroup YAPLibrary -@{ - -This package assumes you use exo-compilation, that is, that you loaded -the pedicate using the `exo` option to load_files/2, In this -case, YAP includes a package for improved search on intervals of -integers. - -The package is activated by `udi` declarations that state what is -the argument of interest: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -:- udi(diagnoses(exo_interval,?,?)). - -:- load_files(db, [consult(exo)]). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -It is designed to optimise the following type of queries: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- max(X, diagnoses(X, 9, Y), X). - -?- min(X, diagnoses(X, 9, 36211117), X). - -?- X #< Y, min(X, diagnoses(X, 9, 36211117), X ), diagnoses(Y, 9, _). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The first argument gives the time, the second the patient, and the -third the condition code. The first query should find the last time -the patient 9 had any code reported, the second looks for the first -report of code 36211117, and the last searches for reports after this -one. All queries run in constant or log(n) time. - - -@} */ - -/** @defgroup Gecode Gecode Interface -@ingroup YAPPackages -@{ - - -The gecode library intreface was designed and implemented by Denis -Duchier, with recent work by Vítor Santos Costa to port it to version 4 -of gecode and to have an higher level interface, - - -@} */ - -/** @defgroup The_Gecode_Interface The Gecode Interface -@ingroup Gecode -@{ - -This text is due to Denys Duchier. The gecode interface requires - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -:- use_module(library(gecode)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Several example programs are available with the distribution. - - + CREATING A SPACE - -A space is gecodes data representation for a store of constraints: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Space := space -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + CREATING VARIABLES - -Unlike in Gecode, variable objects are not bound to a specific Space. Each one -actually contains an index with which it is possible to access a Space-bound -Gecode variable. Variables can be created using the following expressions: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - IVar := intvar(Space,SPEC...) - BVar := boolvar(Space) - SVar := setvar(Space,SPEC...) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -where SPEC... is the same as in Gecode. For creating lists of variables use -the following variants: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - IVars := intvars(Space,N,SPEC...) - BVars := boolvars(Space,N,SPEC...) - SVars := setvars(Space,N,SPEC...) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -where N is the number of variables to create (just like for XXXVarArray in -Gecode). Sometimes an IntSet is necessary: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - ISet := intset([SPEC...]) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -where each SPEC is either an integer or a pair (I,J) of integers. An IntSet -describes a set of ints by providing either intervals, or integers (which stand -for an interval of themselves). It might be tempting to simply represent an -IntSet as a list of specs, but this would be ambiguous with IntArgs which, -here, are represented as lists of ints. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Space += keep(Var) - Space += keep(Vars) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Variables can be marked as "kept". In this case, only such variables will be -explicitly copied during search. This could bring substantial benefits in -memory usage. Of course, in a solution, you can then only look at variables -that have been "kept". If no variable is marked as "kept", then they are all -kept. Thus marking variables as "kept" is purely an optimization. - - + CONSTRAINTS AND BRANCHINGS - -all constraint and branching posting functions are available just like in -Gecode. Wherever a XXXArgs or YYYSharedArray is expected, simply use a list. -At present, there is no support for minimodel-like constraint posting. -Constraints and branchings are added to a space using: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Space += CONSTRAINT - Space += BRANCHING -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -For example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Space += rel(X,'IRT_EQ',Y) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -arrays of variables are represented by lists of variables, and constants are -represented by atoms with the same name as the Gecode constant -(e.g. 'INT_VAR_SIZE_MIN'). - - + SEARCHING FOR SOLUTIONS - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - SolSpace := search(Space) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This is a backtrackable predicate that enumerates all solution spaces -(SolSpace). It may also take options: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - SolSpace := search(Space,Options) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Options is a list whose elements maybe: - - + restart -to select the Restart search engine - + threads=N -to activate the parallel search engine and control the number of -workers (see Gecode doc) - + c_d=N -to set the commit distance for recomputation - + a_d=N -to set the adaptive distance for recomputation - - - - + EXTRACTING INFO FROM A SOLUTION - -An advantage of non Space-bound variables, is that you can use them both to -post constraints in the original space AND to consult their values in -solutions. Below are methods for looking up information about variables. Each -of these methods can either take a variable as argument, or a list of -variables, and returns resp. either a value, or a list of values: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Val := assigned(Space,X) - - Val := min(Space,X) - Val := max(Space,X) - Val := med(Space,X) - Val := val(Space,X) - Val := size(Space,X) - Val := width(Space,X) - Val := regret_min(Space,X) - Val := regret_max(Space,X) - - Val := glbSize(Space,V) - Val := lubSize(Space,V) - Val := unknownSize(Space,V) - Val := cardMin(Space,V) - Val := cardMax(Space,V) - Val := lubMin(Space,V) - Val := lubMax(Space,V) - Val := glbMin(Space,V) - Val := glbMax(Space,V) - Val := glb_ranges(Space,V) - Val := lub_ranges(Space,V) - Val := unknown_ranges(Space,V) - Val := glb_values(Space,V) - Val := lub_values(Space,V) - Val := unknown_values(Space,V) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + DISJUNCTORS - -Disjunctors provide support for disjunctions of clauses, where each clause is a -conjunction of constraints: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - C1 or C2 or ... or Cn -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Each clause is executed "speculatively": this means it does not affect the main -space. When a clause becomes failed, it is discarded. When only one clause -remains, it is committed: this means that it now affects the main space. - -Example: - -Consider the problem where either X=Y=0 or X=Y+(1 or 2) for variable X and Y -that take values in 0..3. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Space := space, - [X,Y] := intvars(Space,2,0,3), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -First, we must create a disjunctor as a manager for our 2 clauses: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Disj := disjunctor(Space), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -We can now create our first clause: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - C1 := clause(Disj), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This clause wants to constrain X and Y to 0. However, since it must be -executed "speculatively", it must operate on new variables X1 and Y1 that -shadow X and Y: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - [X1,Y1] := intvars(C1,2,0,3), - C1 += forward([X,Y],[X1,Y1]), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The forward(...) stipulation indicates which global variable is shadowed by -which clause-local variable. Now we can post the speculative clause-local -constraints for X=Y=0: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - C1 += rel(X1,'IRT_EQ',0), - C1 += rel(Y1,'IRT_EQ',0), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -We now create the second clause which uses X2 and Y2 to shadow X and Y: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - C2 := clause(Disj), - [X2,Y2] := intvars(C2,2,0,3), - C2 += forward([X,Y],[X2,Y2]), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -However, this clause also needs a clause-local variable Z2 taking values 1 or -2 in order to post the clause-local constraint X2=Y2+Z2: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Z2 := intvar(C2,1,2), - C2 += linear([-1,1,1],[X2,Y2,Z2],'IRT_EQ',0), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Finally, we can branch and search: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Space += branch([X,Y],'INT_VAR_SIZE_MIN','INT_VAL_MIN'), - SolSpace := search(Space), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -and lookup values of variables in each solution: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - [X_,Y_] := val(SolSpace,[X,Y]). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup Gecode_and_ClPbBFDbC Programming Finite Domain Constraints in YAP/Gecode -@ingroup Gecode -@{ - -The gecode/clp(fd) interface is designed to use the GECODE functionality -in a more CLP like style. It requires - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -:- use_module(library(gecode/clpfd)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Several example programs are available with the distribution. - -Integer variables are declared as: - - + _V_ in _A_.. _B_ -declares an integer variable _V_ with range _A_ to _B_. - + _Vs_ ins _A_.. _B_ -declares a set of integer variabless _Vs_ with range _A_ to _B_. - + boolvar( _V_) -declares a boolean variable. - + boolvars( _Vs_) -declares a set of boolean variable. - - -Constraints supported are: - - -*/ - -/** @pred _X_ #= _Y_ -equality - -*/ - -/** @pred _X_ #\\= _Y_ -disequality - -*/ - -/** @pred _X_ #\> _Y_ -larger - -*/ - -/** @pred _X_ #\>= _Y_ -larger or equal - -*/ - -/** @pred _X_ #=\< _Y_ -smaller - -*/ - -/** @pred _X_ #\< _Y_ -smaller or equal - -Arguments to this constraint may be an arithmetic expression with +, --, \\\*, integer division /, min, max, sum, -count, and -abs. Boolean variables support conjunction (/\\), disjunction (\\/), -implication (=\>), equivalence (\<=\>), and xor. The sum constraint allows a two argument version using the -`where` conditional, in Zinc style. - -The send more money equation may be written as: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - 1000*S + 100*E + 10*N + D + - 1000*M + 100*O + 10*R + E #= -10000*M + 1000*O + 100*N + 10*E + Y, -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This example uses `where` to select from -column _I_ the elements that have value under _M_: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -OutFlow[I] #= sum(J in 1..N where D[J,I]count constraint counts the number of elements that match a -certain constant or variable (integer sets are not available). - - -*/ - -/** @pred all_different( _Vs_ ) - -*/ - -/** @pred all_distinct( _Vs_) - -*/ - -/** @pred all_different( _Cs_, _Vs_) - -*/ - -/** @pred all_distinct( _Cs_, _Vs_) -verifies whether all elements of a list are different. In the second -case, tests if all the sums between a list of constants and a list of -variables are different. - -This is a formulation of the queens problem that uses both versions of `all_different`: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -queens(N, Queens) :- - length(Queens, N), - Queens ins 1..N, - all_distinct(Queens), - foldl(inc, Queens, Inc, 0, _), % [0, 1, 2, .... ] - foldl(dec, Queens, Dec, 0, _), % [0, -1, -2, ... ] - all_distinct(Inc,Queens), - all_distinct(Dec,Queens), - labeling([], Queens). - -inc(_, I0, I0, I) :- - I is I0+1. - -dec(_, I0, I0, I) :- - I is I0-1. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The next example uses `all_different/1` and the functionality of the matrix package to verify that all squares in -sudoku have a different value: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - foreach( [I,J] ins 0..2 , - all_different(M[I*3+(0..2),J*3+(0..2)]) ), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred scalar_product(+ _Cs_, + _Vs_, + _Rel_, ? _V_ ) - -The product of constant _Cs_ by _Vs_ must be in relation - _Rel_ with _V_ . - - -*/ - -/** @pred _X_ #= -all elements of _X_ must take the same value - -*/ - -/** @pred _X_ #\\= -not all elements of _X_ take the same value - -*/ - -/** @pred _X_ #\> -elements of _X_ must be increasing - -*/ - -/** @pred _X_ #\>= -elements of _X_ must be increasinga or equal - -*/ - -/** @pred _X_ #=\< -elements of _X_ must be decreasing - -*/ - -/** @pred _X_ #\< -elements of _X_ must be decreasing or equal - - -*/ - -/** @pred _X_ #\<==\> _B_ -reified equivalence - -*/ - -/** @pred _X_ #==\> _B_ -reified implication - -*/ - -/** @pred _X_ #\< _B_ -reified implication - -As an example. consider finding out the people who wanted to sit -next to a friend and that are are actually sitting together: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -preference_satisfied(X-Y, B) :- - abs(X - Y) #= 1 #<==> B. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Note that not all constraints may be reifiable. - - -*/ - -/** @pred element( _X_, _Vs_ ) - _X_ is an element of list _Vs_ - - -*/ - -/** @pred clause( _Type_, _Ps_ , _Ns_, _V_ ) -If _Type_ is `and` it is the conjunction of boolean variables - _Ps_ and the negation of boolean variables _Ns_ and must have -result _V_. If _Type_ is `or` it is a disjunction. - - + DFA -the interface allows creating and manipulation deterministic finite -automata. A DFA has a set of states, represented as integers -and is initialised with an initial state, a set of transitions from the -first to the last argument emitting the middle argument, and a final -state. - -The swedish-drinkers protocol is represented as follows: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - A = [X,Y,Z], - dfa( 0, [t(0,0,0),t(0,1,1),t(1,0,0),t(-1,0,0)], [0], C), - in_dfa( A, C ), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This code will enumeratae the valid tuples of three emissions. - - + extensional constraints -Constraints can also be represented as lists of tuples. - -The previous example -would be written as: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - extensional_constraint([[0,0,0],[0,1,0],[1,0,0]], C), - in_relation( A, C ), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred minimum( _X_, _Vs_) - -*/ - -/** @pred min( _X_, _Vs_) -First Argument is the least element of a list. - - -*/ - -/** @pred maximum( _X_, _Vs_) - -*/ - -/** @pred max( _X_, _Vs_) -First Argument is the greatest element of a list. - - + lex_order( _Vs_) -All elements must be ordered. - - - -The following predicates control search: - - -*/ - -/** @pred labeling( _Opts_, _Xs_) -performs labeling, several variable and value selection options are -available. The defaults are `min` and `min_step`. - -Variable selection options are as follows: - - + leftmost -choose the first variable - + min -choose one of the variables with smallest minimum value - + max -choose one of the variables with greatest maximum value - + ff -choose one of the most constrained variables, that is, with the smallest -domain. - - -Given that we selected a variable, the values chosen for branching may -be: - - + min_step -smallest value - + max_step -largest value - + bisect -median - + enum -all value starting from the minimum. - - - -*/ - -/** @pred maximize( _V_) -maximise variable _V_ - - -*/ - -/** @pred minimize(V) -minimise variable _V_ - - - - -@} */ - -/** @defgroup Heaps Heaps -@ingroup YAPLibrary -@{ - -A heap is a labelled binary tree where the key of each node is less than -or equal to the keys of its sons. The point of a heap is that we can -keep on adding new elements to the heap and we can keep on taking out -the minimum element. If there are N elements total, the total time is -O(NlgN). If you know all the elements in advance, you are better off -doing a merge-sort, but this file is for when you want to do say a -best-first search, and have no idea when you start how many elements -there will be, let alone what they are. - -The following heap manipulation routines are available once included -with the `use_module(library(heaps))` command. - - - - @pred add_to_heap(+ _Heap_,+ _key_,+ _Datum_,- _NewHeap_) - - -Inserts the new _Key-Datum_ pair into the heap. The insertion is not -stable, that is, if you insert several pairs with the same _Key_ it -is not defined which of them will come out first, and it is possible for -any of them to come out first depending on the history of the heap. - - -*/ - -/** @pred empty_heap(? _Heap_) - - -Succeeds if _Heap_ is an empty heap. - - -*/ - -/** @pred get_from_heap(+ _Heap_,- _key_,- _Datum_,- _Heap_) - - -Returns the _Key-Datum_ pair in _OldHeap_ with the smallest - _Key_, and also a _Heap_ which is the _OldHeap_ with that -pair deleted. - - -*/ - -/** @pred heap_size(+ _Heap_, - _Size_) - - -Reports the number of elements currently in the heap. - - -*/ - -/** @pred heap_to_list(+ _Heap_, - _List_) - - -Returns the current set of _Key-Datum_ pairs in the _Heap_ as a - _List_, sorted into ascending order of _Keys_. - - -*/ - -/** @pred list_to_heap(+ _List_, - _Heap_) - - -Takes a list of _Key-Datum_ pairs (such as keysort could be used to sort) -and forms them into a heap. - - -*/ - -/** @pred min_of_heap(+ _Heap_, - _Key_, - _Datum_) - - -Returns the Key-Datum pair at the top of the heap (which is of course -the pair with the smallest Key), but does not remove it from the heap. - - -*/ - -/** @pred min_of_heap(+ _Heap_, - _Key1_, - _Datum1_, -- _Key2_, - _Datum2_) - -Returns the smallest (Key1) and second smallest (Key2) pairs in the -heap, without deleting them. - - - -@} */ - -/** @defgroup Lists List Manipulation -@ingroup YAPLibrary -@{ - -The following list manipulation routines are available once included -with the `use_module(library(lists))` command. - - - - @pred append(? _Prefix_,? _Suffix_,? _Combined_) - - -True when all three arguments are lists, and the members of - _Combined_ are the members of _Prefix_ followed by the members of _Suffix_. -It may be used to form _Combined_ from a given _Prefix_, _Suffix_ or to take -a given _Combined_ apart. - - -*/ - -/** @pred append(? _Lists_,? _Combined_) - -Holds if the lists of _Lists_ can be concatenated as a - _Combined_ list. - - -*/ - -/** @pred delete(+ _List_, ? _Element_, ? _Residue_) - - -True when _List_ is a list, in which _Element_ may or may not -occur, and _Residue_ is a copy of _List_ with all elements -identical to _Element_ deleted. - - -*/ - -/** @pred flatten(+ _List_, ? _FlattenedList_) - - -Flatten a list of lists _List_ into a single list - _FlattenedList_. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- flatten([[1],[2,3],[4,[5,6],7,8]],L). - -L = [1,2,3,4,5,6,7,8] ? ; - -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred last(+ _List_,? _Last_) - - -True when _List_ is a list and _Last_ is identical to its last element. - - -*/ - -/** @pred list_concat(+ _Lists_,? _List_) - - -True when _Lists_ is a list of lists and _List_ is the -concatenation of _Lists_. - - -*/ - -/** @pred member(? _Element_, ? _Set_) - - -True when _Set_ is a list, and _Element_ occurs in it. It may be used -to test for an element or to enumerate all the elements by backtracking. - - -*/ - -/** @pred memberchk(+ _Element_, + _Set_) - - -As member/2, but may only be used to test whether a known - _Element_ occurs in a known Set. In return for this limited use, it -is more efficient when it is applicable. - - -*/ - -/** @pred nth0(? _N_, ? _List_, ? _Elem_) - - -True when _Elem_ is the Nth member of _List_, -counting the first as element 0. (That is, throw away the first -N elements and unify _Elem_ with the next.) It can only be used to -select a particular element given the list and index. For that -task it is more efficient than member/2 - - -*/ - -/** @pred nth1(? _N_, ? _List_, ? _Elem_) - - -The same as nth0/3, except that it counts from -1, that is `nth(1, [H|_], H)`. - - -*/ - -/** @pred nth(? _N_, ? _List_, ? _Elem_) - - -The same as nth1/3. - - -*/ - -/** @pred nth0(? _N_, ? _List_, ? _Elem_, ? _Rest_) - -Unifies _Elem_ with the Nth element of _List_, -counting from 0, and _Rest_ with the other elements. It can be used -to select the Nth element of _List_ (yielding _Elem_ and _Rest_), or to -insert _Elem_ before the Nth (counting from 1) element of _Rest_, when -it yields _List_, e.g. `nth0(2, List, c, [a,b,d,e])` unifies List with -`[a,b,c,d,e]`. `nth/4` is the same except that it counts from 1. `nth0/4` -can be used to insert _Elem_ after the Nth element of _Rest_. - - -*/ - -/** @pred nth1(? _N_, ? _List_, ? _Elem_, ? _Rest_) - -Unifies _Elem_ with the Nth element of _List_, counting from 1, -and _Rest_ with the other elements. It can be used to select the -Nth element of _List_ (yielding _Elem_ and _Rest_), or to -insert _Elem_ before the Nth (counting from 1) element of - _Rest_, when it yields _List_, e.g. `nth(3, List, c, [a,b,d,e])` unifies List with `[a,b,c,d,e]`. `nth/4` -can be used to insert _Elem_ after the Nth element of _Rest_. - - -*/ - -/** @pred nth(? _N_, ? _List_, ? _Elem_, ? _Rest_) - -Same as `nth1/4`. - - -*/ - -/** @pred permutation(+ _List_,? _Perm_) - - -True when _List_ and _Perm_ are permutations of each other. - - -*/ - -/** @pred remove_duplicates(+ _List_, ? _Pruned_) - - -Removes duplicated elements from _List_. Beware: if the _List_ has -non-ground elements, the result may surprise you. - - -*/ - -/** @pred reverse(+ _List_, ? _Reversed_) - - -True when _List_ and _Reversed_ are lists with the same elements -but in opposite orders. - - -*/ - -/** @pred same_length(? _List1_, ? _List2_) - - -True when _List1_ and _List2_ are both lists and have the same number -of elements. No relation between the values of their elements is -implied. -Modes `same_length(-,+)` and `same_length(+,-)` generate either list given -the other; mode `same_length(-,-)` generates two lists of the same length, -in which case the arguments will be bound to lists of length 0, 1, 2, ... - - -*/ - -/** @pred select(? _Element_, ? _List_, ? _Residue_) - - -True when _Set_ is a list, _Element_ occurs in _List_, and - _Residue_ is everything in _List_ except _Element_ (things -stay in the same order). - - -*/ - -/** @pred selectchk(? _Element_, ? _List_, ? _Residue_) - - -Semi-deterministic selection from a list. Steadfast: defines as - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -selectchk(Elem, List, Residue) :- - select(Elem, List, Rest0), !, - Rest = Rest0. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred sublist(? _Sublist_, ? _List_) - - -True when both `append(_,Sublist,S)` and `append(S,_,List)` hold. - - -*/ - -/** @pred suffix(? _Suffix_, ? _List_) - - -Holds when `append(_,Suffix,List)` holds. - - -*/ - -/** @pred sum_list(? _Numbers_, ? _Total_) - - -True when _Numbers_ is a list of numbers, and _Total_ is their sum. - - -*/ - -/** @pred sum_list(? _Numbers_, + _SoFar_, ? _Total_) - -True when _Numbers_ is a list of numbers, and _Total_ is the sum of their total plus _SoFar_. - - -*/ - -/** @pred sumlist(? _Numbers_, ? _Total_) - - -True when _Numbers_ is a list of integers, and _Total_ is their -sum. The same as sum_list/2, please do use sum_list/2 -instead. - - -*/ - -/** @pred max_list(? _Numbers_, ? _Max_) - - -True when _Numbers_ is a list of numbers, and _Max_ is the maximum. - - -*/ - -/** @pred min_list(? _Numbers_, ? _Min_) - - -True when _Numbers_ is a list of numbers, and _Min_ is the minimum. - - -*/ - -/** @pred numlist(+ _Low_, + _High_, + _List_) - - -If _Low_ and _High_ are integers with _Low_ =\< - _High_, unify _List_ to a list `[Low, Low+1, ...High]`. See -also between/3. - - -*/ - -/** @pred intersection(+ _Set1_, + _Set2_, + _Set3_) - - -Succeeds if _Set3_ unifies with the intersection of _Set1_ and - _Set2_. _Set1_ and _Set2_ are lists without duplicates. They -need not be ordered. - - -*/ - -/** @pred subtract(+ _Set_, + _Delete_, ? _Result_) - - -Delete all elements from _Set_ that occur in _Delete_ (a set) -and unify the result with _Result_. Deletion is based on -unification using memberchk/2. The complexity is -`|Delete|\*|Set|`. - -See ord_subtract/3. - - - -@} */ - -/** @defgroup LineUtilities Line Manipulation Utilities -@ingroup YAPLibrary -@{ - -This package provides a set of useful predicates to manipulate -sequences of characters codes, usually first read in as a line. It is -available by loading the library `library(lineutils)`. - - - - @pred search_for(+ _Char_,+ _Line_) - - - -Search for a character _Char_ in the list of codes _Line_. - - -*/ - -/** @pred search_for(+ _Char_,+ _Line_,- _RestOfine_) - - -Search for a character _Char_ in the list of codes _Line_, - _RestOfLine_ has the line to the right. - - -*/ - -/** @pred scan_natural(? _Nat_,+ _Line_,+ _RestOfLine_) - - - -Scan the list of codes _Line_ for a natural number _Nat_, zero -or a positive integer, and unify _RestOfLine_ with the remainder -of the line. - - -*/ - -/** @pred scan_integer(? _Int_,+ _Line_,+ _RestOfLine_) - - - -Scan the list of codes _Line_ for an integer _Nat_, either a -positive, zero, or negative integer, and unify _RestOfLine_ with -the remainder of the line. - - -*/ - -/** @pred split(+ _Line_,+ _Separators_,- _Split_) - - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the character codes in _Separators_ as separators. As an -example, consider: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- split("Hello * I am free"," *",S). - -S = ["Hello","I","am","free"] ? - -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred split(+ _Line_,- _Split_) - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the blank characters as separators. - - -*/ - -/** @pred fields(+ _Line_,+ _Separators_,- _Split_) - - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the character codes in _Separators_ as separators for -fields. If two separators occur in a row, the field is considered -empty. As an example, consider: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- fields("Hello I am free"," *",S). - -S = ["Hello","","I","am","","free"] ? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred fields(+ _Line_,- _Split_) - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the blank characters as field separators. - - -*/ - -/** @pred glue(+ _Words_,+ _Separator_,- _Line_) - - - -Unify _Line_ with string obtained by glueing _Words_ with -the character code _Separator_. - - -*/ - -/** @pred copy_line(+ _StreamInput_,+ _StreamOutput_) - - - -Copy a line from _StreamInput_ to _StreamOutput_. - - -*/ - -/** @pred process(+ _StreamInp_, + _Goal_) - - - -For every line _LineIn_ in stream _StreamInp_, call -`call(Goal,LineIn)`. - - -*/ - -/** @pred filter(+ _StreamInp_, + _StreamOut_, + _Goal_) - - - -For every line _LineIn_ in stream _StreamInp_, execute -`call(Goal,LineIn,LineOut)`, and output _LineOut_ to -stream _StreamOut_. - - -*/ - -/** @pred file_filter(+ _FileIn_, + _FileOut_, + _Goal_) - - - -For every line _LineIn_ in file _FileIn_, execute -`call(Goal,LineIn,LineOut)`, and output _LineOut_ to file - _FileOut_. - - -*/ - -/** @pred file_filter(+ _FileIn_, + _FileOut_, + _Goal_, - -+ _FormatCommand_, + _Arguments_) - - -Same as file_filter/3, but before starting the filter execute -`format/3` on the output stream, using _FormatCommand_ and - _Arguments_. - - - - -@} */ - -/** @defgroup matrix Matrix Library -@ingroup YAPLibrary -@{ - -This package provides a fast implementation of multi-dimensional -matrices of integers and floats. In contrast to dynamic arrays, these -matrices are multi-dimensional and compact. In contrast to static -arrays. these arrays are allocated in the stack. Matrices are available -by loading the library `library(matrix)`. They are multimensional -objects of type: - - + terms: Prolog terms - + ints: bounded integers, represented as an opaque term. The -maximum integer depends on hardware, but should be obtained from the -natural size of the machine. - + floats: floating-poiny numbers, represented as an opaque term. - - -Matrix elements can be accessed through the `matrix_get/2` -predicate or through an R-inspired access notation (that uses the ciao -style extension to `[]`. Examples include: - - -*/ - -/** @pred _E_ \<== _X_[2,3] -Access the second row, third column of matrix X. Indices start from -`0`, - -*/ - -/** @pred _L_ \<== _X_[2,_] -Access all the second row, the output is a list ofe elements. - -*/ - -/** @pred _L_ \<== _X_[2..4,_] -Access all the second, thrd and fourth rows, the output is a list of elements. - -*/ - -/** @pred _L_ \<== _X_[2..4+3,_] -Access all the fifth, sixth and eight rows, the output is a list of elements. - - -The matrix library also supports a B-Prolog/ECliPSe inspired `foreach` ITerator to iterate over -elements of a matrix: - - -*/ - -/** @pred foreach(I in 0..N1, X[I] \<== Y[I]) -Copies a vector, element by element. - -*/ - -/** @pred foreach([I in 0..N1, J in I..N1], Z[I,J] \<== X[I,J] - X[I,J]) -The lower-triangular matrix _Z_ is the difference between the -lower-triangular and upper-triangular parts of _X_. - -*/ - -/** @pred foreach([I in 0..N1, J in 0..N1], plus(X[I,J]), 0, Sum) -Add all elements of a matrix by using _Sum_ as an accumulator. - - -Notice that the library does not support all known matrix operations. Please -contact the YAP maintainers if you require extra functionality. - - - - + _X_ = array[ _Dim1_,..., _Dimn_] of _Objects_ - - -The of/2 operator can be used to create a new array of - _Objects_. The objects supported are: - - + Unbound Variable -create an array of free variables - + ints -create an array of integers - + floats -create an array of floating-point numbers - + _I_: _J_ -create an array with integers from _I_ to _J_ - + [..] -create an array from the values in a list - - -The dimensions can be given as an integer, and the matrix will be -indexed `C`-style from `0..( _Max_-1)`, or can be given -as an interval ` _Base_.. _Limit_`. In the latter case, -matrices of integers and of floating-point numbers should have the same - _Base_ on every dimension. - - -*/ - -/** @pred ? _LHS_ \<== _RHS_ - - -General matrix assignment operation. It evaluates the right-hand side -and then acts different according to the -left-hand side and to the matrix: - - + if _LHS_ is part of an integer or floating-point matrix, -perform non-backtrackable assignment. - + other unify left-hand side and right-hand size. - - -The right-hand side supports the following operators: - - + []/2 -written as _M_[ _Offset_]: obtain an element or list of elements -of matrix _M_ at offset _Offset_. - + matrix/1 -create a vector from a list - + matrix/2 -create a matrix from a list. Oprions are: - - + dim= -a list of dimensiona - + type= -integers, floating-point or terms - + base= -a list of base offsets per dimension (all must be the same for arrays of -integers and floating-points - - + matrix/3 -create matrix giving two options - + dim/1 -list with matrix dimensions - + nrow/1 -number of rows in bi-dimensional matrix - + ncol/1 -number of columns in bi-dimensional matrix - + length/1 -size of a matrix - + size/1 -size of a matrix - + max/1 -maximum element of a numeric matrix - + maxarg/1 -argument of maximum element of a numeric matrix - + min/1 -minimum element of a numeric matrix - + minarg/1 -argument of minimum element of a numeric matrix - + list/1 -represent matrix as a list - + lists/2 -represent matrix as list of embedded lists - + ../2 - _I_.. _J_ generates a list with all integers from _I_ to - _J_, included. - + +/2 -add two numbers, add two matrices element-by-element, or add a number to -all elements of a matrix or list - + -/2 -subtract two numbers, subtract two matrices or lists element-by-element, or subtract a number from -all elements of a matrix or list - + \* /2 -multiply two numbers, multiply two matrices or lists element-by-element, or multiply a number from -all elements of a matrix or list - + log/1 -natural logarithm of a number, matrix or list - + exp/1 -natural exponentiation of a number, matrix or list - - - -*/ - -/** @pred foreach( _Sequence_, _Goal_) - - -Deterministic iterator. The ranges are given by _Sequence_ that is -either ` _I_ in _M_.. _N_`, or of the form -`[ _I_, _J_] ins _M_.. _N_`, or a list of the above conditions. - -Variables in the goal are assumed to be global, ie, share a single value -in the execution. The exceptions are the iteration indices. Moreover, if -the goal is of the form ` _Locals_^ _G_` all variables -occurring in _Locals_ are marked as local. As an example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -foreach([I,J] ins 1..N, A^(A <==M[I,J], N[I] <== N[I] + A*A) ) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -the variables _I_, _J_ and _A_ are duplicated for every -call (local), whereas the matrices _M_ and _N_ are shared -throughout the execution (global). - - -*/ - -/** @pred foreach( _Sequence_, _Goal_, _Acc0_, _AccF_) - -Deterministic iterator with accumulator style arguments. - - -*/ - -/** @pred matrix_new(+ _Type_,+ _Dims_,- _Matrix_) - - - -Create a new matrix _Matrix_ of type _Type_, which may be one of -`ints` or `floats`, and with a list of dimensions _Dims_. -The matrix will be initialised to zeros. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- matrix_new(ints,[2,3],Matrix). - -Matrix = {..} -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Notice that currently YAP will always write a matrix of numbers as `{..}`. - - -*/ - -/** @pred matrix_new(+ _Type_,+ _Dims_,+ _List_,- _Matrix_) - - -Create a new matrix _Matrix_ of type _Type_, which may be one of -`ints` or `floats`, with dimensions _Dims_, and -initialised from list _List_. - - -*/ - -/** @pred matrix_new_set(? _Dims_,+ _OldMatrix_,+ _Value_,- _NewMatrix_) - - - -Create a new matrix _NewMatrix_ of type _Type_, with dimensions - _Dims_. The elements of _NewMatrix_ are set to _Value_. - - -*/ - -/** @pred matrix_dims(+ _Matrix_,- _Dims_) - - - -Unify _Dims_ with a list of dimensions for _Matrix_. - - -*/ - -/** @pred matrix_ndims(+ _Matrix_,- _Dims_) - - - -Unify _NDims_ with the number of dimensions for _Matrix_. - - -*/ - -/** @pred matrix_size(+ _Matrix_,- _NElems_) - - - -Unify _NElems_ with the number of elements for _Matrix_. - - -*/ - -/** @pred matrix_type(+ _Matrix_,- _Type_) - - - -Unify _NElems_ with the type of the elements in _Matrix_. - - -*/ - -/** @pred matrix_to_list(+ _Matrix_,- _Elems_) - - - -Unify _Elems_ with the list including all the elements in _Matrix_. - - -*/ - -/** @pred matrix_get(+ _Matrix_,+ _Position_,- _Elem_) - - - -Unify _Elem_ with the element of _Matrix_ at position - _Position_. - - -*/ - -/** @pred matrix_get(+ _Matrix_[+ _Position_],- _Elem_) - - -Unify _Elem_ with the element _Matrix_[ _Position_]. - - -*/ - -/** @pred matrix_set(+ _Matrix_,+ _Position_,+ _Elem_) - - - -Set the element of _Matrix_ at position - _Position_ to _Elem_. - - -*/ - -/** @pred matrix_set(+ _Matrix_[+ _Position_],+ _Elem_) - - -Set the element of _Matrix_[ _Position_] to _Elem_. - - -*/ - -/** @pred matrix_set_all(+ _Matrix_,+ _Elem_) - - - -Set all element of _Matrix_ to _Elem_. - - -*/ - -/** @pred matrix_add(+ _Matrix_,+ _Position_,+ _Operand_) - - - -Add _Operand_ to the element of _Matrix_ at position - _Position_. - - -*/ - -/** @pred matrix_inc(+ _Matrix_,+ _Position_) - - - -Increment the element of _Matrix_ at position _Position_. - - -*/ - -/** @pred matrix_inc(+ _Matrix_,+ _Position_,- _Element_) - - -Increment the element of _Matrix_ at position _Position_ and -unify with _Element_. - - -*/ - -/** @pred matrix_dec(+ _Matrix_,+ _Position_) - - - -Decrement the element of _Matrix_ at position _Position_. - - -*/ - -/** @pred matrix_dec(+ _Matrix_,+ _Position_,- _Element_) - - -Decrement the element of _Matrix_ at position _Position_ and -unify with _Element_. - - -*/ - -/** @pred matrix_arg_to_offset(+ _Matrix_,+ _Position_,- _Offset_) - - - -Given matrix _Matrix_ return what is the numerical _Offset_ of -the element at _Position_. - - -*/ - -/** @pred matrix_offset_to_arg(+ _Matrix_,- _Offset_,+ _Position_) - - - -Given a position _Position _ for matrix _Matrix_ return the -corresponding numerical _Offset_ from the beginning of the matrix. - - -*/ - -/** @pred matrix_max(+ _Matrix_,+ _Max_) - - - -Unify _Max_ with the maximum in matrix _Matrix_. - - -*/ - -/** @pred matrix_maxarg(+ _Matrix_,+ _Maxarg_) - - - -Unify _Max_ with the position of the maximum in matrix _Matrix_. - - -*/ - -/** @pred matrix_min(+ _Matrix_,+ _Min_) - - - -Unify _Min_ with the minimum in matrix _Matrix_. - - -*/ - -/** @pred matrix_minarg(+ _Matrix_,+ _Minarg_) - - - -Unify _Min_ with the position of the minimum in matrix _Matrix_. - - -*/ - -/** @pred matrix_sum(+ _Matrix_,+ _Sum_) - - - -Unify _Sum_ with the sum of all elements in matrix _Matrix_. - - -*/ - -/** @pred matrix_agg_lines(+ _Matrix_,+ _Aggregate_) - - - -If _Matrix_ is a n-dimensional matrix, unify _Aggregate_ with -the n-1 dimensional matrix where each element is obtained by adding all -Matrix elements with same last n-1 index. - - -*/ - -/** @pred matrix_agg_cols(+ _Matrix_,+ _Aggregate_) - - - -If _Matrix_ is a n-dimensional matrix, unify _Aggregate_ with -the one dimensional matrix where each element is obtained by adding all -Matrix elements with same first index. - - -*/ - -/** @pred matrix_op(+ _Matrix1_,+ _Matrix2_,+ _Op_,- _Result_) - - - - _Result_ is the result of applying _Op_ to matrix _Matrix1_ -and _Matrix2_. Currently, only addition (`+`) is supported. - - -*/ - -/** @pred matrix_op_to_all(+ _Matrix1_,+ _Op_,+ _Operand_,- _Result_) - - - - _Result_ is the result of applying _Op_ to all elements of - _Matrix1_, with _Operand_ as the second argument. Currently, -only addition (`+`), multiplication (`\*`), and division -(`/`) are supported. - - -*/ - -/** @pred matrix_op_to_lines(+ _Matrix1_,+ _Lines_,+ _Op_,- _Result_) - - - - _Result_ is the result of applying _Op_ to all elements of - _Matrix1_, with the corresponding element in _Lines_ as the -second argument. Currently, only division (`/`) is supported. - - -*/ - -/** @pred matrix_op_to_cols(+ _Matrix1_,+ _Cols_,+ _Op_,- _Result_) - - - - _Result_ is the result of applying _Op_ to all elements of - _Matrix1_, with the corresponding element in _Cols_ as the -second argument. Currently, only addition (`+`) is -supported. Notice that _Cols_ will have n-1 dimensions. - - -*/ - -/** @pred matrix_shuffle(+ _Matrix_,+ _NewOrder_,- _Shuffle_) - - - -Shuffle the dimensions of matrix _Matrix_ according to - _NewOrder_. The list _NewOrder_ must have all the dimensions of - _Matrix_, starting from 0. - - -*/ - -/** @pred matrix_transpose(+ _Matrix_,- _Transpose_) - - - -Transpose matrix _Matrix_ to _Transpose_. Equivalent to: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -matrix_transpose(Matrix,Transpose) :- - matrix_shuffle(Matrix,[1,0],Transpose). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred matrix_expand(+ _Matrix_,+ _NewDimensions_,- _New_) - - - -Expand _Matrix_ to occupy new dimensions. The elements in - _NewDimensions_ are either 0, for an existing dimension, or a -positive integer with the size of the new dimension. - - -*/ - -/** @pred matrix_select(+ _Matrix_,+ _Dimension_,+ _Index_,- _New_) - - - -Select from _Matrix_ the elements who have _Index_ at - _Dimension_. - - -*/ - -/** @pred matrix_row(+ _Matrix_,+ _Column_,- _NewMatrix_) - - - -Select from _Matrix_ the row matching _Column_ as new matrix _NewMatrix_. _Column_ must have one less dimension than the original matrix. - _Dimension_. - - - - -@} */ - -/** @defgroup MATLAB MATLAB Package Interface -@ingroup YAPLibrary -@{ - -The MathWorks MATLAB is a widely used package for array -processing. YAP now includes a straightforward interface to MATLAB. To -actually use it, you need to install YAP calling `configure` with -the `--with-matlab=DIR` option, and you need to call -`use_module(library(lists))` command. - -Accessing the matlab dynamic libraries can be complicated. In Linux -machines, to use this interface, you may have to set the environment -variable LD_LIBRARY_PATH. Next, follows an example using bash in a -64-bit Linux PC: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -export LD_LIBRARY_PATH=''$MATLAB_HOME"/sys/os/glnxa64:''$MATLAB_HOME"/bin/glnxa64:''$LD_LIBRARY_PATH" -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -where `MATLAB_HOME` is the directory where matlab is installed -at. Please replace `ax64` for `x86` on a 32-bit PC. - - - - @pred start_matlab(+ _Options_) - - -Start a matlab session. The argument _Options_ may either be the -empty string/atom or the command to call matlab. The command may fail. - - -*/ - -/** @pred close_matlab - - -Stop the current matlab session. - - -*/ - -/** @pred matlab_on - - -Holds if a matlab session is on. - - -*/ - -/** @pred matlab_eval_string(+ _Command_) - - -Holds if matlab evaluated successfully the command _Command_. - - -*/ - -/** @pred matlab_eval_string(+ _Command_, - _Answer_) - -MATLAB will evaluate the command _Command_ and unify _Answer_ -with a string reporting the result. - - -*/ - -/** @pred matlab_cells(+ _Size_, ? _Array_) - - -MATLAB will create an empty vector of cells of size _Size_, and if - _Array_ is bound to an atom, store the array in the matlab -variable with name _Array_. Corresponds to the MATLAB command `cells`. - - -*/ - -/** @pred matlab_cells(+ _SizeX_, + _SizeY_, ? _Array_) - -MATLAB will create an empty array of cells of size _SizeX_ and - _SizeY_, and if _Array_ is bound to an atom, store the array -in the matlab variable with name _Array_. Corresponds to the -MATLAB command `cells`. - - -*/ - -/** @pred matlab_initialized_cells(+ _SizeX_, + _SizeY_, + _List_, ? _Array_) - - -MATLAB will create an array of cells of size _SizeX_ and - _SizeY_, initialized from the list _List_, and if _Array_ -is bound to an atom, store the array in the matlab variable with name - _Array_. - - -*/ - -/** @pred matlab_matrix(+ _SizeX_, + _SizeY_, + _List_, ? _Array_) - - -MATLAB will create an array of floats of size _SizeX_ and _SizeY_, -initialized from the list _List_, and if _Array_ is bound to -an atom, store the array in the matlab variable with name _Array_. - - -*/ - -/** @pred matlab_set(+ _MatVar_, + _X_, + _Y_, + _Value_) - - -Call MATLAB to set element _MatVar_( _X_, _Y_) to - _Value_. Notice that this command uses the MATLAB array access -convention. - - -*/ - -/** @pred matlab_get_variable(+ _MatVar_, - _List_) - - -Unify MATLAB variable _MatVar_ with the List _List_. - - -*/ - -/** @pred matlab_item(+ _MatVar_, + _X_, ? _Val_) - - -Read or set MATLAB _MatVar_( _X_) from/to _Val_. Use -`C` notation for matrix access (ie, starting from 0). - - -*/ - -/** @pred matlab_item(+ _MatVar_, + _X_, + _Y_, ? _Val_) - -Read or set MATLAB _MatVar_( _X_, _Y_) from/to _Val_. Use -`C` notation for matrix access (ie, starting from 0). - - -*/ - -/** @pred matlab_item1(+ _MatVar_, + _X_, ? _Val_) - - -Read or set MATLAB _MatVar_( _X_) from/to _Val_. Use -MATLAB notation for matrix access (ie, starting from 1). - - -*/ - -/** @pred matlab_item1(+ _MatVar_, + _X_, + _Y_, ? _Val_) - -Read or set MATLAB _MatVar_( _X_, _Y_) from/to _Val_. Use -MATLAB notation for matrix access (ie, starting from 1). - - -*/ - -/** @pred matlab_sequence(+ _Min_, + _Max_, ? _Array_) - - -MATLAB will create a sequence going from _Min_ to _Max_, and -if _Array_ is bound to an atom, store the sequence in the matlab -variable with name _Array_. - - -*/ - -/** @pred matlab_vector(+ _Size_, + _List_, ? _Array_) - - -MATLAB will create a vector of floats of size _Size_, initialized -from the list _List_, and if _Array_ is bound to an atom, -store the array in the matlab variable with name _Array_. - - -*/ - -/** @pred matlab_zeros(+ _Size_, ? _Array_) - - -MATLAB will create a vector of zeros of size _Size_, and if - _Array_ is bound to an atom, store the array in the matlab -variable with name _Array_. Corresponds to the MATLAB command -`zeros`. - - -*/ - -/** @pred matlab_zeros(+ _SizeX_, + _SizeY_, ? _Array_) - -MATLAB will create an array of zeros of size _SizeX_ and - _SizeY_, and if _Array_ is bound to an atom, store the array -in the matlab variable with name _Array_. Corresponds to the -MATLAB command `zeros`. - - -*/ - -/** @pred matlab_zeros(+ _SizeX_, + _SizeY_, + _SizeZ_, ? _Array_) - -MATLAB will create an array of zeros of size _SizeX_, _SizeY_, -and _SizeZ_. If _Array_ is bound to an atom, store the array -in the matlab variable with name _Array_. Corresponds to the -MATLAB command `zeros`. - - - - -@} */ - -/** @defgroup NonhYBacktrackable_Data_Structures Non-Backtrackable Data Structures -@ingroup YAPLibrary -@{ - -The following routines implement well-known data-structures using global -non-backtrackable variables (implemented on the Prolog stack). The -data-structures currently supported are Queues, Heaps, and Beam for Beam -search. They are allowed through `library(nb)`. - - -*/ - -/** @pred nb_queue(- _Queue_) - - -Create a _Queue_. - - -*/ - -/** @pred nb_queue_close(+ _Queue_, - _Head_, ? _Tail_) - - -Unify the queue _Queue_ with a difference list - _Head_- _Tail_. The queue will now be empty and no further -elements can be added. - - -*/ - -/** @pred nb_queue_enqueue(+ _Queue_, + _Element_) - - -Add _Element_ to the front of the queue _Queue_. - - -*/ - -/** @pred nb_queue_dequeue(+ _Queue_, - _Element_) - - -Remove _Element_ from the front of the queue _Queue_. Fail if -the queue is empty. - - -*/ - -/** @pred nb_queue_peek(+ _Queue_, - _Element_) - - - _Element_ is the front of the queue _Queue_. Fail if -the queue is empty. - - -*/ - -/** @pred nb_queue_size(+ _Queue_, - _Size_) - - -Unify _Size_ with the number of elements in the queue _Queue_. - - -*/ - -/** @pred nb_queue_empty(+ _Queue_) - - -Succeeds if _Queue_ is empty. - - -*/ - -/** @pred nb_heap(+ _DefaultSize_,- _Heap_) - - -Create a _Heap_ with default size _DefaultSize_. Note that size -will expand as needed. - - -*/ - -/** @pred nb_heap_close(+ _Heap_) - - -Close the heap _Heap_: no further elements can be added. - - -*/ - -/** @pred nb_heap_add(+ _Heap_, + _Key_, + _Value_) - - -Add _Key_- _Value_ to the heap _Heap_. The key is sorted on - _Key_ only. - - -*/ - -/** @pred nb_heap_del(+ _Heap_, - _Key_, - _Value_) - - -Remove element _Key_- _Value_ with smallest _Value_ in heap - _Heap_. Fail if the heap is empty. - - -*/ - -/** @pred nb_heap_peek(+ _Heap_, - _Key_, - _Value_)) - - - _Key_- _Value_ is the element with smallest _Key_ in the heap - _Heap_. Fail if the heap is empty. - - -*/ - -/** @pred nb_heap_size(+ _Heap_, - _Size_) - - -Unify _Size_ with the number of elements in the heap _Heap_. - - -*/ - -/** @pred nb_heap_empty(+ _Heap_) - - -Succeeds if _Heap_ is empty. - - -*/ - -/** @pred nb_beam(+ _DefaultSize_,- _Beam_) - - -Create a _Beam_ with default size _DefaultSize_. Note that size -is fixed throughout. - - -*/ - -/** @pred nb_beam_close(+ _Beam_) - - -Close the beam _Beam_: no further elements can be added. - - -*/ - -/** @pred nb_beam_add(+ _Beam_, + _Key_, + _Value_) - - -Add _Key_- _Value_ to the beam _Beam_. The key is sorted on - _Key_ only. - - -*/ - -/** @pred nb_beam_del(+ _Beam_, - _Key_, - _Value_) - - -Remove element _Key_- _Value_ with smallest _Value_ in beam - _Beam_. Fail if the beam is empty. - - -*/ - -/** @pred nb_beam_peek(+ _Beam_, - _Key_, - _Value_)) - - - _Key_- _Value_ is the element with smallest _Key_ in the beam - _Beam_. Fail if the beam is empty. - - -*/ - -/** @pred nb_beam_size(+ _Beam_, - _Size_) - - -Unify _Size_ with the number of elements in the beam _Beam_. - - -*/ - -/** @pred nb_beam_empty(+ _Beam_) - - -Succeeds if _Beam_ is empty. - - - - -@} */ - -/** @defgroup Ordered_Sets Ordered Sets -@ingroup YAPLibrary -@{ - -The following ordered set manipulation routines are available once -included with the `use_module(library(ordsets))` command. An -ordered set is represented by a list having unique and ordered -elements. Output arguments are guaranteed to be ordered sets, if the -relevant inputs are. This is a slightly patched version of Richard -O'Keefe's original library. - - -*/ - -/** @pred list_to_ord_set(+ _List_, ? _Set_) - - -Holds when _Set_ is the ordered representation of the set -represented by the unordered representation _List_. - - -*/ - -/** @pred merge(+ _List1_, + _List2_, - _Merged_) - - -Holds when _Merged_ is the stable merge of the two given lists. - -Notice that merge/3 will not remove duplicates, so merging -ordered sets will not necessarily result in an ordered set. Use -`ord_union/3` instead. - - -*/ - -/** @pred ord_add_element(+ _Set1_, + _Element_, ? _Set2_) - - -Inserting _Element_ in _Set1_ returns _Set2_. It should give -exactly the same result as `merge(Set1, [Element], Set2)`, but a -bit faster, and certainly more clearly. The same as ord_insert/3. - - -*/ - -/** @pred ord_del_element(+ _Set1_, + _Element_, ? _Set2_) - - -Removing _Element_ from _Set1_ returns _Set2_. - - -*/ - -/** @pred ord_disjoint(+ _Set1_, + _Set2_) - - -Holds when the two ordered sets have no element in common. - - -*/ - -/** @pred ord_member(+ _Element_, + _Set_) - - -Holds when _Element_ is a member of _Set_. - - -*/ - -/** @pred ord_insert(+ _Set1_, + _Element_, ? _Set2_) - - -Inserting _Element_ in _Set1_ returns _Set2_. It should give -exactly the same result as `merge(Set1, [Element], Set2)`, but a -bit faster, and certainly more clearly. The same as ord_add_element/3. - - -*/ - -/** @pred ord_intersect(+ _Set1_, + _Set2_) - - -Holds when the two ordered sets have at least one element in common. - - -*/ - -/** @pred ord_intersection(+ _Set1_, + _Set2_, ? _Intersection_) - -Holds when Intersection is the ordered representation of _Set1_ -and _Set2_. - - -*/ - -/** @pred ord_intersection(+ _Set1_, + _Set2_, ? _Intersection_, ? _Diff_) - -Holds when Intersection is the ordered representation of _Set1_ -and _Set2_. _Diff_ is the difference between _Set2_ and _Set1_. - - -*/ - -/** @pred ord_seteq(+ _Set1_, + _Set2_) - - -Holds when the two arguments represent the same set. - - -*/ - -/** @pred ord_setproduct(+ _Set1_, + _Set2_, - _Set_) - - -If Set1 and Set2 are ordered sets, Product will be an ordered -set of x1-x2 pairs. - - -*/ - -/** @pred ord_subset(+ _Set1_, + _Set2_) - - -Holds when every element of the ordered set _Set1_ appears in the -ordered set _Set2_. - - -*/ - -/** @pred ord_subtract(+ _Set1_, + _Set2_, ? _Difference_) - - -Holds when _Difference_ contains all and only the elements of _Set1_ -which are not also in _Set2_. - - -*/ - -/** @pred ord_symdiff(+ _Set1_, + _Set2_, ? _Difference_) - - -Holds when _Difference_ is the symmetric difference of _Set1_ -and _Set2_. - - -*/ - -/** @pred ord_union(+ _Sets_, ? _Union_) - - -Holds when _Union_ is the union of the lists _Sets_. - - -*/ - -/** @pred ord_union(+ _Set1_, + _Set2_, ? _Union_) - -Holds when _Union_ is the union of _Set1_ and _Set2_. - - -*/ - -/** @pred ord_union(+ _Set1_, + _Set2_, ? _Union_, ? _Diff_) - -Holds when _Union_ is the union of _Set1_ and _Set2_ and - _Diff_ is the difference. - - - - -@} */ - -/** @defgroup Pseudo_Random Pseudo Random Number Integer Generator -@ingroup YAPLibrary -@{ - -The following routines produce random non-negative integers in the range -0 .. 2^(w-1) -1, where w is the word size available for integers, e.g. -32 for Intel machines and 64 for Alpha machines. Note that the numbers -generated by this random number generator are repeatable. This generator -was originally written by Allen Van Gelder and is based on Knuth Vol 2. - - -*/ - -/** @pred rannum(- _I_) - - -Produces a random non-negative integer _I_ whose low bits are not -all that random, so it should be scaled to a smaller range in general. -The integer _I_ is in the range 0 .. 2^(w-1) - 1. You can use: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -rannum(X) :- yap_flag(max_integer,MI), rannum(R), X is R/MI. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -to obtain a floating point number uniformly distributed between 0 and 1. - - -*/ - -/** @pred ranstart - - -Initialize the random number generator using a built-in seed. The -ranstart/0 built-in is always called by the system when loading -the package. - - -*/ - -/** @pred ranstart(+ _Seed_) - -Initialize the random number generator with user-defined _Seed_. The -same _Seed_ always produces the same sequence of numbers. - - -*/ - -/** @pred ranunif(+ _Range_,- _I_) - - -ranunif/2 produces a uniformly distributed non-negative random -integer _I_ over a caller-specified range _R_. If range is _R_, -the result is in 0 .. _R_-1. - - - - -@} */ - -/** @defgroup Queues Queues -@ingroup YAPLibrary -@{ - -The following queue manipulation routines are available once -included with the `use_module(library(queues))` command. Queues are -implemented with difference lists. - - - - @pred make_queue(+ _Queue_) - - -Creates a new empty queue. It should only be used to create a new queue. - - -*/ - -/** @pred join_queue(+ _Element_, + _OldQueue_, - _NewQueue_) - - -Adds the new element at the end of the queue. - - -*/ - -/** @pred list_join_queue(+ _List_, + _OldQueue_, - _NewQueue_) - - -Ads the new elements at the end of the queue. - - -*/ - -/** @pred jump_queue(+ _Element_, + _OldQueue_, - _NewQueue_) - - -Adds the new element at the front of the list. - - -*/ - -/** @pred list_jump_queue(+ _List_, + _OldQueue_, + _NewQueue_) - - -Adds all the elements of _List_ at the front of the queue. - - -*/ - -/** @pred head_queue(+ _Queue_, ? _Head_) - - -Unifies Head with the first element of the queue. - - -*/ - -/** @pred serve_queue(+ _OldQueue_, + _Head_, - _NewQueue_) - - -Removes the first element of the queue for service. - - -*/ - -/** @pred empty_queue(+ _Queue_) - - -Tests whether the queue is empty. - - -*/ - -/** @pred length_queue(+ _Queue_, - _Length_) - - -Counts the number of elements currently in the queue. - - -*/ - -/** @pred list_to_queue(+ _List_, - _Queue_) - - -Creates a new queue with the same elements as _List._ - - -*/ - -/** @pred queue_to_list(+ _Queue_, - _List_) - - -Creates a new list with the same elements as _Queue_. - - - - -@} */ - -/** @defgroup Random Random Number Generator -@ingroup YAPLibrary -@{ - -The following random number operations are included with the -`use_module(library(random))` command. Since YAP-4.3.19 YAP uses -the O'Keefe public-domain algorithm, based on the "Applied Statistics" -algorithm AS183. - - - - @pred getrand(- _Key_) - - -Unify _Key_ with a term of the form `rand(X,Y,Z)` describing the -current state of the random number generator. - - -*/ - -/** @pred random(- _Number_) - - -Unify _Number_ with a floating-point number in the range `[0...1)`. - - -*/ - -/** @pred random(+ _LOW_, + _HIGH_, - _NUMBER_) - -Unify _Number_ with a number in the range -`[LOW...HIGH)`. If both _LOW_ and _HIGH_ are -integers then _NUMBER_ will also be an integer, otherwise - _NUMBER_ will be a floating-point number. - - -*/ - -/** @pred randseq(+ _LENGTH_, + _MAX_, - _Numbers_) - - -Unify _Numbers_ with a list of _LENGTH_ unique random integers -in the range `[1... _MAX_)`. - - -*/ - -/** @pred randset(+ _LENGTH_, + _MAX_, - _Numbers_) - - -Unify _Numbers_ with an ordered list of _LENGTH_ unique random -integers in the range `[1... _MAX_)`. - - -*/ - -/** @pred setrand(+ _Key_) - - -Use a term of the form `rand(X,Y,Z)` to set a new state for the -random number generator. The integer `X` must be in the range -`[1...30269)`, the integer `Y` must be in the range -`[1...30307)`, and the integer `Z` must be in the range -`[1...30323)`. - - - - -@} */ - -/** @defgroup Read_Utilities Read Utilities -@ingroup YAPLibrary -@{ - -The `readutil` library contains primitives to read lines, files, -multiple terms, etc. - - -*/ - -/** @pred read_line_to_codes(+ _Stream_, - _Codes_) - - - -Read the next line of input from _Stream_ and unify the result with - _Codes_ after the line has been read. A line is ended by a -newline character or end-of-file. Unlike `read_line_to_codes/3`, -this predicate removes trailing newline character. - -On end-of-file the atom `end_of_file` is returned. See also -`at_end_of_stream/[0,1]`. - - -*/ - -/** @pred read_line_to_codes(+ _Stream_, - _Codes_, ? _Tail_) - -Difference-list version to read an input line to a list of character -codes. Reading stops at the newline or end-of-file character, but -unlike read_line_to_codes/2, the newline is retained in the -output. This predicate is especially useful for reading a block of -lines upto some delimiter. The following example reads an HTTP header -ended by a blank line: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -read_header_data(Stream, Header) :- - read_line_to_codes(Stream, Header, Tail), - read_header_data(Header, Stream, Tail). - -read_header_data("\r\n", _, _) :- !. -read_header_data("\n", _, _) :- !. -read_header_data("", _, _) :- !. -read_header_data(_, Stream, Tail) :- - read_line_to_codes(Stream, Tail, NewTail), - read_header_data(Tail, Stream, NewTail). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred read_stream_to_codes(+ _Stream_, - _Codes_) - - -Read all input until end-of-file and unify the result to _Codes_. - - -*/ - -/** @pred read_stream_to_codes(+ _Stream_, - _Codes_, ? _Tail_) - -Difference-list version of read_stream_to_codes/2. - - -*/ - -/** @pred read_file_to_codes(+ _Spec_, - _Codes_, + _Options_) - - -Read a file to a list of character codes. Currently ignores - _Options_. - - -*/ - -/** @pred read_file_to_terms(+ _Spec_, - _Terms_, + _Options_) - - -Read a file to a list of Prolog terms (see read/1). @c _Spec_ is a - - - - - - - - - -@} */ - -/** @defgroup RedhYBlack_Trees Red-Black Trees -@ingroup YAPLibrary -@{ - -Red-Black trees are balanced search binary trees. They are named because -nodes can be classified as either red or black. The code we include is -based on "Introduction to Algorithms", second edition, by Cormen, -Leiserson, Rivest and Stein. The library includes routines to insert, -lookup and delete elements in the tree. - - -*/ - -/** @pred rb_new(? _T_) - - -Create a new tree. - - -*/ - -/** @pred rb_empty(? _T_) - - -Succeeds if tree _T_ is empty. - - -*/ - -/** @pred is_rbtree(+ _T_) - - -Check whether _T_ is a valid red-black tree. - - -*/ - -/** @pred rb_insert(+ _T0_,+ _Key_,? _Value_,+ _TF_) - - -Add an element with key _Key_ and _Value_ to the tree - _T0_ creating a new red-black tree _TF_. Duplicated elements are not -allowed. - -Add a new element with key _Key_ and _Value_ to the tree - _T0_ creating a new red-black tree _TF_. Fails is an element -with _Key_ exists in the tree. - - -*/ - -/** @pred rb_lookup(+ _Key_,- _Value_,+ _T_) - - -Backtrack through all elements with key _Key_ in the red-black tree - _T_, returning for each the value _Value_. - - -*/ - -/** @pred rb_lookupall(+ _Key_,- _Value_,+ _T_) - - -Lookup all elements with key _Key_ in the red-black tree - _T_, returning the value _Value_. - - -*/ - -/** @pred rb_delete(+ _T_,+ _Key_,- _TN_) - - -Delete element with key _Key_ from the tree _T_, returning a new -tree _TN_. - - -*/ - -/** @pred rb_delete(+ _T_,+ _Key_,- _Val_,- _TN_) - -Delete element with key _Key_ from the tree _T_, returning the -value _Val_ associated with the key and a new tree _TN_. - - -*/ - -/** @pred rb_del_min(+ _T_,- _Key_,- _Val_,- _TN_) - - -Delete the least element from the tree _T_, returning the key - _Key_, the value _Val_ associated with the key and a new tree - _TN_. - - -*/ - -/** @pred rb_del_max(+ _T_,- _Key_,- _Val_,- _TN_) - - -Delete the largest element from the tree _T_, returning the key - _Key_, the value _Val_ associated with the key and a new tree - _TN_. - - -*/ - -/** @pred rb_update(+ _T_,+ _Key_,+ _NewVal_,- _TN_) - - -Tree _TN_ is tree _T_, but with value for _Key_ associated -with _NewVal_. Fails if it cannot find _Key_ in _T_. - - -*/ - -/** @pred rb_apply(+ _T_,+ _Key_,+ _G_,- _TN_) - - -If the value associated with key _Key_ is _Val0_ in _T_, and -if `call(G,Val0,ValF)` holds, then _TN_ differs from - _T_ only in that _Key_ is associated with value _ValF_ in -tree _TN_. Fails if it cannot find _Key_ in _T_, or if -`call(G,Val0,ValF)` is not satisfiable. - - -*/ - -/** @pred rb_visit(+ _T_,- _Pairs_) - - - _Pairs_ is an infix visit of tree _T_, where each element of - _Pairs_ is of the form _K_- _Val_. - - -*/ - -/** @pred rb_size(+ _T_,- _Size_) - - - _Size_ is the number of elements in _T_. - - -*/ - -/** @pred rb_keys(+ _T_,+ _Keys_) - - - _Keys_ is an infix visit with all keys in tree _T_. Keys will be -sorted, but may be duplicate. - - -*/ - -/** @pred rb_map(+ _T_,+ _G_,- _TN_) - - -For all nodes _Key_ in the tree _T_, if the value associated with -key _Key_ is _Val0_ in tree _T_, and if -`call(G,Val0,ValF)` holds, then the value associated with _Key_ -in _TN_ is _ValF_. Fails if or if `call(G,Val0,ValF)` is not -satisfiable for all _Var0_. - - -*/ - -/** @pred rb_partial_map(+ _T_,+ _Keys_,+ _G_,- _TN_) - - -For all nodes _Key_ in _Keys_, if the value associated with key - _Key_ is _Val0_ in tree _T_, and if `call(G,Val0,ValF)` -holds, then the value associated with _Key_ in _TN_ is - _ValF_. Fails if or if `call(G,Val0,ValF)` is not satisfiable -for all _Var0_. Assumes keys are not repeated. - - -*/ - -/** @pred rb_fold(+ _T_,+ _G_,+ _Acc0_, - _AccF_) - - -For all nodes _Key_ in the tree _T_, if the value -associated with key _Key_ is _V_ in tree _T_, if -`call(G,V,Acc1,Acc2)` holds, then if _VL_ is value of the -previous node in inorder, `call(G,VL,_,Acc0)` must hold, and if - _VR_ is the value of the next node in inorder, -`call(G,VR,Acc1,_)` must hold. - - -*/ - -/** @pred rb_key_fold(+ _T_,+ _G_,+ _Acc0_, - _AccF_) - - -For all nodes _Key_ in the tree _T_, if the value -associated with key _Key_ is _V_ in tree _T_, if -`call(G,Key,V,Acc1,Acc2)` holds, then if _VL_ is value of the -previous node in inorder, `call(G,KeyL,VL,_,Acc0)` must hold, and if - _VR_ is the value of the next node in inorder, -`call(G,KeyR,VR,Acc1,_)` must hold. - - -*/ - -/** @pred rb_clone(+ _T_,+ _NT_,+ _Nodes_) - - -``Clone'' the red-back tree into a new tree with the same keys as the -original but with all values set to unbound values. Nodes is a list -containing all new nodes as pairs _K-V_. - - -*/ - -/** @pred rb_min(+ _T_,- _Key_,- _Value_) - - - _Key_ is the minimum key in _T_, and is associated with _Val_. - - -*/ - -/** @pred rb_max(+ _T_,- _Key_,- _Value_) - - - _Key_ is the maximal key in _T_, and is associated with _Val_. - - -*/ - -/** @pred rb_next(+ _T_, + _Key_,- _Next_,- _Value_) - - - _Next_ is the next element after _Key_ in _T_, and is -associated with _Val_. - - -*/ - -/** @pred rb_previous(+ _T_, + _Key_,- _Previous_,- _Value_) - - - _Previous_ is the previous element after _Key_ in _T_, and is -associated with _Val_. - - -*/ - -/** @pred ord_list_to_rbtree(+ _L_, - _T_) - - - _T_ is the red-black tree corresponding to the mapping in ordered -list _L_. - - - -@} */ - -/** @defgroup RegExp Regular Expressions -@ingroup YAPLibrary -@{ - -This library includes routines to determine whether a regular expression -matches part or all of a string. The routines can also return which -parts parts of the string matched the expression or subexpressions of -it. This library relies on Henry Spencer's `C`-package and is only -available in operating systems that support dynamic loading. The -`C`-code has been obtained from the sources of FreeBSD-4.0 and is -protected by copyright from Henry Spencer and from the Regents of the -University of California (see the file library/regex/COPYRIGHT for -further details). - -Much of the description of regular expressions below is copied verbatim -from Henry Spencer's manual page. - -A regular expression is zero or more branches, separated by ``|''. It -matches anything that matches one of the branches. - -A branch is zero or more pieces, concatenated. It matches a match for -the first, followed by a match for the second, etc. - -A piece is an atom possibly followed by ``\*'', ``+'', or ``?''. An atom -followed by ``\*'' matches a sequence of 0 or more matches of the atom. -An atom followed by ``+'' matches a sequence of 1 or more matches of the -atom. An atom followed by ``?'' matches a match of the atom, or the -null string. - -An atom is a regular expression in parentheses (matching a match for the -regular expression), a range (see below), ``.'' (matching any single -character), ``^'' (matching the null string at the beginning of the -input string), ``$'' (matching the null string at the end of the input -string), a ``\\'' followed by a single character (matching that -character), or a single character with no other significance (matching -that character). - -A range is a sequence of characters enclosed in ``[]''. It normally -matches any single character from the sequence. If the sequence begins -with ``^'', it matches any single character not from the rest of the -sequence. If two characters in the sequence are separated by ``-'', -this is shorthand for the full list of ASCII characters between them -(e.g. ``[0-9]'' matches any decimal digit). To include a literal ``]'' -in the sequence, make it the first character (following a possible -``^''). To include a literal ``-'', make it the first or last -character. - - - - @pred regexp(+ _RegExp_,+ _String_,+ _Opts_) - - - -Match regular expression _RegExp_ to input string _String_ -according to options _Opts_. The options may be: - - + `nocase`: Causes upper-case characters in _String_ to -be treated as lower case during the matching process. - - - -*/ - -/** @pred regexp(+ _RegExp_,+ _String_,+ _Opts_,? _SubMatchVars_) - - -Match regular expression _RegExp_ to input string _String_ -according to options _Opts_. The variable _SubMatchVars_ should -be originally unbound or a list of unbound variables all will contain a -sequence of matches, that is, the head of _SubMatchVars_ will -contain the characters in _String_ that matched the leftmost -parenthesized subexpression within _RegExp_, the next head of list -will contain the characters that matched the next parenthesized -subexpression to the right in _RegExp_, and so on. - -The options may be: - - + `nocase`: Causes upper-case characters in _String_ to -be treated as lower case during the matching process. - + `indices`: Changes what is stored in - _SubMatchVars_. Instead of storing the matching characters from - _String_, each variable will contain a term of the form _IO-IF_ -giving the indices in _String_ of the first and last characters in -the matching range of characters. - - - -In general there may be more than one way to match a regular expression -to an input string. For example, consider the command - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - regexp("(a*)b*","aabaaabb", [], [X,Y]) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Considering only the rules given so far, _X_ and _Y_ could end up -with the values `"aabb"` and `"aa"`, `"aaab"` and -`"aaa"`, `"ab"` and `"a"`, or any of several other -combinations. To resolve this potential ambiguity `regexp` chooses among -alternatives using the rule ``first then longest''. In other words, it -considers the possible matches in order working from left to right -across the input string and the pattern, and it attempts to match longer -pieces of the input string before shorter ones. More specifically, the -following rules apply in decreasing order of priority: - -
        - + If a regular expression could match two different parts of an -input string then it will match the one that begins earliest. - - + If a regular expression contains "|" operators then the leftmost matching sub-expression is chosen. - - + In \*, +, and ? constructs, longer matches are chosen in preference to shorter ones. - - + In sequences of expression components the components are considered from left to right. -
      - -In the example from above, `"(a\*)b\*"` matches `"aab"`: the -`"(a\*)"` portion of the pattern is matched first and it consumes -the leading `"aa"`; then the `"b\*"` portion of the pattern -consumes the next `"b"`. Or, consider the following example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - regexp("(ab|a)(b*)c", "abc", [], [X,Y,Z]) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -After this command _X_ will be `"abc"`, _Y_ will be -`"ab"`, and _Z_ will be an empty string. Rule 4 specifies that -`"(ab|a)"` gets first shot at the input string and Rule 2 specifies -that the `"ab"` sub-expression is checked before the `"a"` -sub-expression. Thus the `"b"` has already been claimed before the -`"(b\*)"` component is checked and `(b\*)` must match an empty string. - - - - -@} */ - -/** @defgroup shlib SWI-Prolog's shlib library -@ingroup YAPLibrary -@{ - -This section discusses the functionality of the (autoload) -`library(shlib)`, providing an interface to manage shared -libraries. - -One of the files provides a global function `install_mylib()` that -initialises the module using calls to `PL_register_foreign()`. Here is a -simple example file `mylib.c`, which creates a Windows MessageBox: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c} -#include -#include - -static foreign_t -pl_say_hello(term_t to) -{ char *a; - - if ( PL_get_atom_chars(to, &a) ) - { MessageBox(NULL, a, "DLL test", MB_OK|MB_TASKMODAL); - - PL_succeed; - } - - PL_fail; -} - -install_t -install_mylib() -{ PL_register_foreign("say_hello", 1, pl_say_hello, 0); -} -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Now write a file mylib.pl: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(mylib, [ say_hello/1 ]). -:- use_foreign_library(foreign(mylib)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The file mylib.pl can be loaded as a normal Prolog file and provides the predicate defined in C. - - -*/ - -/** @pred load_foreign_library(: _FileSpec_) is det - - - -*/ - -/** @pred load_foreign_library(: _FileSpec_, + _Entry_:atom) is det - -Load a shared object or DLL. After loading the _Entry_ function is -called without arguments. The default entry function is composed -from `install_`, followed by the file base-name. E.g., the -load-call below calls the function `install_mylib()`. If the platform -prefixes extern functions with `_`, this prefix is added before -calling. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ... - load_foreign_library(foreign(mylib)), - ... -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - _FileSpec_ is a specification for -absolute_file_name/3. If searching the file fails, the plain -name is passed to the OS to try the default method of the OS for -locating foreign objects. The default definition of -file_search_path/2 searches \/lib/Yap. - -See also -`use_foreign_library/1,2` are intended for use in -directives. - - -*/ - -/** @pred [det] use_foreign_library(+ _FileSpec_), use_foreign_library(+ _FileSpec_, + _Entry_:atom) - - - -Load and install a foreign library as load_foreign_library/1 -and `load_foreign_library/2` and -register the installation using `initialization/2` with the option -now. This is similar to using: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :- initialization(load_foreign_library(foreign(mylib))). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -but using the initialization/1 wrapper causes the library to -be loaded after loading of the file in which it appears is -completed, while use_foreign_library/1 loads the library -immediately. I.e. the difference is only relevant if the remainder -of the file uses functionality of the `C`-library. - - -*/ - -/** @pred [det]unload_foreign_library(+ _FileSpec_) - -*/ - -/** @pred [det]unload_foreign_library(+ _FileSpec_, + _Exit_:atom) - - - - -Unload a shared -object or DLL. After calling the _Exit_ function, the shared object is -removed from the process. The default exit function is composed from -`uninstall_`, followed by the file base-name. - - -*/ - -/** @pred current_foreign_library(? _File_, ? _Public_) - - - -Query currently -loaded shared libraries. - - - - -@} */ - -/** @defgroup Splay_Trees Splay Trees -@ingroup YAPLibrary -@{ - -Splay trees are explained in the paper "Self-adjusting Binary Search -Trees", by D.D. Sleator and R.E. Tarjan, JACM, vol. 32, No.3, July 1985, -p. 668. They are designed to support fast insertions, deletions and -removals in binary search trees without the complexity of traditional -balanced trees. The key idea is to allow the tree to become -unbalanced. To make up for this, whenever we find a node, we move it up -to the top. We use code by Vijay Saraswat originally posted to the Prolog -mailing-list. - - - - @pred splay_access(- _Return_,+ _Key_,? _Val_,+ _Tree_,- _NewTree_) - - -If item _Key_ is in tree _Tree_, return its _Val_ and -unify _Return_ with `true`. Otherwise unify _Return_ with -`null`. The variable _NewTree_ unifies with the new tree. - - -*/ - -/** @pred splay_delete(+ _Key_,? _Val_,+ _Tree_,- _NewTree_) - - -Delete item _Key_ from tree _Tree_, assuming that it is present -already. The variable _Val_ unifies with a value for key _Key_, -and the variable _NewTree_ unifies with the new tree. The predicate -will fail if _Key_ is not present. - - -*/ - -/** @pred splay_init(- _NewTree_) - - -Initialize a new splay tree. - - -*/ - -/** @pred splay_insert(+ _Key_,? _Val_,+ _Tree_,- _NewTree_) - - -Insert item _Key_ in tree _Tree_, assuming that it is not -there already. The variable _Val_ unifies with a value for key - _Key_, and the variable _NewTree_ unifies with the new -tree. In our implementation, _Key_ is not inserted if it is -already there: rather it is unified with the item already in the tree. - - -*/ - -/** @pred splay_join(+ _LeftTree_,+ _RighTree_,- _NewTree_) - - -Combine trees _LeftTree_ and _RighTree_ into a single -tree _NewTree_ containing all items from both trees. This operation -assumes that all items in _LeftTree_ are less than all those in - _RighTree_ and destroys both _LeftTree_ and _RighTree_. - - -*/ - -/** @pred splay_split(+ _Key_,? _Val_,+ _Tree_,- _LeftTree_,- _RightTree_) - - -Construct and return two trees _LeftTree_ and _RightTree_, -where _LeftTree_ contains all items in _Tree_ less than - _Key_, and _RightTree_ contains all items in _Tree_ -greater than _Key_. This operations destroys _Tree_. - - - - -@} */ - -/** @defgroup String_InputOutput Reading From and Writing To Strings -@ingroup YAPLibrary -@{ - -From Version 4.3.2 onwards YAP implements SICStus Prolog compatible -String Input/Output. The library allows users to read from and write to a memory -buffer as if it was a file. The memory buffer is built from or converted -to a string of character codes by the routines in library. Therefore, if -one wants to read from a string the string must be fully instantiated -before the library built-in opens the string for reading. These commands -are available through the `use_module(library(charsio))` command. - - - - @pred format_to_chars(+ _Form_, + _Args_, - _Result_) - - - -Execute the built-in procedure format/2 with form _Form_ and -arguments _Args_ outputting the result to the string of character -codes _Result_. - - -*/ - -/** @pred format_to_chars(+ _Form_, + _Args_, - _Result_, - _Result0_) - - -Execute the built-in procedure format/2 with form _Form_ and -arguments _Args_ outputting the result to the difference list of -character codes _Result-Result0_. - - -*/ - -/** @pred write_to_chars(+ _Term_, - _Result_) - - - -Execute the built-in procedure write/1 with argument _Term_ -outputting the result to the string of character codes _Result_. - - -*/ - -/** @pred write_to_chars(+ _Term_, - _Result0_, - _Result_) - - -Execute the built-in procedure write/1 with argument _Term_ -outputting the result to the difference list of character codes - _Result-Result0_. - - -*/ - -/** @pred atom_to_chars(+ _Atom_, - _Result_) - - - -Convert the atom _Atom_ to the string of character codes - _Result_. - - -*/ - -/** @pred atom_to_chars(+ _Atom_, - _Result0_, - _Result_) - - -Convert the atom _Atom_ to the difference list of character codes - _Result-Result0_. - - -*/ - -/** @pred number_to_chars(+ _Number_, - _Result_) - - - -Convert the number _Number_ to the string of character codes - _Result_. - - -*/ - -/** @pred number_to_chars(+ _Number_, - _Result0_, - _Result_) - - -Convert the atom _Number_ to the difference list of character codes - _Result-Result0_. - - -*/ - -/** @pred atom_to_term(+ _Atom_, - _Term_, - _Bindings_) - - -Use _Atom_ as input to read_term/2 using the option `variable_names` and return the read term in _Term_ and the variable bindings in _Bindings_. _Bindings_ is a list of `Name = Var` couples, thus providing access to the actual variable names. See also read_term/2. If Atom has no valid syntax, a syntax_error exception is raised. - - -*/ - -/** @pred term_to_atom(? _Term_, ? _Atom_) - - -True if _Atom_ describes a term that unifies with _Term_. When - _Atom_ is instantiated _Atom_ is converted and then unified with - _Term_. If _Atom_ has no valid syntax, a syntax_error exception -is raised. Otherwise _Term_ is ``written'' on _Atom_ using -write_term/2 with the option quoted(true). - - -*/ - -/** @pred read_from_chars(+ _Chars_, - _Term_) - - - -Parse the list of character codes _Chars_ and return the result in -the term _Term_. The character codes to be read must terminate with -a dot character such that either (i) the dot character is followed by -blank characters; or (ii) the dot character is the last character in the -string. - - -*/ - -/** @pred open_chars_stream(+ _Chars_, - _Stream_) - - - -Open the list of character codes _Chars_ as a stream _Stream_. - - -*/ - -/** @pred with_output_to_chars(? _Goal_, - _Chars_) - - - -Execute goal _Goal_ such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the list of character codes _Chars_. - - -*/ - -/** @pred with_output_to_chars(? _Goal_, ? _Chars0_, - _Chars_) - - -Execute goal _Goal_ such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the difference list of character codes - _Chars-Chars0_. - - -*/ - -/** @pred with_output_to_chars(? _Goal_, - _Stream_, ? _Chars0_, - _Chars_) - - -Execute goal _Goal_ such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the difference list of character codes - _Chars-Chars0_ and _Stream_ receives the stream corresponding to -the memory buffer. - - - -The implementation of the character IO operations relies on three YAP -built-ins: - - - - @pred charsio:open_mem_read_stream(+ _String_, - _Stream_) -Store a string in a memory buffer and output a stream that reads from this -memory buffer. - - -*/ - -/** @pred charsio:open_mem_write_stream(- _Stream_) -Create a new memory buffer and output a stream that writes to it. - - -*/ - -/** @pred charsio:peek_mem_write_stream(- _Stream_, L0, L) -Convert the memory buffer associated with stream _Stream_ to the -difference list of character codes _L-L0_. - - -These built-ins are initialized to belong to the module `charsio` in -`init.yap`. Novel procedures for manipulating strings by explicitly -importing these built-ins. - -YAP does not currently support opening a `charsio` stream in -`append` mode, or seeking in such a stream. - - -@} */ - -/** @defgroup System Calling The Operating System from YAP -@ingroup YAPLibrary -@{ - -YAP now provides a library of system utilities compatible with the -SICStus Prolog system library. This library extends and to some point -replaces the functionality of Operating System access routines. The -library includes Unix/Linux and Win32 `C` code. They -are available through the `use_module(library(system))` command. - - - - @pred datime(datime(- _Year_, - _Month_, - _DayOfTheMonth_, - -- _Hour_, - _Minute_, - _Second_) - -The datime/1 procedure returns the current date and time, with -information on _Year_, _Month_, _DayOfTheMonth_, - _Hour_, _Minute_, and _Second_. The _Hour_ is returned -on local time. This function uses the WIN32 -`GetLocalTime` function or the Unix `localtime` function. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- datime(X). - -X = datime(2001,5,28,15,29,46) ? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred mktime(datime(+ _Year_, + _Month_, + _DayOfTheMonth_, - -+ _Hour_, + _Minute_, + _Second_), - _Seconds_) - -The `mktime/1` procedure returns the number of _Seconds_ -elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time -(UTC). The user provides information on _Year_, _Month_, - _DayOfTheMonth_, _Hour_, _Minute_, and _Second_. The - _Hour_ is given on local time. This function uses the WIN32 -`GetLocalTime` function or the Unix `mktime` function. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- mktime(datime(2001,5,28,15,29,46),X). - -X = 991081786 ? ; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred delete_file(+ _File_) - - -The delete_file/1 procedure removes file _File_. If - _File_ is a directory, remove the directory and all its subdirectories. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- delete_file(x). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred delete_file(+ _File_,+ _Opts_) - -The `delete_file/2` procedure removes file _File_ according to -options _Opts_. These options are `directory` if one should -remove directories, `recursive` if one should remove directories -recursively, and `ignore` if errors are not to be reported. - -This example is equivalent to using the delete_file/1 predicate: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- delete_file(x, [recursive]). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred directory_files(+ _Dir_,+ _List_) - - -Given a directory _Dir_, directory_files/2 procedures a -listing of all files and directories in the directory: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- directory_files('.',L), writeq(L). -['Makefile.~1~','sys.so','Makefile','sys.o',x,..,'.'] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The predicates uses the `dirent` family of routines in Unix -environments, and `findfirst` in WIN32. - - -*/ - -/** @pred file_exists(+ _File_) - - -The atom _File_ corresponds to an existing file. - - -*/ - -/** @pred file_exists(+ _File_,+ _Permissions_) - -The atom _File_ corresponds to an existing file with permissions -compatible with _Permissions_. YAP currently only accepts for -permissions to be described as a number. The actual meaning of this -number is Operating System dependent. - - -*/ - -/** @pred file_property(+ _File_,? _Property_) - - -The atom _File_ corresponds to an existing file, and _Property_ -will be unified with a property of this file. The properties are of the -form `type( _Type_)`, which gives whether the file is a regular -file, a directory, a fifo file, or of unknown type; -`size( _Size_)`, with gives the size for a file, and -`mod_time( _Time_)`, which gives the last time a file was -modified according to some Operating System dependent -timestamp; `mode( _mode_)`, gives the permission flags for the -file, and `linkto( _FileName_)`, gives the file pointed to by a -symbolic link. Properties can be obtained through backtracking: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- file_property('Makefile',P). - -P = type(regular) ? ; - -P = size(2375) ? ; - -P = mod_time(990826911) ? ; - -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred make_directory(+ _Dir_) - - -Create a directory _Dir_. The name of the directory must be an atom. - - -*/ - -/** @pred rename_file(+ _OldFile_,+ _NewFile_) - - -Create file _OldFile_ to _NewFile_. This predicate uses the -`C` built-in function `rename`. - - -*/ - -/** @pred environ(? _EnvVar_,+ _EnvValue_) - - -Unify environment variable _EnvVar_ with its value _EnvValue_, -if there is one. This predicate is backtrackable in Unix systems, but -not currently in Win32 configurations. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- environ('HOME',X). - -X = 'C:\\cygwin\\home\\administrator' ? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred host_id(- _Id_) - - - -Unify _Id_ with an identifier of the current host. YAP uses the -`hostid` function when available, - - -*/ - -/** @pred host_name(- _Name_) - - - -Unify _Name_ with a name for the current host. YAP uses the -`hostname` function in Unix systems when available, and the -`GetComputerName` function in WIN32 systems. - - -*/ - -/** @pred kill( _Id_,+ _SIGNAL_) - - - -Send signal _SIGNAL_ to process _Id_. In Unix this predicate is -a direct interface to `kill` so one can send signals to groups of -processes. In WIN32 the predicate is an interface to -`TerminateProcess`, so it kills _Id_ independently of _SIGNAL_. - - -*/ - -/** @pred mktemp( _Spec_,- _File_) - - - -Direct interface to `mktemp`: given a _Spec_, that is a file -name with six _X_ to it, create a file name _File_. Use -tmpnam/1 instead. - - -*/ - -/** @pred pid(- _Id_) - - - -Unify _Id_ with the process identifier for the current -process. An interface to the getpid function. - - -*/ - -/** @pred tmpnam(- _File_) - - - -Interface with _tmpnam_: obtain a new, unique file name _File_. - - -*/ - -/** @pred tmp_file(- _File_) - - - -Create a name for a temporary file. _Base_ is an user provided -identifier for the category of file. The _TmpName_ is guaranteed to -be unique. If the system halts, it will automatically remove all created -temporary files. - - -*/ - -/** @pred exec(+ _Command_,[+ _InputStream_,+ _OutputStream_,+ _ErrorStream_],- _PID_) - - -Execute command _Command_ with its streams connected to - _InputStream_, _OutputStream_, and _ErrorStream_. The -process that executes the command is returned as _PID_. The -command is executed by the default shell `bin/sh -c` in Unix. - -The following example demonstrates the use of exec/3 to send a -command and process its output: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -exec(ls,[std,pipe(S),null],P),repeat, get0(S,C), (C = -1, close(S) ! ; put(C)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The streams may be one of standard stream, `std`, null stream, -`null`, or `pipe(S)`, where _S_ is a pipe stream. Note -that it is up to the user to close the pipe. - - -*/ - -/** @pred popen(+ _Command_, + _TYPE_, - _Stream_) - - -Interface to the popen function. It opens a process by creating a -pipe, forking and invoking _Command_ on the current shell. Since a -pipe is by definition unidirectional the _Type_ argument may be -`read` or `write`, not both. The stream should be closed -using close/1, there is no need for a special `pclose` -command. - -The following example demonstrates the use of popen/3 to process -the output of a command, as exec/3 would do: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - ?- popen(ls,read,X),repeat, get0(X,C), (C = -1, ! ; put(C)). - -X = 'C:\\cygwin\\home\\administrator' ? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The WIN32 implementation of popen/3 relies on exec/3. - - -*/ - -/** @pred shell - - -Start a new shell and leave YAP in background until the shell -completes. YAP uses the shell given by the environment variable -`SHELL`. In WIN32 environment YAP will use `COMSPEC` if -`SHELL` is undefined. - - -*/ - -/** @pred shell(+ _Command_) - -Execute command _Command_ under a new shell. YAP will be in -background until the command completes. In Unix environments YAP uses -the shell given by the environment variable `SHELL` with the option -`" -c "`. In WIN32 environment YAP will use `COMSPEC` if -`SHELL` is undefined, in this case with the option `" /c "`. - - -*/ - -/** @pred shell(+ _Command_,- _Status_) - -Execute command _Command_ under a new shell and unify _Status_ -with the exit for the command. YAP will be in background until the -command completes. In Unix environments YAP uses the shell given by the -environment variable `SHELL` with the option `" -c "`. In -WIN32 environment YAP will use `COMSPEC` if `SHELL` is -undefined, in this case with the option `" /c "`. - - -*/ - -/** @pred sleep(+ _Time_) - - -Block the current thread for _Time_ seconds. When YAP is compiled -without multi-threading support, this predicate blocks the YAP process. -The number of seconds must be a positive number, and it may an integer -or a float. The Unix implementation uses `usleep` if the number of -seconds is below one, and `sleep` if it is over a second. The WIN32 -implementation uses `Sleep` for both cases. - - -*/ - -/** @pred system - -Start a new default shell and leave YAP in background until the shell -completes. YAP uses `/bin/sh` in Unix systems and `COMSPEC` in -WIN32. - - -*/ - -/** @pred system(+ _Command_,- _Res_) - -Interface to `system`: execute command _Command_ and unify - _Res_ with the result. - - -*/ - -/** @pred wait(+ _PID_,- _Status_) - - -Wait until process _PID_ terminates, and return its exits _Status_. - - - - -@} */ - -/** @defgroup Terms Utilities On Terms -@ingroup YAPLibrary -@{ - -The next routines provide a set of commonly used utilities to manipulate -terms. Most of these utilities have been implemented in `C` for -efficiency. They are available through the -`use_module(library(terms))` command. - - - - @pred cyclic_term(? _Term_) - - -Succeed if the argument _Term_ is not a cyclic term. - - -*/ - -/** @pred term_hash(+ _Term_, ? _Hash_) - - - -If _Term_ is ground unify _Hash_ with a positive integer -calculated from the structure of the term. Otherwise the argument - _Hash_ is left unbound. The range of the positive integer is from -`0` to, but not including, `33554432`. - - -*/ - -/** @pred term_hash(+ _Term_, + _Depth_, + _Range_, ? _Hash_) - - -Unify _Hash_ with a positive integer calculated from the structure -of the term. The range of the positive integer is from `0` to, but -not including, _Range_. If _Depth_ is `-1` the whole term -is considered. Otherwise, the term is considered only up to depth -`1`, where the constants and the principal functor have depth -`1`, and an argument of a term with depth _I_ has depth _I+1_. - - -*/ - -/** @pred variables_within_term(+ _Variables_,? _Term_, - _OutputVariables_) - - - -Unify _OutputVariables_ with the subset of the variables _Variables_ that occurs in _Term_. - - -*/ - -/** @pred new_variables_in_term(+ _Variables_,? _Term_, - _OutputVariables_) - - - -Unify _OutputVariables_ with all variables occurring in _Term_ that are not in the list _Variables_. - - -*/ - -/** @pred variant(? _Term1_, ? _Term2_) - - - -Succeed if _Term1_ and _Term2_ are variant terms. - - -*/ - -/** @pred subsumes(? _Term1_, ? _Term2_) - - - -Succeed if _Term1_ subsumes _Term2_. Variables in term - _Term1_ are bound so that the two terms become equal. - - -*/ - -/** @pred subsumes_chk(? _Term1_, ? _Term2_) - - - -Succeed if _Term1_ subsumes _Term2_ but does not bind any -variable in _Term1_. - - -*/ - -/** @pred variable_in_term(? _Term_,? _Var_) - - -Succeed if the second argument _Var_ is a variable and occurs in -term _Term_. - - -*/ - -/** @pred unifiable(? _Term1_, ? _Term2_, - _Bindings_) - - - -Succeed if _Term1_ and _Term2_ are unifiable with substitution - _Bindings_. - - - - -@} */ - -/** @defgroup Tries Trie DataStructure -@ingroup YAPLibrary -@{ - -The next routines provide a set of utilities to create and manipulate -prefix trees of Prolog terms. Tries were originally proposed to -implement tabling in Logic Programming, but can be used for other -purposes. The tries will be stored in the Prolog database and can seen -as alternative to `assert` and `record` family of -primitives. Most of these utilities have been implemented in `C` -for efficiency. They are available through the -`use_module(library(tries))` command. - - -*/ - -/** @pred trie_open(- _Id_) - - - -Open a new trie with identifier _Id_. - - -*/ - -/** @pred trie_close(+ _Id_) - - - -Close trie with identifier _Id_. - - -*/ - -/** @pred trie_close_all - - - -Close all available tries. - - -*/ - -/** @pred trie_mode(? _Mode_) - - - -Unify _Mode_ with trie operation mode. Allowed values are either -`std` (default) or `rev`. - - -*/ - -/** @pred trie_put_entry(+ _Trie_,+ _Term_,- _Ref_) - - - -Add term _Term_ to trie _Trie_. The handle _Ref_ gives -a reference to the term. - - -*/ - -/** @pred trie_check_entry(+ _Trie_,+ _Term_,- _Ref_) - - - -Succeeds if a variant of term _Term_ is in trie _Trie_. An handle - _Ref_ gives a reference to the term. - - -*/ - -/** @pred trie_get_entry(+ _Ref_,- _Term_) - - -Unify _Term_ with the entry for handle _Ref_. - - -*/ - -/** @pred trie_remove_entry(+ _Ref_) - - - -Remove entry for handle _Ref_. - - -*/ - -/** @pred trie_remove_subtree(+ _Ref_) - - - -Remove subtree rooted at handle _Ref_. - - -*/ - -/** @pred trie_save(+ _Trie_,+ _FileName_) - - -Dump trie _Trie_ into file _FileName_. - - -*/ - -/** @pred trie_load(+ _Trie_,+ _FileName_) - - -Load trie _Trie_ from the contents of file _FileName_. - - -*/ - -/** @pred trie_stats(- _Memory_,- _Tries_,- _Entries_,- _Nodes_) - - -Give generic statistics on tries, including the amount of memory, - _Memory_, the number of tries, _Tries_, the number of entries, - _Entries_, and the total number of nodes, _Nodes_. - - -*/ - -/** @pred trie_max_stats(- _Memory_,- _Tries_,- _Entries_,- _Nodes_) - - -Give maximal statistics on tries, including the amount of memory, - _Memory_, the number of tries, _Tries_, the number of entries, - _Entries_, and the total number of nodes, _Nodes_. - - -*/ - -/** @pred trie_usage(+ _Trie_,- _Entries_,- _Nodes_,- _VirtualNodes_) - - -Give statistics on trie _Trie_, the number of entries, - _Entries_, and the total number of nodes, _Nodes_, and the -number of _VirtualNodes_. - - -*/ - -/** @pred trie_print(+ _Trie_) - - -Print trie _Trie_ on standard output. - - - - -@} */ - -/** @defgroup Cleanup Call Cleanup -@ingroup YAPLibrary -@{ - -call_cleanup/1 and call_cleanup/2 allow predicates to register -code for execution after the call is finished. Predicates can be -declared to be fragile to ensure that call_cleanup is called -for any Goal which needs it. This library is loaded with the -`use_module(library(cleanup))` command. - - -*/ - -/** @pred :- fragile _P_,...., _Pn_ - - -Declares the predicate _P_=[module:]name/arity as a fragile -predicate, module is optional, default is the current -typein_module. Whenever such a fragile predicate is used in a query -it will be called through call_cleanup/1. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -:- fragile foo/1,bar:baz/2. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred call_cleanup(: _Goal_) - - -Execute goal _Goal_ within a cleanup-context. Called predicates -might register cleanup Goals which are called right after the end of -the call to _Goal_. Cuts and exceptions inside Goal do not prevent the -execution of the cleanup calls. call_cleanup might be nested. - - -*/ - -/** @pred call_cleanup(: _Goal_, : _CleanUpGoal_) - -This is similar to call_cleanup/1 with an additional - _CleanUpGoal_ which gets called after _Goal_ is finished. - - -*/ - -/** @pred setup_call_cleanup(: _Setup_,: _Goal_, : _CleanUpGoal_) - - -Calls `(Setup, Goal)`. For each sucessful execution of _Setup_, calling _Goal_, the -cleanup handler _Cleanup_ is guaranteed to be called exactly once. -This will happen after _Goal_ completes, either through failure, -deterministic success, commit, or an exception. _Setup_ will -contain the goals that need to be protected from asynchronous interrupts -such as the ones received from `call_with_time_limit/2` or thread_signal/2. In -most uses, _Setup_ will perform temporary side-effects required by - _Goal_ that are finally undone by _Cleanup_. - -Success or failure of _Cleanup_ is ignored and choice-points it -created are destroyed (as once/1). If _Cleanup_ throws an exception, -this is executed as normal. - -Typically, this predicate is used to cleanup permanent data storage -required to execute _Goal_, close file-descriptors, etc. The example -below provides a non-deterministic search for a term in a file, closing -the stream as needed. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -term_in_file(Term, File) :- - setup_call_cleanup(open(File, read, In), - term_in_stream(Term, In), - close(In) ). - -term_in_stream(Term, In) :- - repeat, - read(In, T), - ( T == end_of_file - -> !, fail - ; T = Term - ). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that it is impossible to implement this predicate in Prolog other than -by reading all terms into a list, close the file and call member/2. -Without setup_call_cleanup/3 there is no way to gain control if the -choice-point left by `repeat` is removed by a cut or an exception. - -`setup_call_cleanup/2` can also be used to test determinism of a goal: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- setup_call_cleanup(true,(X=1;X=2), Det=yes). - -X = 1 ; - -X = 2, -Det = yes ; -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This predicate is under consideration for inclusion into the ISO standard. -For compatibility with other Prolog implementations see `call_cleanup/2`. - - -*/ - -/** @pred setup_call_catcher_cleanup(: _Setup_,: _Goal_, + _Catcher_,: _CleanUpGoal_) - - -Similar to `setup_call_cleanup( _Setup_, _Goal_, _Cleanup_)` with -additional information on the reason of calling _Cleanup_. Prior -to calling _Cleanup_, _Catcher_ unifies with the termination -code. If this unification fails, _Cleanup_ is - *not* called. - - -*/ - -/** @pred on_cleanup(+ _CleanUpGoal_) - - -Any Predicate might registers a _CleanUpGoal_. The - _CleanUpGoal_ is put onto the current cleanup context. All such -CleanUpGoals are executed in reverse order of their registration when -the surrounding cleanup-context ends. This call will throw an exception -if a predicate tries to register a _CleanUpGoal_ outside of any -cleanup-context. - - -*/ - -/** @pred cleanup_all - - -Calls all pending CleanUpGoals and resets the cleanup-system to an -initial state. Should only be used as one of the last calls in the -main program. - - - -There are some private predicates which could be used in special -cases, such as manually setting up cleanup-contexts and registering -CleanUpGoals for other than the current cleanup-context. -Read the Source Luke. - - -@} */ - -/** @defgroup Timeout Calls With Timeout -@ingroup YAPLibrary -@{ - -The time_out/3 command relies on the alarm/3 built-in to -implement a call with a maximum time of execution. The command is -available with the `use_module(library(timeout))` command. - - - - @pred time_out(+ _Goal_, + _Timeout_, - _Result_) - - -Execute goal _Goal_ with time limited _Timeout_, where - _Timeout_ is measured in milliseconds. If the goal succeeds, unify - _Result_ with success. If the timer expires before the goal -terminates, unify _Result_ with time_out. - -This command is implemented by activating an alarm at procedure -entry. If the timer expires before the goal completes, the alarm will -throw an exception _timeout_. - -One should note that time_out/3 is not reentrant, that is, a goal -called from `time_out` should never itself call -time_out/3. Moreover, time_out/3 will deactivate any previous -alarms set by alarm/3 and vice-versa, hence only one of these -calls should be used in a program. - -Last, even though the timer is set in milliseconds, the current -implementation relies on alarm/3, and therefore can only offer -precision on the scale of seconds. - - - - -@} */ - -/** @defgroup Trees Updatable Binary Trees -@ingroup YAPLibrary -@{ - -The following queue manipulation routines are available once -included with the `use_module(library(trees))` command. - - - - @pred get_label(+ _Index_, + _Tree_, ? _Label_) - - -Treats the tree as an array of _N_ elements and returns the - _Index_-th. - - -*/ - -/** @pred list_to_tree(+ _List_, - _Tree_) - - -Takes a given _List_ of _N_ elements and constructs a binary - _Tree_. - - -*/ - -/** @pred map_tree(+ _Pred_, + _OldTree_, - _NewTree_) - - -Holds when _OldTree_ and _NewTree_ are binary trees of the same shape -and `Pred(Old,New)` is true for corresponding elements of the two trees. - - -*/ - -/** @pred put_label(+ _Index_, + _OldTree_, + _Label_, - _NewTree_) - - -constructs a new tree the same shape as the old which moreover has the -same elements except that the _Index_-th one is _Label_. - - -*/ - -/** @pred tree_size(+ _Tree_, - _Size_) - - -Calculates the number of elements in the _Tree_. - - -*/ - -/** @pred tree_to_list(+ _Tree_, - _List_) - - -Is the converse operation to list_to_tree. - - - - -@} */ - -/** @defgroup UGraphs Unweighted Graphs -@ingroup YAPLibrary -@{ - -The following graph manipulation routines are based in code originally -written by Richard O'Keefe. The code was then extended to be compatible -with the SICStus Prolog ugraphs library. The routines assume directed -graphs, undirected graphs may be implemented by using two edges. Graphs -are represented in one of two ways: - - + The P-representation of a graph is a list of (from-to) vertex -pairs, where the pairs can be in any old order. This form is -convenient for input/output. - - -*/ - -/** @pred The S-representation of a graph is a list of (vertex-neighbors) -pairs, where the pairs are in standard order (as produced by keysort) -and the neighbors of each vertex are also in standard order (as -produced by sort). This form is convenient for many calculations. - - -These built-ins are available once included with the -`use_module(library(ugraphs))` command. - - - - @pred vertices_edges_to_ugraph(+ _Vertices_, + _Edges_, - _Graph_) - - -Given a graph with a set of vertices _Vertices_ and a set of edges - _Edges_, _Graph_ must unify with the corresponding -s-representation. Note that the vertices without edges will appear in - _Vertices_ but not in _Edges_. Moreover, it is sufficient for a -vertex to appear in _Edges_. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- vertices_edges_to_ugraph([],[1-3,2-4,4-5,1-5],L). - -L = [1-[3,5],2-[4],3-[],4-[5],5-[]] ? - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In this case all edges are defined implicitly. The next example shows -three unconnected edges: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- vertices_edges_to_ugraph([6,7,8],[1-3,2-4,4-5,1-5],L). - -L = [1-[3,5],2-[4],3-[],4-[5],5-[],6-[],7-[],8-[]] ? - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred vertices(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with all vertices appearing in graph - _Graph_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). - -L = [1,2,3,4,5] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred edges(+ _Graph_, - _Edges_) - - -Unify _Edges_ with all edges appearing in graph - _Graph_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). - -L = [1,2,3,4,5] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -vertices _Vertices_ to the graph _Graph_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- add_vertices([1-[3,5],2-[4],3-[],4-[5], - 5-[],6-[],7-[],8-[]], - [0,2,9,10,11], - NG). - -NG = [0-[],1-[3,5],2-[4],3-[],4-[5],5-[], - 6-[],7-[],8-[],9-[],10-[],11-[]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting the list of -vertices _Vertices_ and all the edges that start from or go to a -vertex in _Vertices_ to the graph _Graph_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- del_vertices([2,1],[1-[3,5],2-[4],3-[], - 4-[5],5-[],6-[],7-[2,6],8-[]],NL). - -NL = [3-[],4-[5],5-[],6-[],7-[6],8-[]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred add_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -edges _Edges_ to the graph _Graph_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- add_edges([1-[3,5],2-[4],3-[],4-[5],5-[],6-[], - 7-[],8-[]],[1-6,2-3,3-2,5-7,3-2,4-5],NL). - -NL = [1-[3,5,6],2-[3,4],3-[2],4-[5],5-[7],6-[],7-[],8-[]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred del_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by removing the list of -edges _Edges_ from the graph _Graph_. Notice that no vertices -are deleted. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- del_edges([1-[3,5],2-[4],3-[],4-[5],5-[], - 6-[],7-[],8-[]], - [1-6,2-3,3-2,5-7,3-2,4-5,1-3],NL). - -NL = [1-[5],2-[4],3-[],4-[],5-[],6-[],7-[],8-[]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred transpose(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained from _Graph_ by -replacing all edges of the form _V1-V2_ by edges of the form - _V2-V1_. The cost is `O(|V|^2)`. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- transpose([1-[3,5],2-[4],3-[], - 4-[5],5-[],6-[],7-[],8-[]], NL). - -NL = [1-[],2-[],3-[1],4-[2],5-[1,4],6-[],7-[],8-[]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Notice that an undirected graph is its own transpose. - - -*/ - -/** @pred neighbors(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbors of vertex _Vertex_ -in _Graph_. If the vertice is not in the graph fail. In the next -example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- neighbors(4,[1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], - NL). - -NL = [1,2,7,5] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred neighbours(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbours of vertex _Vertex_ -in _Graph_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- neighbours(4,[1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). - -NL = [1,2,7,5] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred complement(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with the graph complementary to _Graph_. -In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- complement([1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). - -NL = [1-[2,4,6,7,8],2-[1,3,5,6,7,8],3-[1,2,4,5,6,7,8], - 4-[3,5,6,8],5-[1,2,3,4,6,7,8],6-[1,2,3,4,5,7,8], - 7-[1,2,3,4,5,6,8],8-[1,2,3,4,5,6,7]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred compose(+ _LeftGraph_, + _RightGraph_, - _NewGraph_) - - -Compose the graphs _LeftGraph_ and _RightGraph_ to form _NewGraph_. -In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- compose([1-[2],2-[3]],[2-[4],3-[1,2,4]],L). - -L = [1-[4],2-[1,2,4],3-[]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred top_sort(+ _Graph_, - _Sort_) - - -Generate the set of nodes _Sort_ as a topological sorting of graph - _Graph_, if one is possible. -In the next example we show how topological sorting works for a linear graph: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- top_sort([_138-[_219],_219-[_139], _139-[]],L). - -L = [_138,_219,_139] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred top_sort(+ _Graph_, - _Sort0_, - _Sort_) - -Generate the difference list _Sort_- _Sort0_ as a topological -sorting of graph _Graph_, if one is possible. - - -*/ - -/** @pred transitive_closure(+ _Graph_, + _Closure_) - - -Generate the graph _Closure_ as the transitive closure of graph - _Graph_. -In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- transitive_closure([1-[2,3],2-[4,5],4-[6]],L). - -L = [1-[2,3,4,5,6],2-[4,5,6],4-[6]] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred reachable(+ _Node_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the set of all vertices in graph - _Graph_ that are reachable from _Node_. In the next example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- reachable(1,[1-[3,5],2-[4],3-[],4-[5],5-[]],V). - -V = [1,3,5] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup DGraphs Directed Graphs -@ingroup YAPLibrary -@{ - -The following graph manipulation routines use the red-black tree library -to try to avoid linear-time scans of the graph for all graph -operations. Graphs are represented as a red-black tree, where the key is -the vertex, and the associated value is a list of vertices reachable -from that vertex through an edge (ie, a list of edges). - - - - @pred dgraph_new(+ _Graph_) - - -Create a new directed graph. This operation must be performed before -trying to use the graph. - - -*/ - -/** @pred dgraph_vertices(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with all vertices appearing in graph - _Graph_. - - -*/ - -/** @pred dgraph_edge(+ _N1_, + _N2_, + _Graph_) - - -Edge _N1_- _N2_ is an edge in directed graph _Graph_. - - -*/ - -/** @pred dgraph_edges(+ _Graph_, - _Edges_) - - -Unify _Edges_ with all edges appearing in graph - _Graph_. - - -*/ - -/** @pred dgraph_add_vertices(+ _Graph_, + _Vertex_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding -vertex _Vertex_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -vertices _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_del_vertex(+ _Graph_, + _Vertex_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting vertex - _Vertex_ and all the edges that start from or go to _Vertex_ to -the graph _Graph_. - - -*/ - -/** @pred dgraph_del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting the list of -vertices _Vertices_ and all the edges that start from or go to a -vertex in _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_add_edge(+ _Graph_, + _N1_, + _N2_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the edge - _N1_- _N2_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_add_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -edges _Edges_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_del_edge(+ _Graph_, + _N1_, + _N2_, - _NewGraph_) - - -Succeeds if _NewGraph_ unifies with a new graph obtained by -removing the edge _N1_- _N2_ from the graph _Graph_. Notice -that no vertices are deleted. - - -*/ - -/** @pred dgraph_del_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by removing the list of -edges _Edges_ from the graph _Graph_. Notice that no vertices -are deleted. - - -*/ - -/** @pred dgraph_to_ugraph(+ _Graph_, - _UGraph_) - - -Unify _UGraph_ with the representation used by the _ugraphs_ -unweighted graphs library, that is, a list of the form - _V-Neighbors_, where _V_ is a node and _Neighbors_ the nodes -children. - - -*/ - -/** @pred ugraph_to_dgraph( + _UGraph_, - _Graph_) - - -Unify _Graph_ with the directed graph obtain from _UGraph_, -represented in the form used in the _ugraphs_ unweighted graphs -library. - - -*/ - -/** @pred dgraph_neighbors(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbors of vertex _Vertex_ -in _Graph_. If the vertice is not in the graph fail. - - -*/ - -/** @pred dgraph_neighbours(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbours of vertex _Vertex_ -in _Graph_. - - -*/ - -/** @pred dgraph_complement(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with the graph complementary to _Graph_. - - -*/ - -/** @pred dgraph_transpose(+ _Graph_, - _Transpose_) - - -Unify _NewGraph_ with a new graph obtained from _Graph_ by -replacing all edges of the form _V1-V2_ by edges of the form - _V2-V1_. - - -*/ - -/** @pred dgraph_compose(+ _Graph1_, + _Graph2_, - _ComposedGraph_) - - -Unify _ComposedGraph_ with a new graph obtained by composing - _Graph1_ and _Graph2_, ie, _ComposedGraph_ has an edge - _V1-V2_ iff there is a _V_ such that _V1-V_ in _Graph1_ -and _V-V2_ in _Graph2_. - - -*/ - -/** @pred dgraph_transitive_closure(+ _Graph_, - _Closure_) - - -Unify _Closure_ with the transitive closure of graph _Graph_. - - -*/ - -/** @pred dgraph_symmetric_closure(+ _Graph_, - _Closure_) - - -Unify _Closure_ with the symmetric closure of graph _Graph_, -that is, if _Closure_ contains an edge _U-V_ it must also -contain the edge _V-U_. - - -*/ - -/** @pred dgraph_top_sort(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with the topological sort of graph _Graph_. - - -*/ - -/** @pred dgraph_top_sort(+ _Graph_, - _Vertices_, ? _Vertices0_) - -Unify the difference list _Vertices_- _Vertices0_ with the -topological sort of graph _Graph_. - - -*/ - -/** @pred dgraph_min_path(+ _V1_, + _V1_, + _Graph_, - _Path_, ? _Costt_) - - -Unify the list _Path_ with the minimal cost path between nodes - _N1_ and _N2_ in graph _Graph_. Path _Path_ has cost - _Cost_. - - -*/ - -/** @pred dgraph_max_path(+ _V1_, + _V1_, + _Graph_, - _Path_, ? _Costt_) - - -Unify the list _Path_ with the maximal cost path between nodes - _N1_ and _N2_ in graph _Graph_. Path _Path_ has cost - _Cost_. - - -*/ - -/** @pred dgraph_min_paths(+ _V1_, + _Graph_, - _Paths_) - - -Unify the list _Paths_ with the minimal cost paths from node - _N1_ to the nodes in graph _Graph_. - - -*/ - -/** @pred dgraph_isomorphic(+ _Vs_, + _NewVs_, + _G0_, - _GF_) - - -Unify the list _GF_ with the graph isomorphic to _G0_ where -vertices in _Vs_ map to vertices in _NewVs_. - - -*/ - -/** @pred dgraph_path(+ _Vertex_, + _Graph_, ? _Path_) - - -The path _Path_ is a path starting at vertex _Vertex_ in graph - _Graph_. - - -*/ - -/** @pred dgraph_path(+ _Vertex_, + _Vertex1_, + _Graph_, ? _Path_) - -The path _Path_ is a path starting at vertex _Vertex_ in graph - _Graph_ and ending at path _Vertex2_. - - -*/ - -/** @pred dgraph_reachable(+ _Vertex_, + _Graph_, ? _Edges_) - - -The path _Path_ is a path starting at vertex _Vertex_ in graph - _Graph_. - - -*/ - -/** @pred dgraph_leaves(+ _Graph_, ? _Vertices_) - - -The vertices _Vertices_ have no outgoing edge in graph - _Graph_. - - - - -@} */ - -/** @defgroup UnDGraphs Undirected Graphs -@ingroup YAPLibrary -@{ - -The following graph manipulation routines use the red-black tree graph -library to implement undirected graphs. Mostly, this is done by having -two directed edges per undirected edge. - - - - @pred undgraph_new(+ _Graph_) - - -Create a new directed graph. This operation must be performed before -trying to use the graph. - - -*/ - -/** @pred undgraph_vertices(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with all vertices appearing in graph - _Graph_. - - -*/ - -/** @pred undgraph_edge(+ _N1_, + _N2_, + _Graph_) - - -Edge _N1_- _N2_ is an edge in undirected graph _Graph_. - - -*/ - -/** @pred undgraph_edges(+ _Graph_, - _Edges_) - - -Unify _Edges_ with all edges appearing in graph - _Graph_. - - -*/ - -/** @pred undgraph_add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -vertices _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred undgraph_del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting the list of -vertices _Vertices_ and all the edges that start from or go to a -vertex in _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred undgraph_add_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -edges _Edges_ to the graph _Graph_. - - -*/ - -/** @pred undgraph_del_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by removing the list of -edges _Edges_ from the graph _Graph_. Notice that no vertices -are deleted. - - -*/ - -/** @pred undgraph_neighbors(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbors of vertex _Vertex_ -in _Graph_. If the vertice is not in the graph fail. - - -*/ - -/** @pred undgraph_neighbours(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbours of vertex _Vertex_ -in _Graph_. - - -*/ - -/** @pred undgraph_complement(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with the graph complementary to _Graph_. - - -*/ - -/** @pred dgraph_to_undgraph( + _DGraph_, - _UndGraph_) - - -Unify _UndGraph_ with the undirected graph obtained from the -directed graph _DGraph_. - - - - -@} */ - -/** @defgroup DBUsage Memory Usage in Prolog Data-Base -@ingroup YAPLibrary -@{ - -This library provides a set of utilities for studying memory usage in YAP. -The following routines are available once included with the -`use_module(library(dbusage))` command. - - -*/ - -/** @pred db_usage - - -Give general overview of data-base usage in the system. - - -*/ - -/** @pred db_static - - -List memory usage for every static predicate. - - -*/ - -/** @pred db_static(+ _Threshold_) - -List memory usage for every static predicate. Predicate must use more -than _Threshold_ bytes. - - -*/ - -/** @pred db_dynamic - - -List memory usage for every dynamic predicate. - - -*/ - -/** @pred db_dynamic(+ _Threshold_) - -List memory usage for every dynamic predicate. Predicate must use more -than _Threshold_ bytes. - - - - -@} */ - -/** @defgroup Lambda Lambda Expressions -@ingroup YAPLibrary -@{ - -This library, designed and implemented by Ulrich Neumerkel, provides -lambda expressions to simplify higher order programming based on `call/N`. - -Lambda expressions are represented by ordinary Prolog terms. There are -two kinds of lambda expressions: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} - Free+\X1^X2^ ..^XN^Goal - - \X1^X2^ ..^XN^Goal -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The second is a shorthand for` t+\\X1^X2^..^XN^Goal`, where `Xi` are the parameters. - - _Goal_ is a goal or continuation (Syntax note: _Operators_ within _Goal_ -require parentheses due to the low precedence of the `^` operator). - -Free contains variables that are valid outside the scope of the lambda -expression. They are thus free variables within. - -All other variables of _Goal_ are considered local variables. They must -not appear outside the lambda expression. This restriction is -currently not checked. Violations may lead to unexpected bindings. - -In the following example the parentheses around `X\>3` are necessary. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- use_module(library(lambda)). -?- use_module(library(apply)). - -?- maplist(\X^(X>3),[4,5,9]). -true. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In the following _X_ is a variable that is shared by both instances -of the lambda expression. The second query illustrates the cooperation -of continuations and lambdas. The lambda expression is in this case a -continuation expecting a further argument. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- Xs = [A,B], maplist(X+\Y^dif(X,Y), Xs). -Xs = [A, B], -dif(X, A), -dif(X, B). - -?- Xs = [A,B], maplist(X+\dif(X), Xs). -Xs = [A, B], -dif(X, A), -dif(X, B). - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The following queries are all equivalent. To see this, use -the fact `f(x,y)`. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.prolog} -?- call(f,A1,A2). -?- call(\X^f(X),A1,A2). -?- call(\X^Y^f(X,Y), A1,A2). -?- call(\X^(X+\Y^f(X,Y)), A1,A2). -?- call(call(f, A1),A2). -?- call(f(A1),A2). -?- f(A1,A2). -A1 = x, -A2 = y. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Further discussions -at Ulrich Neumerker's page in . - - -@} */ - -/** @defgroup LAM LAM -@ingroup YAPPackages -@{ - -This library provides a set of utilities for interfacing with LAM MPI. -The following routines are available once included with the -`use_module(library(lam_mpi))` command. The yap should be -invoked using the LAM mpiexec or mpirun commands (see LAM manual for -more details). - - -*/ - -/** @pred mpi_init - - -Sets up the mpi environment. This predicate should be called before any other MPI predicate. - - -*/ - -/** @pred mpi_finalize - - -Terminates the MPI execution environment. Every process must call this predicate before exiting. - - -*/ - -/** @pred mpi_comm_size(- _Size_) - - -Unifies _Size_ with the number of processes in the MPI environment. - - -*/ - -/** @pred mpi_comm_rank(- _Rank_) - - -Unifies _Rank_ with the rank of the current process in the MPI environment. - - -*/ - -/** @pred mpi_version(- _Major_,- _Minor_) - - -Unifies _Major_ and _Minor_ with, respectively, the major and minor version of the MPI. - - -*/ - -/** @pred mpi_send(+ _Data_,+ _Dest_,+ _Tag_) - - - -Blocking communication predicate. The message in _Data_, with tag - _Tag_, is sent immediately to the processor with rank _Dest_. -The predicate succeeds after the message being sent. - - -*/ - -/** @pred mpi_isend(+ _Data_,+ _Dest_,+ _Tag_,- _Handle_) - - - -Non blocking communication predicate. The message in _Data_, with -tag _Tag_, is sent whenever possible to the processor with rank - _Dest_. An _Handle_ to the message is returned to be used to -check for the status of the message, using the `mpi_wait` or -`mpi_test` predicates. Until `mpi_wait` is called, the -memory allocated for the buffer containing the message is not -released. - - -*/ - -/** @pred mpi_recv(? _Source_,? _Tag_,- _Data_) - - - -Blocking communication predicate. The predicate blocks until a message -is received from processor with rank _Source_ and tag _Tag_. -The message is placed in _Data_. - - -*/ - -/** @pred mpi_irecv(? _Source_,? _Tag_,- _Handle_) - - - -Non-blocking communication predicate. The predicate returns an - _Handle_ for a message that will be received from processor with -rank _Source_ and tag _Tag_. Note that the predicate succeeds -immediately, even if no message has been received. The predicate -`mpi_wait_recv` should be used to obtain the data associated to -the handle. - - -*/ - -/** @pred mpi_wait_recv(? _Handle_,- _Status_,- _Data_) - - - -Completes a non-blocking receive operation. The predicate blocks until -a message associated with handle _Hanlde_ is buffered. The -predicate succeeds unifying _Status_ with the status of the -message and _Data_ with the message itself. - - -*/ - -/** @pred mpi_test_recv(? _Handle_,- _Status_,- _Data_) - - - -Provides information regarding a handle. If the message associated -with handle _Hanlde_ is buffered then the predicate succeeds -unifying _Status_ with the status of the message and _Data_ -with the message itself. Otherwise, the predicate fails. - - -*/ - -/** @pred mpi_wait(? _Handle_,- _Status_) - - - -Completes a non-blocking operation. If the operation was a -`mpi_send`, the predicate blocks until the message is buffered -or sent by the runtime system. At this point the send buffer is -released. If the operation was a `mpi_recv`, it waits until the -message is copied to the receive buffer. _Status_ is unified with -the status of the message. - - -*/ - -/** @pred mpi_test(? _Handle_,- _Status_) - - - -Provides information regarding the handle _Handle_, ie., if a -communication operation has been completed. If the operation -associate with _Hanlde_ has been completed the predicate succeeds -with the completion status in _Status_, otherwise it fails. - - -*/ - -/** @pred mpi_barrier - - - -Collective communication predicate. Performs a barrier -synchronization among all processes. Note that a collective -communication means that all processes call the same predicate. To be -able to use a regular `mpi_recv` to receive the messages, one -should use `mpi_bcast2`. - - -*/ - -/** @pred mpi_bcast2(+ _Root_, ? _Data_) - - - -Broadcasts the message _Data_ from the process with rank _Root_ -to all other processes. - - -*/ - -/** @pred mpi_bcast3(+ _Root_, + _Data_, + _Tag_) - - -Broadcasts the message _Data_ with tag _Tag_ from the process with rank _Root_ -to all other processes. - - -*/ - -/** @pred mpi_ibcast(+ _Root_, + _Data_, + _Tag_) - - - -Non-blocking operation. Broadcasts the message _Data_ with tag _Tag_ -from the process with rank _Root_ to all other processes. - - -*/ - -/** @pred mpi_default_buffer_size(- _OldBufferSize_, ? _NewBufferSize_) - - - -The _OldBufferSize_ argument unifies with the current size of the -MPI communication buffer size and sets the communication buffer size - _NewBufferSize_. The buffer is used for assynchronous waiting and -for broadcast receivers. Notice that buffer is local at each MPI -process. - - -*/ - -/** @pred mpi_msg_size( _Msg_, - _MsgSize_) - - -Unify _MsgSize_ with the number of bytes YAP would need to send the -message _Msg_. - - -*/ - -/** @pred mpi_gc - - - -Attempts to perform garbage collection with all the open handles -associated with send and non-blocking broadcasts. For each handle it -tests it and the message has been delivered the handle and the buffer -are released. - - - - -@} */ - -/** @defgroup BDDs Binary Decision Diagrams and Friends -@ingroup YAPPackages -@{ - -This library provides an interface to the BDD package CUDD. It requires -CUDD compiled as a dynamic library. In Linux this is available out of -box in Fedora, but can easily be ported to other Linux -distributions. CUDD is available in the ports OSX package, and in -cygwin. To use it, call `:-use_module(library(bdd))`. - -The following predicates construct a BDD: - - -*/ - -/** @pred bbd_new(? _Exp_, - _BddHandle_) - -create a new BDD from the logical expression _Exp_. The expression -may include: - - + Logical Variables: -a leaf-node can be a logical variable. - + Constants 0 and 1 -a leaf-node can also be one of these two constants. - + or( _X_, _Y_), _X_ \\/ _Y_, _X_ + _Y_ -disjunction - + and( _X_, _Y_), _X_ /\\ _Y_, _X_ \* _Y_ -conjunction - + nand( _X_, _Y_) -negated conjunction@ - + nor( _X_, _Y_) -negated disjunction - + xor( _X_, _Y_) -exclusive or - + not( _X_), - _X_ -negation - - - -*/ - -/** @pred bdd_from_list(? _List_, - _BddHandle_) - -Convert a _List_ of logical expressions of the form above into a BDD -accessible through _BddHandle_. - - -*/ - -/** @pred mtbdd_new(? _Exp_, - _BddHandle_) - -create a new algebraic decision diagram (ADD) from the logical -expression _Exp_. The expression may include: - - + Logical Variables: -a leaf-node can be a logical variable, or parameter. - + Number -a leaf-node can also be any number - + _X_ \* _Y_ -product - + _X_ + _Y_ -sum - + _X_ - _Y_ -subtraction - + or( _X_, _Y_), _X_ \\/ _Y_ -logical or - - - -*/ - -/** @pred bdd_tree(+ _BDDHandle_, _Term_) - -Convert the BDD or ADD represented by _BDDHandle_ to a Prolog term -of the form `bdd( _Dir_, _Nodes_, _Vars_)` or `mtbdd( _Nodes_, _Vars_)`, respectively. The arguments are: - - + - _Dir_ direction of the BDD, usually 1 - + - _Nodes_ list of nodes in the BDD or ADD. - -In a BDD nodes may be pp (both terminals are positive) or pn -(right-hand-side is negative), and have four arguments: a logical -variable that will be bound to the value of the node, the logical -variable corresponding to the node, a logical variable, a 0 or a 1 with -the value of the left-hand side, and a logical variable, a 0 or a 1 -with the right-hand side. - - + - _Vars_ are the free variables in the original BDD, or the parameters of the BDD/ADD. - -As an example, the BDD for the expression `X+(Y+X)\*(-Z)` becomes: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -bdd(1,[pn(N2,X,1,N1),pp(N1,Y,N0,1),pn(N0,Z,1,1)],vs(X,Y,Z)) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred bdd_eval(+ _BDDHandle_, _Val_) - -Unify _Val_ with the value of the logical expression compiled in - _BDDHandle_ given an assignment to its variables. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -bdd_new(X+(Y+X)*(-Z), BDD), -[X,Y,Z] = [0,0,0], -bdd_eval(BDD, V), -writeln(V). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -would write 0 in the standard output stream. - -The Prolog code equivalent to bdd_eval/2 is: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Tree = bdd(1, T, _Vs), - reverse(T, RT), - foldl(eval_bdd, RT, _, V). - -eval_bdd(pp(P,X,L,R), _, P) :- - P is ( X/\L ) \/ ( (1-X) /\ R ). -eval_bdd(pn(P,X,L,R), _, P) :- - P is ( X/\L ) \/ ( (1-X) /\ (1-R) ). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -First, the nodes are reversed to implement bottom-up evaluation. Then, -we use the `foldl` list manipulation predicate to walk every node, -computing the disjunction of the two cases and binding the output -variable. The top node gives the full expression value. Notice that -`(1- _X_)` implements negation. - - -*/ - -/** @pred bdd_size(+ _BDDHandle_, - _Size_) - -Unify _Size_ with the number of nodes in _BDDHandle_. - - -*/ - -/** @pred bdd_print(+ _BDDHandle_, + _File_) - -Output bdd _BDDHandle_ as a dot file to _File_. - - -*/ - -/** @pred bdd_to_probability_sum_product(+ _BDDHandle_, - _Prob_) - -Each node in a BDD is given a probability _Pi_. The total -probability of a corresponding sum-product network is _Prob_. - - -*/ - -/** @pred bdd_to_probability_sum_product(+ _BDDHandle_, - _Probs_, - _Prob_) -Each node in a BDD is given a probability _Pi_. The total -probability of a corresponding sum-product network is _Prob_, and -the probabilities of the inner nodes are _Probs_. - -In Prolog, this predicate would correspond to computing the value of a -BDD. The input variables will be bound to probabilities, eg -`[ _X_, _Y_, _Z_] = [0.3.0.7,0.1]`, and the previous -`eval_bdd` would operate over real numbers: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Tree = bdd(1, T, _Vs), - reverse(T, RT), - foldl(eval_prob, RT, _, V). - -eval_prob(pp(P,X,L,R), _, P) :- - P is X * L + (1-X) * R. -eval_prob(pn(P,X,L,R), _, P) :- - P is X * L + (1-X) * (1-R). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -*/ - -/** @pred bdd_close( _BDDHandle_) - -close the BDD and release any resources it holds. - - - - -@} */ - -/** @defgroup Block_Diagram Block Diagram -@ingroup YAPLibrary -@{ - -This library provides a way of visualizing a prolog program using -modules with blocks. To use it use: -`:-use_module(library(block_diagram))`. - - -*/ - -/** @pred make_diagram(+inputfilename, +ouputfilename) - - - -This will crawl the files following the use_module, ensure_loaded directives withing the inputfilename. -The result will be a file in dot format. -You can make a pdf at the shell by asking `dot -Tpdf filename \> output.pdf`. - - -*/ - -/** @pred make_diagram(+inputfilename, +ouputfilename, +predicate, +depth, +extension) - - -The same as make_diagram/2 but you can define how many of the imported/exporeted predicates will be shown with predicate, and how deep the crawler is allowed to go with depth. The extension is used if the file use module directives do not include a file extension. - - - -*/ - -/** @page SWIhYProlog_Emulation SWI-Prolog Emulation - -This library provides a number of SWI-Prolog builtins that are not by -default in YAP. This support is loaded with the -`expects_dialect(swi)` command. - - -*/ - -/** @pred append(? _List1_,? _List2_,? _List3_) - - -Succeeds when _List3_ unifies with the concatenation of _List1_ -and _List2_. The predicate can be used with any instantiation -pattern (even three variables). - - -*/ - -/** @pred between(+ _Low_,+ _High_,? _Value_) - - - - _Low_ and _High_ are integers, _High_ less or equal than - _Low_. If _Value_ is an integer, _Low_ less or equal than - _Value_ less or equal than _High_. When _Value_ is a -variable it is successively bound to all integers between _Low_ and - _High_. If _High_ is `inf`, between/3 is true iff - _Value_ less or equal than _Low_, a feature that is particularly -interesting for generating integers from a certain value. - - -*/ - -/** @pred chdir(+ _Dir_) - - - -Compatibility predicate. New code should use working_directory/2. - - -*/ - -/** @pred concat_atom(+ _List_,- _Atom_) - - - - _List_ is a list of atoms, integers or floating point numbers. Succeeds -if _Atom_ can be unified with the concatenated elements of _List_. If - _List_ has exactly 2 elements it is equivalent to `atom_concat/3`, -allowing for variables in the list. - - -*/ - -/** @pred concat_atom(? _List_,+ _Separator_,? _Atom_) - - -Creates an atom just like concat_atom/2, but inserts _Separator_ -between each pair of atoms. For example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- concat_atom([gnu, gnat], ', ', A). - -A = 'gnu, gnat' -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -(Unimplemented) This predicate can also be used to split atoms by -instantiating _Separator_ and _Atom_: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- concat_atom(L, -, 'gnu-gnat'). - -L = [gnu, gnat] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred nth1(+ _Index_,? _List_,? _Elem_) - - -Succeeds when the _Index_-th element of _List_ unifies with - _Elem_. Counting starts at 1. - -Set environment variable. _Name_ and _Value_ should be -instantiated to atoms or integers. The environment variable will be -passed to `shell/[0-2]` and can be requested using `getenv/2`. -They also influence expand_file_name/2. - - -*/ - -/** @pred setenv(+ _Name_,+ _Value_) - - -Set environment variable. _Name_ and _Value_ should be -instantiated to atoms or integers. The environment variable will be -passed to `shell/[0-2]` and can be requested using `getenv/2`. -They also influence expand_file_name/2. - - -*/ - -/** @pred term_to_atom(? _Term_,? _Atom_) - - -Succeeds if _Atom_ describes a term that unifies with _Term_. When - _Atom_ is instantiated _Atom_ is converted and then unified with - _Term_. If _Atom_ has no valid syntax, a `syntax_error` -exception is raised. Otherwise _Term_ is ``written'' on _Atom_ -using write/1. - - -*/ - -/** @pred working_directory(- _Old_,+ _New_) - - - -Unify _Old_ with an absolute path to the current working directory -and change working directory to _New_. Use the pattern -`working_directory(CWD, CWD)` to get the current directory. See -also `absolute_file_name/2` and chdir/1. - - -*/ - -/** @pred @ _Term1_ =@= @ _Term2_ - - - -True iff _Term1_ and _Term2_ are structurally equivalent. I.e. if _Term1_ and _Term2_ are variants of each other. - - - - -@} */ - -/** @defgroup Invoking_Predicates_on_all_Members_of_a_List Invoking Predicates on all Members of a List -@ingroup YAPLibrary -@{ - - -All the predicates in this section call a predicate on all members of a -list or until the predicate called fails. The predicate is called via -`call/[2..]`, which implies common arguments can be put in -front of the arguments obtained from the list(s). For example: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- maplist(plus(1), [0, 1, 2], X). - -X = [1, 2, 3] -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -we will phrase this as `` _Predicate_ is applied on ...'' - - - - @pred maplist(+ _Pred_,+ _List_) - - - _Pred_ is applied successively on each element of _List_ until -the end of the list or _Pred_ fails. In the latter case -`maplist/2` fails. - - -*/ - -/** @pred maplist(+ _Pred_,+ _List1_,+ _List2_) - -Apply _Pred_ on all successive pairs of elements from - _List1_ and - _List2_. Fails if _Pred_ can not be applied to a -pair. See the example above. - - -*/ - -/** @pred maplist(+ _Pred_,+ _List1_,+ _List2_,+ _List4_) - -Apply _Pred_ on all successive triples of elements from _List1_, - _List2_ and _List3_. Fails if _Pred_ can not be applied to a -triple. See the example above. - - - - -@} */ - -/** @defgroup Forall Forall -@ingroup YAPPackages -@{ - - - -*/ - -/** @pred forall(+ _Cond_,+ _Action_) - - - - -For all alternative bindings of _Cond_ _Action_ can be proven. -The next example verifies that all arithmetic statements in the list - _L_ are correct. It does not say which is wrong if one proves wrong. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), - Result =:= Formula). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - -*/ - -/** @page SWIhYProlog_Global_Variables SWI Global variables - - -SWI-Prolog global variables are associations between names (atoms) and -terms. They differ in various ways from storing information using -assert/1 or recorda/3. - - + The value lives on the Prolog (global) stack. This implies -that lookup time is independent from the size of the term. -This is particulary interesting for large data structures -such as parsed XML documents or the CHR global constraint -store. - - -*/ - -/** @pred They support both global assignment using nb_setval/2 and -backtrackable assignment using b_setval/2. - - + Only one value (which can be an arbitrary complex Prolog -term) can be associated to a variable at a time. - - + Their value cannot be shared among threads. Each thread -has its own namespace and values for global variables. - - + Currently global variables are scoped globally. We may -consider module scoping in future versions. - - -Both b_setval/2 and nb_setval/2 implicitly create a variable if the -referenced name does not already refer to a variable. - -Global variables may be initialised from directives to make them -available during the program lifetime, but some considerations are -necessary for saved-states and threads. Saved-states to not store global -variables, which implies they have to be declared with initialization/1 -to recreate them after loading the saved state. Each thread has -its own set of global variables, starting with an empty set. Using -`thread_inititialization/1` to define a global variable it will be -defined, restored after reloading a saved state and created in all -threads that are created after the registration. - - -*/ - -/** @pred b_setval(+ _Name_,+ _Value_) - - -Associate the term _Value_ with the atom _Name_ or replaces -the currently associated value with _Value_. If _Name_ does -not refer to an existing global variable a variable with initial value -`[]` is created (the empty list). On backtracking the -assignment is reversed. - - -*/ - -/** @pred b_getval(+ _Name_,- _Value_) - - -Get the value associated with the global variable _Name_ and unify -it with _Value_. Note that this unification may further instantiate -the value of the global variable. If this is undesirable the normal -precautions (double negation or copy_term/2) must be taken. The -b_getval/2 predicate generates errors if _Name_ is not an atom or -the requested variable does not exist. - - -*/ - -/** @pred nb_setval(+ _Name_,+ _Value_) - - -Associates a copy of _Value_ created with duplicate_term/2 -with the atom _Name_. Note that this can be used to set an -initial value other than `[]` prior to backtrackable assignment. - - -*/ - -/** @pred nb_getval(+ _Name_,- _Value_) - - -The nb_getval/2 predicate is a synonym for b_getval/2, introduced for -compatibility and symmetry. As most scenarios will use a particular -global variable either using non-backtrackable or backtrackable -assignment, using nb_getval/2 can be used to document that the -variable is used non-backtrackable. - - -*/ - -/** @pred nb_current(? _Name_,? _Value_) - - -Enumerate all defined variables with their value. The order of -enumeration is undefined. - - -*/ - -/** @pred nb_delete(? _Name_) - -Delete the named global variable. - - - -@} */ - -/** @defgroup Compatibility_of_Global_Variables Compatibility of Global Variables -@ingroup YAPPackages -@{ - -Global variables have been introduced by various Prolog -implementations recently. YAP follows their implementation in SWI-Prolog, itself -based on hProlog by Bart Demoen. Jan and Bart -decided that the semantics if hProlog nb_setval/2, which is -equivalent to nb_linkval/2 is not acceptable for normal Prolog -users as the behaviour is influenced by how builtin predicates -constructing terms (read/1, =../2, etc.) are implemented. - -GNU-Prolog provides a rich set of global variables, including arrays. -Arrays can be implemented easily in SWI-Prolog using functor/3 and -`setarg/3` due to the unrestricted arity of compound terms. - -*/ - -/** @page Extensions Extensions to Prolog - -YAP includes a number of extensions over the original Prolog -language. Next, we discuss support to the most important ones. - - -@} */ - -/** @defgroup Rational_Trees Rational Trees -@ingroup YAPPackages -@{ - -Prolog unification is not a complete implementation. For efficiency -considerations, Prolog systems do not perform occur checks while -unifying terms. As an example, `X = a(X)` will not fail but instead -will create an infinite term of the form `a(a(a(a(a(...)))))`, or -rational tree. - -Rational trees are now supported by default in YAP. In previous -versions, this was not the default and these terms could easily lead -to infinite computation. For example, `X = a(X), X = X` would -enter an infinite loop. - -The `RATIONAL_TREES` flag improves support for these -terms. Internal primitives are now aware that these terms can exist, and -will not enter infinite loops. Hence, the previous unification will -succeed. Another example, `X = a(X), ground(X)` will succeed -instead of looping. Other affected built-ins include the term comparison -primitives, numbervars/3, copy_term/2, and the internal -data base routines. The support does not extend to Input/Output routines -or to assert/1 YAP does not allow directly reading -rational trees, and you need to use `write_depth/2` to avoid -entering an infinite cycle when trying to write an infinite term. - - -@} */ - -/** @defgroup CohYroutining Co-routining -@ingroup YAPPackages -@{ - -Prolog uses a simple left-to-right flow of control. It is sometimes -convenient to change this control so that goals will only be executed -when conditions are fulfilled. This may result in a more "data-driven" -execution, or may be necessary to correctly implement extensions such as -negation by default. - -The `COROUTINING` flag enables this option. Note that the support for -coroutining will in general slow down execution. - -The following declaration is supported: - - + block/1 -The argument to `block/1` is a condition on a goal or a conjunction -of conditions, with each element separated by commas. Each condition is -of the form `predname( _C1_,..., _CN_)`, where _N_ is the -arity of the goal, and each _CI_ is of the form `-`, if the -argument must suspend until the first such variable is bound, or -`?`, otherwise. - - + wait/1 -The argument to `wait/1` is a predicate descriptor or a conjunction -of these predicates. These predicates will suspend until their first -argument is bound. - - -The following primitives are supported: - - -*/ - -/** @pred dif( _X_, _Y_) - - -Succeed if the two arguments do not unify. A call to dif/2 will -suspend if unification may still succeed or fail, and will fail if they -always unify. - - -*/ - -/** @pred freeze(? _X_,: _G_) - - -Delay execution of goal _G_ until the variable _X_ is bound. - - -*/ - -/** @pred frozen( _X_, _G_) - - -Unify _G_ with a conjunction of goals suspended on variable _X_, -or `true` if no goal has suspended. - - -*/ - -/** @pred when(+ _C_,: _G_) - - -Delay execution of goal _G_ until the conditions _C_ are -satisfied. The conditions are of the following form: - - + _C1_, _C2_ -Delay until both conditions _C1_ and _C2_ are satisfied. - + _C1_; _C2_ -Delay until either condition _C1_ or condition _C2_ is satisfied. - + ?=( _V1_, _C2_) -Delay until terms _V1_ and _V1_ have been unified. - + nonvar( _V_) -Delay until variable _V_ is bound. - + ground( _V_) -Delay until variable _V_ is ground. - - -Note that when/2 will fail if the conditions fail. - - -*/ - -/** @pred call_residue(: _G_, _L_) - - - -Call goal _G_. If subgoals of _G_ are still blocked, return -a list containing these goals and the variables they are blocked in. The -goals are then considered as unblocked. The next example shows a case -where dif/2 suspends twice, once outside call_residue/2, -and the other inside: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- dif(X,Y), - call_residue((dif(X,Y),(X = f(Z) ; Y = f(Z))), L). - -X = f(Z), -L = [[Y]-dif(f(Z),Y)], -dif(f(Z),Y) ? ; - -Y = f(Z), -L = [[X]-dif(X,f(Z))], -dif(X,f(Z)) ? ; - -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The system only reports one invocation of dif/2 as having -suspended. - - -*/ - -/** @pred call_residue_vars(: _G_, _L_) - - - -Call goal _G_ and unify _L_ with a list of all constrained variables created during execution of _G_: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ?- dif(X,Z), call_residue_vars(dif(X,Y),L). -dif(X,Z), call_residue_vars(dif(X,Y),L). -L = [Y], -dif(X,Z), -dif(X,Y) ? ; - -no -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup Attributed_Variables Attributed Variables -@ingroup YAPPackages -@{ - -YAP supports attributed variables, originally developed at OFAI by -Christian Holzbaur. Attributes are a means of declaring that an -arbitrary term is a property for a variable. These properties can be -updated during forward execution. Moreover, the unification algorithm is -aware of attributed variables and will call user defined handlers when -trying to unify these variables. - -Attributed variables provide an elegant abstraction over which one can -extend Prolog systems. Their main application so far has been in -implementing constraint handlers, such as Holzbaur's CLPQR, Fruewirth -and Holzbaur's CHR, and CLP(BN). - -Different Prolog systems implement attributed variables in different -ways. Traditionally, YAP has used the interface designed by SICStus -Prolog. This interface is still -available in the atts library, but from YAP-6.0.3 we recommend using -the hProlog, SWI style interface. The main reason to do so is that -most packages included in YAP that use attributed variables, such as CHR, CLP(FD), and CLP(QR), -rely on the SWI-Prolog interface. - - -@} */ - -/** @defgroup New_Style_Attribute_Declarations hProlog and SWI-Prolog style Attribute Declarations -@ingroup YAPPackages -@{ - -The following documentation is taken from the SWI-Prolog manual. - -Binding an attributed variable schedules a goal to be executed at the -first possible opportunity. In the current implementation the hooks are -executed immediately after a successful unification of the clause-head -or successful completion of a foreign language (built-in) predicate. Each -attribute is associated to a module and the hook attr_unify_hook/2 is -executed in this module. The example below realises a very simple and -incomplete finite domain reasoner. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(domain, - [ domain/2 % Var, ?Domain - ]). -:- use_module(library(ordsets)). - -domain(X, Dom) :- - var(Dom), !, - get_attr(X, domain, Dom). -domain(X, List) :- - list_to_ord_set(List, Domain), - put_attr(Y, domain, Domain), - X = Y. - -% An attributed variable with attribute value Domain has been -% assigned the value Y - -attr_unify_hook(Domain, Y) :- - ( get_attr(Y, domain, Dom2) - -> ord_intersection(Domain, Dom2, NewDomain), - ( NewDomain == [] - -> fail - ; NewDomain = [Value] - -> Y = Value - ; put_attr(Y, domain, NewDomain) - ) - ; var(Y) - -> put_attr( Y, domain, Domain ) - ; ord_memberchk(Y, Domain) - ). - -% Translate attributes from this module to residual goals - -attribute_goals(X) --> - { get_attr(X, domain, List) }, - [domain(X, List)]. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Before explaining the code we give some example queries: - -The predicate `domain/2` fetches (first clause) or assigns -(second clause) the variable a domain, a set of values it can -be unified with. In the second clause first associates the domain -with a fresh variable and then unifies X to this variable to deal -with the possibility that X already has a domain. The -predicate attr_unify_hook/2 is a hook called after a variable with -a domain is assigned a value. In the simple case where the variable -is bound to a concrete value we simply check whether this value is in -the domain. Otherwise we take the intersection of the domains and either -fail if the intersection is empty (first example), simply assign the -value if there is only one value in the intersection (second example) or -assign the intersection as the new domain of the variable (third -example). The nonterminal `attribute_goals/3` is used to translate -remaining attributes to user-readable goals that, when executed, reinstate -these attributes. - - - - @pred put_attr(+ _Var_,+ _Module_,+ _Value_) - - - -If _Var_ is a variable or attributed variable, set the value for the -attribute named _Module_ to _Value_. If an attribute with this -name is already associated with _Var_, the old value is replaced. -Backtracking will restore the old value (i.e., an attribute is a mutable -term. See also `setarg/3`). This predicate raises a representation error if - _Var_ is not a variable and a type error if _Module_ is not an atom. - - -*/ - -/** @pred get_attr(+ _Var_,+ _Module_,- _Value_) - - - -Request the current _value_ for the attribute named _Module_. If - _Var_ is not an attributed variable or the named attribute is not -associated to _Var_ this predicate fails silently. If _Module_ -is not an atom, a type error is raised. - - -*/ - -/** @pred del_attr(+ _Var_,+ _Module_) - - - -Delete the named attribute. If _Var_ loses its last attribute it -is transformed back into a traditional Prolog variable. If _Module_ -is not an atom, a type error is raised. In all other cases this -predicate succeeds regardless whether or not the named attribute is -present. - - -*/ - -/** @pred attr_unify_hook(+ _AttValue_,+ _VarValue_) - - - -Hook that must be defined in the module an attributed variable refers -to. Is is called after the attributed variable has been -unified with a non-var term, possibly another attributed variable. - _AttValue_ is the attribute that was associated to the variable -in this module and _VarValue_ is the new value of the variable. -Normally this predicate fails to veto binding the variable to - _VarValue_, forcing backtracking to undo the binding. If - _VarValue_ is another attributed variable the hook often combines -the two attribute and associates the combined attribute with - _VarValue_ using put_attr/3. - - -*/ - -/** @pred attr_portray_hook(+ _AttValue_,+ _Var_) - - - -Called by write_term/2 and friends for each attribute if the option -`attributes(portray)` is in effect. If the hook succeeds the -attribute is considered printed. Otherwise `Module = ...` is -printed to indicate the existence of a variable. - - -*/ - -/** @pred attribute_goals(+ _Var_,- _Gs_,+ _GsRest_) - - - -This nonterminal, if it is defined in a module, is used by _copy_term/3_ -to project attributes of that module to residual goals. It is also -used by the toplevel to obtain residual goals after executing a query. - - -Normal user code should deal with put_attr/3, get_attr/3 and del_attr/2. -The routines in this section fetch or set the entire attribute list of a -variables. Use of these predicates is anticipated to be restricted to -printing and other special purpose operations. - - - - @pred get_attrs(+ _Var_,- _Attributes_) - - - -Get all attributes of _Var_. _Attributes_ is a term of the form -`att( _Module_, _Value_, _MoreAttributes_)`, where _MoreAttributes_ is -`[]` for the last attribute. - - -*/ - -/** @pred put_attrs(+ _Var_,+ _Attributes_) - - -Set all attributes of _Var_. See get_attrs/2 for a description of - _Attributes_. - - -*/ - -/** @pred del_attrs(+ _Var_) - - -If _Var_ is an attributed variable, delete all its -attributes. In all other cases, this predicate succeeds without -side-effects. - - -*/ - -/** @pred term_attvars(+ _Term_,- _AttVars_) - - - _AttVars_ is a list of all attributed variables in _Term_ and -its attributes. I.e., term_attvars/2 works recursively through -attributes. This predicate is Cycle-safe. - - -*/ - -/** @pred copy_term(? _TI_,- _TF_,- _Goals_) - -Term _TF_ is a variant of the original term _TI_, such that for -each variable _V_ in the term _TI_ there is a new variable _V'_ -in term _TF_ without any attributes attached. Attributed -variables are thus converted to standard variables. _Goals_ is -unified with a list that represents the attributes. The goal -`maplist(call, _Goals_)` can be called to recreate the -attributes. - -Before the actual copying, `copy_term/3` calls -`attribute_goals/1` in the module where the attribute is -defined. - - -*/ - -/** @pred copy_term_nat(? _TI_,- _TF_) - - -As copy_term/2. Attributes however, are not copied but replaced -by fresh variables. - - - - -@} */ - -/** @defgroup Old_Style_Attribute_Declarations SICStus Prolog style Attribute Declarations -@ingroup YAPLibrary -@{ - -Old style attribute declarations are activated through loading the library atts . The command - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -| ?- use_module(library(atts)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -enables this form of use of attributed variables. The package provides the -following functionality: - - + Each attribute must be declared first. Attributes are described by a functor -and are declared per module. Each Prolog module declares its own sets of -attributes. Different modules may have different functors with the same -module. - + The built-in put_atts/2 adds or deletes attributes to a -variable. The variable may be unbound or may be an attributed -variable. In the latter case, YAP discards previous values for the -attributes. - + The built-in get_atts/2 can be used to check the values of -an attribute associated with a variable. - + The unification algorithm calls the user-defined predicate -verify_attributes/3 before trying to bind an attributed -variable. Unification will resume after this call. - + The user-defined predicate -attribute_goal/2 converts from an attribute to a goal. - + The user-defined predicate -project_attributes/2 is used from a set of variables into a set of -constraints or goals. One application of project_attributes/2 is in -the top-level, where it is used to output the set of -floundered constraints at the end of a query. - - - -@} */ - -/** @defgroup Attribute_Declarations Attribute Declarations -@ingroup Old_Style_Attribute_Declarations -@{ - -Attributes are compound terms associated with a variable. Each attribute -has a name which is private to the module in which the -attribute was defined. Variables may have at most one attribute with a -name. Attribute names are defined with the following declaration: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- attribute AttributeSpec, ..., AttributeSpec. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -where each _AttributeSpec_ has the form ( _Name_/ _Arity_). -One single such declaration is allowed per module _Module_. - -Although the YAP module system is predicate based, attributes are local -to modules. This is implemented by rewriting all calls to the -built-ins that manipulate attributes so that attribute names are -preprocessed depending on the module. The `user:goal_expansion/3` -mechanism is used for this purpose. - - -@} */ - -/** @defgroup Attribute_Manipulation Attribute Manipulation -@ingroup Old_Style_Attribute_Declarations -@{ - -The attribute manipulation predicates always work as follows: - -
        - + The first argument is the unbound variable associated with -attributes, - + The second argument is a list of attributes. Each attribute will -be a Prolog term or a constant, prefixed with the + and - unary -operators. The prefix + may be dropped for convenience. -
      - -The following three procedures are available to the user. Notice that -these built-ins are rewritten by the system into internal built-ins, and -that the rewriting process depends on the module on which the -built-ins have been invoked. - - -*/ - -/** @pred _Module_:get_atts( _-Var_, _?ListOfAttributes_) - - -Unify the list _?ListOfAttributes_ with the attributes for the unbound -variable _Var_. Each member of the list must be a bound term of the -form `+( _Attribute_)`, `-( _Attribute_)` (the kbd -prefix may be dropped). The meaning of + and - is: - + +( _Attribute_) -Unifies _Attribute_ with a corresponding attribute associated with - _Var_, fails otherwise. - - + -( _Attribute_) -Succeeds if a corresponding attribute is not associated with - _Var_. The arguments of _Attribute_ are ignored. - - -*/ - -/** @pred _Module_:put_atts( _-Var_, _?ListOfAttributes_) - - -Associate with or remove attributes from a variable _Var_. The -attributes are given in _?ListOfAttributes_, and the action depends -on how they are prefixed: - + +( _Attribute_) -Associate _Var_ with _Attribute_. A previous value for the -attribute is simply replace (like with `set_mutable/2`). - - + -( _Attribute_) -Remove the attribute with the same name. If no such attribute existed, -simply succeed. - - - -@} */ - -/** @defgroup Attributed_Unification Attributed Unification -@ingroup Old_Style_Attribute_Declarations -@{ - -The user-predicate predicate verify_attributes/3 is called when -attempting to unify an attributed variable which might have attributes -in some _Module_. - - -*/ - -/** @pred _Module_:verify_attributes( _-Var_, _+Value_, _-Goals_) - - - -The predicate is called when trying to unify the attributed variable - _Var_ with the Prolog term _Value_. Note that _Value_ may be -itself an attributed variable, or may contain attributed variables. The -goal verify_attributes/3 is actually called before _Var_ is -unified with _Value_. - -It is up to the user to define which actions may be performed by -verify_attributes/3 but the procedure is expected to return in - _Goals_ a list of goals to be called after _Var_ is -unified with _Value_. If verify_attributes/3 fails, the -unification will fail. - -Notice that the verify_attributes/3 may be called even if _Var_\< -has no attributes in module Module. In this case the routine should -simply succeed with _Goals_ unified with the empty list. - - -*/ - -/** @pred attvar( _-Var_) - - -Succeed if _Var_ is an attributed variable. - - - -@} */ - -/** @defgroup Displaying_Attributes Displaying Attributes -@ingroup Old_Style_Attribute_Declarations -@{ - -Attributes are usually presented as goals. The following routines are -used by built-in predicates such as call_residue/2 and by the -Prolog top-level to display attributes: - - -*/ - -/** @pred _Module_:attribute_goal( _-Var_, _-Goal_) -User-defined procedure, called to convert the attributes in _Var_ to -a _Goal_. Should fail when no interpretation is available. - - - - -@} */ - -/** @defgroup Projecting_Attributes Projecting Attributes -@ingroup Old_Style_Attribute_Declarations -@{ - -Constraint solvers must be able to project a set of constraints to a set -of variables. This is useful when displaying the solution to a goal, but -may also be used to manipulate computations. The user-defined -project_attributes/2 is responsible for implementing this -projection. - - -*/ - -/** @pred _Module_:project_attributes( _+QueryVars_, _+AttrVars_) - - -Given a list of variables _QueryVars_ and list of attributed -variables _AttrVars_, project all attributes in _AttrVars_ to - _QueryVars_. Although projection is constraint system dependent, -typically this will involve expressing all constraints in terms of - _QueryVars_ and considering all remaining variables as existentially -quantified. - - -Projection interacts with attribute_goal/2 at the Prolog top -level. When the query succeeds, the system first calls -project_attributes/2. The system then calls -attribute_goal/2 to get a user-level representation of the -constraints. Typically, attribute_goal/2 will convert from the -original constraints into a set of new constraints on the projection, -and these constraints are the ones that will have an -attribute_goal/2 handler. - - -@} */ - -/** @defgroup Attribute_Examples Attribute Examples -@ingroup Old_Style_Attribute_Declarations -@{ - -The following two examples example is taken from the SICStus Prolog manual. It -sketches the implementation of a simple finite domain ``solver''. Note -that an industrial strength solver would have to provide a wider range -of functionality and that it quite likely would utilize a more efficient -representation for the domains proper. The module exports a single -predicate `domain( _-Var_, _?Domain_)` which associates - _Domain_ (a list of terms) with _Var_. A variable can be -queried for its domain by leaving _Domain_ unbound. - -We do not present here a definition for project_attributes/2. -Projecting finite domain constraints happens to be difficult. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(domain, [domain/2]). - -:- use_module(library(atts)). -:- use_module(library(ordsets), [ - ord_intersection/3, - ord_intersect/2, - list_to_ord_set/2 - ]). - -:- attribute dom/1. - -verify_attributes(Var, Other, Goals) :- - get_atts(Var, dom(Da)), !, % are we involved? - ( var(Other) -> % must be attributed then - ( get_atts(Other, dom(Db)) -> % has a domain? - ord_intersection(Da, Db, Dc), - Dc = [El|Els], % at least one element - ( Els = [] -> % exactly one element - Goals = [Other=El] % implied binding - ; Goals = [], - put_atts(Other, dom(Dc))% rescue intersection - ) - ; Goals = [], - put_atts(Other, dom(Da)) % rescue the domain - ) - ; Goals = [], - ord_intersect([Other], Da) % value in domain? - ). -verify_attributes(_, _, []). % unification triggered - % because of attributes - % in other modules - -attribute_goal(Var, domain(Var,Dom)) :- % interpretation as goal - get_atts(Var, dom(Dom)). - -domain(X, Dom) :- - var(Dom), !, - get_atts(X, dom(Dom)). -domain(X, List) :- - list_to_ord_set(List, Set), - Set = [El|Els], % at least one element - ( Els = [] -> % exactly one element - X = El % implied binding - ; put_atts(Fresh, dom(Set)), - X = Fresh % may call - % verify_attributes/3 - ). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Note that the ``implied binding'' `Other=El` was deferred until after -the completion of `verify_attribute/3`. Otherwise, there might be a -danger of recursively invoking `verify_attribute/3`, which might bind -`Var`, which is not allowed inside the scope of `verify_attribute/3`. -Deferring unifications into the third argument of `verify_attribute/3` -effectively serializes the calls to `verify_attribute/3`. - -Assuming that the code resides in the file domain.yap, we -can use it via: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -| ?- use_module(domain). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Let's test it: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]). - -domain(X,[1,5,6,7]), -domain(Y,[3,4,5,6]), -domain(Z,[1,6,7,8]) ? - -yes -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), - X=Y. - -Y = X, -domain(X,[5,6]), -domain(Z,[1,6,7,8]) ? - -yes -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), - X=Y, Y=Z. - -X = 6, -Y = 6, -Z = 6 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -To demonstrate the use of the _Goals_ argument of -verify_attributes/3, we give an implementation of -freeze/2. We have to name it `myfreeze/2` in order to -avoid a name clash with the built-in predicate of the same name. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(myfreeze, [myfreeze/2]). - -:- use_module(library(atts)). - -:- attribute frozen/1. - -verify_attributes(Var, Other, Goals) :- - get_atts(Var, frozen(Fa)), !, % are we involved? - ( var(Other) -> % must be attributed then - ( get_atts(Other, frozen(Fb)) % has a pending goal? - -> put_atts(Other, frozen((Fa,Fb))) % rescue conjunction - ; put_atts(Other, frozen(Fa)) % rescue the pending goal - ), - Goals = [] - ; Goals = [Fa] - ). -verify_attributes(_, _, []). - -attribute_goal(Var, Goal) :- % interpretation as goal - get_atts(Var, frozen(Goal)). - -myfreeze(X, Goal) :- - put_atts(Fresh, frozen(Goal)), - Fresh = X. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Assuming that this code lives in file myfreeze.yap, -we would use it via: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -| ?- use_module(myfreeze). -| ?- myfreeze(X,print(bound(x,X))), X=2. - -bound(x,2) % side effect -X = 2 % bindings -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The two solvers even work together: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -| ?- myfreeze(X,print(bound(x,X))), domain(X,[1,2,3]), - domain(Y,[2,10]), X=Y. - -bound(x,2) % side effect -X = 2, % bindings -Y = 2 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The two example solvers interact via bindings to shared attributed -variables only. More complicated interactions are likely to be found -in more sophisticated solvers. The corresponding -verify_attributes/3 predicates would typically refer to the -attributes from other known solvers/modules via the module prefix in -` _Module_:get_atts/2`. - - -@} */ - -/** @defgroup CLPR Constraint Logic Programming over Reals -@ingroup YAPPackages -@{ - -YAP now uses the CLP(R) package developed by Leslie De Koninck, -K.U. Leuven as part of a thesis with supervisor Bart Demoen and daily -advisor Tom Schrijvers, and distributed with SWI-Prolog. - -This CLP(R) system is a port of the CLP(Q,R) system of Sicstus Prolog -and YAP by Christian Holzbaur: Holzbaur C.: OFAI clp(q,r) Manual, -Edition 1.3.3, Austrian Research Institute for Artificial -Intelligence, Vienna, TR-95-09, 1995, - This -port only contains the part concerning real arithmetics. This manual -is roughly based on the manual of the above mentioned *CLP(QR)* -implementation. - -Please note that the clpr library is not an -`autoload` library and therefore this library must be loaded -explicitely before using it: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- use_module(library(clpr)). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -@} */ - -/** @defgroup CLPR_Solver_Predicates Solver Predicates -@ingroup CLPR -@{ - - -The following predicates are provided to work with constraints: - - -*/ - -/** @pred {+ _Constraints_} -Adds the constraints given by _Constraints_ to the constraint store. - - -*/ - -/** @pred entailed(+ _Constraint_) -Succeeds if _Constraint_ is necessarily true within the current -constraint store. This means that adding the negation of the constraint -to the store results in failure. - - -*/ - -/** @pred inf(+ _Expression_,- _Inf_) -Computes the infimum of _Expression_ within the current state of the -constraint store and returns that infimum in _Inf_. This predicate -does not change the constraint store. - - -*/ - -/** @pred inf(+ _Expression_,- _Sup_) -Computes the supremum of _Expression_ within the current state of -the constraint store and returns that supremum in _Sup_. This -predicate does not change the constraint store. - - -*/ - -/** @pred min(+ _Expression_) -Minimizes _Expression_ within the current constraint store. This is -the same as computing the infimum and equation the expression to that -infimum. - - -*/ - -/** @pred max(+ _Expression_) -Maximizes _Expression_ within the current constraint store. This is -the same as computing the supremum and equating the expression to that -supremum. - - -*/ - -/** @pred bb_inf(+ _Ints_,+ _Expression_,- _Inf_,- _Vertext_,+ _Eps_) -Computes the infimum of _Expression_ within the current constraint -store, with the additional constraint that in that infimum, all -variables in _Ints_ have integral values. _Vertex_ will contain -the values of _Ints_ in the infimum. _Eps_ denotes how much a -value may differ from an integer to be considered an integer. E.g. when - _Eps_ = 0.001, then X = 4.999 will be considered as an integer (5 in -this case). _Eps_ should be between 0 and 0.5. - - -*/ - -/** @pred bb_inf(+ _Ints_,+ _Expression_,- _Inf_) -The same as bb_inf/5 but without returning the values of the integers -and with an eps of 0.001. - - -*/ - -/** @pred dump(+ _Target_,+ _Newvars_,- _CodedAnswer_) -Returns the constraints on _Target_ in the list _CodedAnswer_ -where all variables of _Target_ have veen replaced by _NewVars_. -This operation does not change the constraint store. E.g. in - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -dump([X,Y,Z],[x,y,z],Cons) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - _Cons_ will contain the constraints on _X_, _Y_ and - _Z_ where these variables have been replaced by atoms `x`, `y` and `z`. - - - - -@} */ - -/** @defgroup CLPR_Syntax Syntax of the predicate arguments -@ingroup YAPPackages -@{ - - -The arguments of the predicates defined in the subsection above are -defined in the following table. Failing to meet the syntax rules will -result in an exception. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - ---> \\ single constraint \\ - | , \\ conjunction \\ - | ; \\ disjunction \\ - - ---> {<} \\ less than \\ - | {>} \\ greater than \\ - | {=<} \\ less or equal \\ - | {<=}(, ) \\ less or equal \\ - | {>=} \\ greater or equal \\ - | {=\=} \\ not equal \\ - | =:= \\ equal \\ - | = \\ equal \\ - - ---> \\ Prolog variable \\ - | \\ Prolog number (float, integer) \\ - | + \\ unary plus \\ - | - \\ unary minus \\ - | + \\ addition \\ - | - \\ substraction \\ - | * \\ multiplication \\ - | / \\ division \\ - | abs() \\ absolute value \\ - | sin() \\ sine \\ - | cos() \\ cosine \\ - | tan() \\ tangent \\ - | exp() \\ exponent \\ - | pow() \\ exponent \\ - | {^} \\ exponent \\ - | min(, ) \\ minimum \\ - | max(, ) \\ maximum \\ -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -@} */ - -/** @defgroup CLPR_Unification Use of unification -@ingroup CLPR -@{ - -Instead of using the `{}/1` predicate, you can also use the standard -unification mechanism to store constraints. The following code samples -are equivalent: - - + Unification with a variable - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -{X =:= Y} -{X = Y} -X = Y -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + Unification with a number - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -{X =:= 5.0} -{X = 5.0} -X = 5.0 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup CLPR_NonhYlinear_Constraints Non-Linear Constraints -@ingroup CLPR -@{ - - -In this version, non-linear constraints do not get solved until certain -conditions are satisfied. We call these conditions the isolation axioms. -They are given in the following table. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A = B * C when B or C is ground or // A = 5 * C or A = B * 4 \\ - A and (B or C) are ground // 20 = 5 * C or 20 = B * 4 \\ - -A = B / C when C is ground or // A = B / 3 - A and B are ground // 4 = 12 / C - -X = min(Y,Z) when Y and Z are ground or // X = min(4,3) -X = max(Y,Z) Y and Z are ground // X = max(4,3) -X = abs(Y) Y is ground // X = abs(-7) - -X = pow(Y,Z) when X and Y are ground or // 8 = 2 ^ Z -X = exp(Y,Z) X and Z are ground // 8 = Y ^ 3 -X = Y ^ Z Y and Z are ground // X = 2 ^ 3 - -X = sin(Y) when X is ground or // 1 = sin(Y) -X = cos(Y) Y is ground // X = sin(1.5707) -X = tan(Y) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -@section CHR CHR: Constraint Handling Rules -@ingroup YAPPackages - -This chapter is written by Tom Schrijvers, K.U. Leuven for the hProlog -system. Adjusted by Jan Wielemaker to fit the SWI-Prolog documentation -infrastructure and remove hProlog specific references. - -The CHR system of SWI-Prolog is the K.U.Leuven CHR system. The runtime -environment is written by Christian Holzbaur and Tom Schrijvers while the -compiler is written by Tom Schrijvers. Both are integrated with SWI-Prolog -and licenced under compatible conditions with permission from the authors. - -The main reference for SWI-Prolog's CHR system is: - - + T. Schrijvers, and B. Demoen, The K.U.Leuven CHR System: Implementation and Application, First Workshop on Constraint Handling Rules: Selected -Contributions (Fruwirth, T. and Meister, M., eds.), pp. 1--5, 2004. - - - -@} */ - -/** @defgroup CHR_Introduction Introduction -@ingroup CHR -@{ - - -Constraint Handling Rules (CHR) is a committed-choice bottom-up language -embedded in Prolog. It is designed for writing constraint solvers and is -particularily useful for providing application-specific constraints. -It has been used in many kinds of applications, like scheduling, -model checking, abduction, type checking among many others. - -CHR has previously been implemented in other Prolog systems (SICStus, -Eclipse, Yap), Haskell and Java. This CHR system is based on the -compilation scheme and runtime environment of CHR in SICStus. - -In this documentation we restrict ourselves to giving a short overview -of CHR in general and mainly focus on elements specific to this -implementation. For a more thorough review of CHR we refer the reader to -[Freuhwirth:98]. More background on CHR can be found at the CHR web site. - - -@} */ - -/** @defgroup CHR_Syntax_and_Semantics Syntax and Semantics -@ingroup YAPPackages -@{ - - - - -@} */ - -/** @defgroup CHR_Syntax CHR Syntax -Wingroup CHR -@{ - -The syntax of CHR rules in hProlog is the following: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -rules --> rule, rules. -rules --> []. - -rule --> name, actual_rule, pragma, [atom('.')]. - -name --> atom, [atom('@')]. -name --> []. - -actual_rule --> simplification_rule. -actual_rule --> propagation_rule. -actual_rule --> simpagation_rule. - -simplification_rule --> constraints, [atom('<=>')], guard, body. -propagation_rule --> constraints, [atom('==>')], guard, body. -simpagation_rule --> constraints, [atom('\')], constraints, [atom('<=>')], - guard, body. - -constraints --> constraint, constraint_id. -constraints --> constraint, [atom(',')], constraints. - -constraint --> compound_term. - -constraint_id --> []. -constraint_id --> [atom('#')], variable. - -guard --> []. -guard --> goal, [atom('|')]. - -body --> goal. - -pragma --> []. -pragma --> [atom('pragma')], actual_pragmas. - -actual_pragmas --> actual_pragma. -actual_pragmas --> actual_pragma, [atom(',')], actual_pragmas. - -actual_pragma --> [atom('passive(')], variable, [atom(')')]. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Additional syntax-related terminology: - - + *head:* the constraints in an `actual_rule` before -the arrow (either `\<=\>` or `==\>`) - - - -@} */ - -/** @defgroup Semantics Semantics -@ingroup CHR -@{ - - -In this subsection the operational semantics of CHR in Prolog are presented -informally. They do not differ essentially from other CHR systems. - -When a constraint is called, it is considered an active constraint and -the system will try to apply the rules to it. Rules are tried and executed -sequentially in the order they are written. - -A rule is conceptually tried for an active constraint in the following -way. The active constraint is matched with a constraint in the head of -the rule. If more constraints appear in the head they are looked for -among the suspended constraints, which are called passive constraints in -this context. If the necessary passive constraints can be found and all -match with the head of the rule and the guard of the rule succeeds, then -the rule is committed and the body of the rule executed. If not all the -necessary passive constraint can be found, the matching fails or the -guard fails, then the body is not executed and the process of trying and -executing simply continues with the following rules. If for a rule, -there are multiple constraints in the head, the active constraint will -try the rule sequentially multiple times, each time trying to match with -another constraint. - -This process ends either when the active constraint disappears, i.e. it -is removed by some rule, or after the last rule has been processed. In -the latter case the active constraint becomes suspended. - -A suspended constraint is eligible as a passive constraint for an active -constraint. The other way it may interact again with the rules, is when -a variable appearing in the constraint becomes bound to either a nonvariable -or another variable involved in one or more constraints. In that case the -constraint is triggered, i.e. it becomes an active constraint and all -the rules are tried. - - -@} */ - -/** @defgroup Rule_Types -@ingroup CHR -@{ - -There are three different kinds of rules, each with their specific semantics: - - + simplification -The simplification rule removes the constraints in its head and calls its body. - - + propagation -The propagation rule calls its body exactly once for the constraints in -its head. - - + simpagation -The simpagation rule removes the constraints in its head after the -`\\` and then calls its body. It is an optimization of -simplification rules of the form: \\[constraints_1, constraints_2 \<=\> -constraints_1, body \\] Namely, in the simpagation form: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -constraints1 \ constraints2 <=> body -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - _constraints1_ -constraints are not called in the body. - - - -@} */ - -/** @defgroup CHR_Rule_Names Rule Names -@ingroup CHR -@{ - -Naming a rule is optional and has no semantical meaning. It only functions -as documentation for the programmer. - - -@} */ - -/** @defgroup CHRPragmas Pragmas -@ingroup CHR_Rule_Names -@{ - -The semantics of the pragmas are: - - + passive(Identifier) -The constraint in the head of a rule _Identifier_ can only act as a -passive constraint in that rule. - - -Additional pragmas may be released in the future. - - -@} */ - -/** @defgroup CHR_Options Options -@ingroup CHR_Rule_Names -@{ - -It is possible to specify options that apply to all the CHR rules in the module. -Options are specified with the `option/2` declaration: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - option(Option,Value). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Available options are: - - + check_guard_bindings -This option controls whether guards should be checked for illegal -variable bindings or not. Possible values for this option are -`on`, to enable the checks, and `off`, to disable the -checks. - - + optimize -This is an experimental option controlling the degree of optimization. -Possible values are `full`, to enable all available -optimizations, and `off` (default), to disable all optimizations. -The default is derived from the SWI-Prolog flag `optimise`, where -`true` is mapped to `full`. Therefore the commandline -option `-O` provides full CHR optimization. -If optimization is enabled, debugging should be disabled. - - + debug -This options enables or disables the possibility to debug the CHR code. -Possible values are `on` (default) and `off`. See -`debugging` for more details on debugging. The default is -derived from the prolog flag `generate_debug_info`, which -is `true` by default. See `-nodebug`. -If debugging is enabled, optimization should be disabled. - - + mode -This option specifies the mode for a particular constraint. The -value is a term with functor and arity equal to that of a constraint. -The arguments can be one of `-`, `+` or `?`. -The latter is the default. The meaning is the following: - - + - -The corresponding argument of every occurrence -of the constraint is always unbound. - + + -The corresponding argument of every occurrence -of the constraint is always ground. - + ? -The corresponding argument of every occurrence -of the constraint can have any instantiation, which may change -over time. This is the default value. - -The declaration is used by the compiler for various optimizations. -Note that it is up to the user the ensure that the mode declaration -is correct with respect to the use of the constraint. -This option may occur once for each constraint. - - + type_declaration -This option specifies the argument types for a particular constraint. The -value is a term with functor and arity equal to that of a constraint. -The arguments can be a user-defined type or one of -the built-in types: - - + int -The corresponding argument of every occurrence -of the constraint is an integer number. - + float -...{} a floating point number. - + number -...{} a number. - + natural -...{} a positive integer. - + any -The corresponding argument of every occurrence -of the constraint can have any type. This is the default value. - - -Currently, type declarations are only used to improve certain -optimizations (guard simplification, occurrence subsumption, ...{}). - - + type_definition -This option defines a new user-defined type which can be used in -type declarations. The value is a term of the form -`type(` _name_`,` _list_`)`, where - _name_ is a term and _list_ is a list of alternatives. -Variables can be used to define generic types. Recursive definitions -are allowed. Examples are - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -type(bool,[true,false]). -type(complex_number,[float + float * i]). -type(binary_tree(T),[ leaf(T) | node(binary_tree(T),binary_tree(T)) ]). -type(list(T),[ [] | [T | list(T)]). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - -The mode, type_declaration and type_definition options are provided -for backward compatibility. The new syntax is described below. - - -@} */ - -/** @defgroup CHR_in_YAP_Programs CHR in YAP Programs -@ingroup CHR -@{ - - -The CHR constraints defined in a particulary chr file are -associated with a module. The default module is `user`. One should -never load different chr files with the same CHR module name. - - -@} */ - -/** @defgroup Constraint_declaration Constraint declaration -@ingroup CHR_in_YAP_Programs -@{ - - -Every constraint used in CHR rules has to be declared. -There are two ways to do this. The old style is as follows: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -option(type_definition,type(list(T),[ [] , [T|list(T)] ]). -option(mode,foo(+,?)). -option(type_declaration,foo(list(int),float)). -:- constraints foo/2, bar/0. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The new style is as follows: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- chr_type list(T) ---> [] ; [T|list(T)]. -:- constraints foo(+list(int),?float), bar. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -@} */ - -/** @defgroup Compilation Compilation - -The@{ - SWI-Prolog CHR compiler exploits term_expansion/2 rules to translate -the constraint handling rules to plain Prolog. These rules are loaded -from the library chr. They are activated if the compiled file -has the chr extension or after finding a declaration of the -format below. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- constraints ... -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -It is adviced to define CHR rules in a module file, where the module -declaration is immediately followed by including the chr -library as examplified below: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(zebra, [ zebra/0 ]). -:- use_module(library(chr)). - -:- constraints ... -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Using this style CHR rules can be defined in ordinary Prolog -pl files and the operator definitions required by CHR do not -leak into modules where they might cause conflicts. - - -@} */ - -/** @defgroup CHR_Debugging Debugging -@ingroup CHR -@{ - - - -The CHR debugging facilities are currently rather limited. Only tracing -is currently available. To use the CHR debugging facilities for a CHR -file it must be compiled for debugging. Generating debug info is -controlled by the CHR option debug, whose default is derived -from the SWI-Prolog flag `generate_debug_info`. Therefore debug -info is provided unless the `-nodebug` is used. - - -@} */ - -/** @defgroup Ports Ports -@ingroup CHR -@{ - - -For CHR constraints the four standard ports are defined: - - + call -A new constraint is called and becomes active. - + exit -An active constraint exits: it has either been inserted in the store after -trying all rules or has been removed from the constraint store. - + fail -An active constraint fails. - + redo -An active constraint starts looking for an alternative solution. - - -In addition to the above ports, CHR constraints have five additional -ports: - - + wake -A suspended constraint is woken and becomes active. - + insert -An active constraint has tried all rules and is suspended in -the constraint store. - + remove -An active or passive constraint is removed from the constraint -store, if it had been inserted. - + try -An active constraints tries a rule with possibly -some passive constraints. The try port is entered -just before committing to the rule. - + apply -An active constraints commits to a rule with possibly -some passive constraints. The apply port is entered -just after committing to the rule. - - - -@} */ - -/** @defgroup Tracing Tracing -@ingroup CHR -@{ - - -Tracing is enabled with the chr_trace/0 predicate -and disabled with the chr_notrace/0 predicate. - -When enabled the tracer will step through the `call`, -`exit`, `fail`, `wake` and `apply` ports, -accepting debug commands, and simply write out the other ports. - -The following debug commans are currently supported: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - CHR debug options: - - creep c creep - s skip - g ancestors - n nodebug - b break - a abort - f fail - ? help h help -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Their meaning is: - - + creep -Step to the next port. - + skip -Skip to exit port of this call or wake port. - + ancestors -Print list of ancestor call and wake ports. - + nodebug -Disable the tracer. - + break -Enter a recursive Prolog toplevel. See break/0. - + abort -Exit to the toplevel. See abort/0. - + fail -Insert failure in execution. - + help -Print the above available debug options. - - - -@} */ - -/** @defgroup CHR_Debugging_Predicates CHR Debugging Predicates -@ingroup CHR -@{ - - -The chr module contains several predicates that allow -inspecting and printing the content of the constraint store. - - + chr_trace/0 -Activate the CHR tracer. By default the CHR tracer is activated and -deactivated automatically by the Prolog predicates trace/0 and -notrace/0. - - -*/ - -/** @pred chr_notrace/0 -De-activate the CHR tracer. By default the CHR tracer is activated and -deactivated automatically by the Prolog predicates trace/0 and -notrace/0. - - + chr_leash/0 - -Define the set of CHR ports on which the CHR -tracer asks for user intervention (i.e. stops). _Spec_ is either a -list of ports or a predefined `alias'. Defined aliases are: -`full` to stop at all ports, `none` or `off` to never -stop, and `default` to stop at the `call`, `exit`, -`fail`, `wake` and `apply` ports. See also leash/1. - - -*/ - -/** @pred chr_show_store(+ _Mod_) -Prints all suspended constraints of module _Mod_ to the standard -output. This predicate is automatically called by the SWI-Prolog toplevel at -the end of each query for every CHR module currently loaded. The prolog-flag -`chr_toplevel_show_store` controls whether the toplevel shows the -constraint stores. The value `true` enables it. Any other value -disables it. - - - - -@} */ - -/** @defgroup CHR_Examples Examples -@ingroup CHR -@{ - - - -Here are two example constraint solvers written in CHR. - - + -The program below defines a solver with one constraint, -`leq/2`, which is a less-than-or-equal constraint. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(leq,[cycle/3, leq/2]). -:- use_module(library(chr)). - -:- constraints leq/2. -reflexivity @ leq(X,X) <=> true. -antisymmetry @ leq(X,Y), leq(Y,X) <=> X = Y. -idempotence @ leq(X,Y) \ leq(X,Y) <=> true. -transitivity @ leq(X,Y), leq(Y,Z) ==> leq(X,Z). - -cycle(X,Y,Z):- - leq(X,Y), - leq(Y,Z), - leq(Z,X). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + -The program below implements a simple finite domain -constraint solver. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- module(dom,[dom/2]). -:- use_module(library(chr)). - -:- constraints dom/2. - -dom(X,[]) <=> fail. -dom(X,[Y]) <=> X = Y. -dom(X,L1), dom(X,L2) <=> intersection(L1,L2,L3), dom(X,L3). - -intersection([],_,[]). -intersection([H|T],L2,[H|L3]) :- - member(H,L2), !, - intersection(T,L2,L3). -intersection([_|T],L2,L3) :- - intersection(T,L2,L3). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup CHR_Compatibility Compatibility with SICStus CHR -@ingroup YAPPackages -@{ - - - -There are small differences between CHR in SWI-Prolog and newer -YAPs and SICStus and older versions of YAP. Besides differences in -available options and pragmas, the following differences should be -noted: - - + [The handler/1 declaration] -In SICStus every CHR module requires a `handler/1` -declaration declaring a unique handler name. This declaration is valid -syntax in SWI-Prolog, but will have no effect. A warning will be given -during compilation. - - + [The rules/1 declaration] -In SICStus, for every CHR module it is possible to only enable a subset -of the available rules through the `rules/1` declaration. The -declaration is valid syntax in SWI-Prolog, but has no effect. A -warning is given during compilation. - - + [Sourcefile naming] -SICStus uses a two-step compiler, where chr files are -first translated into pl files. For SWI-Prolog CHR -rules may be defined in a file with any extension. - - - -@} */ - -/** @defgroup CHR_Guidelines Guidelines -@ingroup YAPPackages -@{ - - - -In this section we cover several guidelines on how to use CHR to write -constraint solvers and how to do so efficiently. - - + [Set semantics] -The CHR system allows the presence of identical constraints, i.e. -multiple constraints with the same functor, arity and arguments. For -most constraint solvers, this is not desirable: it affects efficiency -and possibly termination. Hence appropriate simpagation rules should be -added of the form: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -{constraint \ constraint <=> true}. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - + [Multi-headed rules] -Multi-headed rules are executed more efficiently when the constraints -share one or more variables. - - + [Mode and type declarations] -Provide mode and type declarations to get more efficient program execution. -Make sure to disable debug (`-nodebug`) and enable optimization -(`-O`). - - - -@} */ - -/** @defgroup Logtalk Logtalk -@ingroup YAPPackages -@{ - -The Logtalk object-oriented extension is available after running its -standalone installer by using the `yaplgt` command in POSIX -systems or by using the `Logtalk - YAP` shortcut in the Logtalk -program group in the Start Menu on Windows systems. For more information -please see the URL . - - -\copydoc real - - -@} */ - -/** @defgroup Threads Threads -@ingroup YAPBuiltins -@{ - -YAP implements a SWI-Prolog compatible multithreading -library. Like in SWI-Prolog, Prolog threads have their own stacks and -only share the Prolog heap: predicates, records, flags and other -global non-backtrackable data. The package is based on the POSIX thread -standard (Butenhof:1997:PPT) used on most popular systems except -for MS-Windows. - - -@} */ - -/** @defgroup Creating_and_Destroying_Prolog_Threads Creating and Destroying Prolog Threads -@ingroup Threads -@{ - - - - @pred thread_create(: _Goal_, - _Id_, + _Options_) - - - -Create a new Prolog thread (and underlying C-thread) and start it -by executing _Goal_. If the thread is created successfully, the -thread-identifier of the created thread is unified to _Id_. - _Options_ is a list of options. Currently defined options are: - - + stack -Set the limit in K-Bytes to which the Prolog stacks of -this thread may grow. If omitted, the limit of the calling thread is -used. See also the commandline `-S` option. - - + trail -Set the limit in K-Bytes to which the trail stack of this thread may -grow. If omitted, the limit of the calling thread is used. See also the -commandline option `-T`. - - + alias -Associate an alias-name with the thread. This named may be used to -refer to the thread and remains valid until the thread is joined -(see thread_join/2). - - + at_exit -Define an exit hook for the thread. This hook is called when the thread -terminates, no matter its exit status. - - + detached -If `false` (default), the thread can be waited for using -thread_join/2. thread_join/2 must be called on this thread -to reclaim the all resources associated to the thread. If `true`, -the system will reclaim all associated resources automatically after the -thread finishes. Please note that thread identifiers are freed for reuse -after a detached thread finishes or a normal thread has been joined. -See also thread_join/2 and thread_detach/1. - - -The _Goal_ argument is copied to the new Prolog engine. -This implies further instantiation of this term in either thread does -not have consequences for the other thread: Prolog threads do not share -data from their stacks. - - -*/ - -/** @pred thread_create(: _Goal_, - _Id_) - - -Create a new Prolog thread using default options. See thread_create/3. - - -*/ - -/** @pred thread_create(: _Goal_) - - -Create a new Prolog detached thread using default options. See thread_create/3. - - -*/ - -/** @pred thread_self(- _Id_) - - -Get the Prolog thread identifier of the running thread. If the thread -has an alias, the alias-name is returned. - - -*/ - -/** @pred thread_join(+ _Id_, - _Status_) - - -Wait for the termination of thread with given _Id_. Then unify the -result-status of the thread with _Status_. After this call, - _Id_ becomes invalid and all resources associated with the thread -are reclaimed. Note that threads with the attribute `detached` -`true` cannot be joined. See also current_thread/2. - -A thread that has been completed without thread_join/2 being -called on it is partly reclaimed: the Prolog stacks are released and the -C-thread is destroyed. A small data-structure representing the -exit-status of the thread is retained until thread_join/2 is called on -the thread. Defined values for _Status_ are: - - + true -The goal has been proven successfully. - - + false -The goal has failed. - - + exception( _Term_) -The thread is terminated on an -exception. See print_message/2 to turn system exceptions into -readable messages. - - + exited( _Term_) -The thread is terminated on thread_exit/1 using the argument _Term_. - - - + thread_detach(+ _Id_) - - -Switch thread into detached-state (see `detached` option at -thread_create/3 at runtime. _Id_ is the identifier of the thread -placed in detached state. - -One of the possible applications is to simplify debugging. Threads that -are created as `detached` leave no traces if they crash. For -not-detached threads the status can be inspected using -current_thread/2. Threads nobody is waiting for may be created -normally and detach themselves just before completion. This way they -leave no traces on normal completion and their reason for failure can be -inspected. - - -*/ - -/** @pred thread_yield - - -Voluntarily relinquish the processor. - - -*/ - -/** @pred thread_exit(+ _Term_) - - -Terminates the thread immediately, leaving `exited( _Term_)` as -result-state for thread_join/2. If the thread has the attribute -`detached` `true` it terminates, but its exit status cannot be -retrieved using thread_join/2 making the value of _Term_ -irrelevant. The Prolog stacks and C-thread are reclaimed. - - -*/ - -/** @pred thread_at_exit(: _Term_) - - -Run _Goal_ just before releasing the thread resources. This is to -be compared to `at_halt/1`, but only for the current -thread. These hooks are ran regardless of why the execution of the -thread has been completed. As these hooks are run, the return-code is -already available through thread_property/2 using the result of -thread_self/1 as thread-identifier. If you want to guarantee the -execution of an exit hook no matter how the thread terminates (the thread -can be aborted before reaching the thread_at_exit/1 call), consider -using instead the `at_exit/1` option of thread_create/3. - - -*/ - -/** @pred thread_setconcurrency(+ _Old_, - _New_) - - -Determine the concurrency of the process, which is defined as the -maximum number of concurrently active threads. `Active' here means -they are using CPU time. This option is provided if the -thread-implementation provides -`pthread_setconcurrency()`. Solaris is a typical example of this -family. On other systems this predicate unifies _Old_ to 0 (zero) -and succeeds silently. - - -*/ - -/** @pred thread_sleep(+ _Time_) - - -Make current thread sleep for _Time_ seconds. _Time_ may be an -integer or a floating point number. When time is zero or a negative value -the call succeeds and returns immediately. This call should not be used if -alarms are also being used. - - - -@} */ - -/** @defgroup Monitoring_Threads Monitoring Threads -@ingroup Threads -@{ - -Normal multi-threaded applications should not need these the predicates -from this section because almost any usage of these predicates is -unsafe. For example checking the existence of a thread before signalling -it is of no use as it may vanish between the two calls. Catching -exceptions using catch/3 is the only safe way to deal with -thread-existence errors. - -These predicates are provided for diagnosis and monitoring tasks. - - -*/ - -/** @pred thread_property(? _Id_, ? _Property_) - - -Enumerates the properties of the specified thread. -Calling thread_property/2 does not influence any thread. See also -thread_join/2. For threads that have an alias-name, this name can -be used in _Id_ instead of the numerical thread identifier. - _Property_ is one of: - - + status( _Status_) -The thread status of a thread (see below). - - + alias( _Alias_) -The thread alias, if it exists. - - + at_exit( _AtExit_) -The thread exit hook, if defined (not available if the thread is already terminated). - - + detached( _Boolean_) -The detached state of the thread. - - + stack( _Size_) -The thread stack data-area size. - - + trail( _Size_) -The thread trail data-area size. - - + system( _Size_) -The thread system data-area size. - - - -*/ - -/** @pred current_thread(+ _Id_, - _Status_) - - -Enumerates identifiers and status of all currently known threads. -Calling current_thread/2 does not influence any thread. See also -thread_join/2. For threads that have an alias-name, this name is -returned in _Id_ instead of the numerical thread identifier. - _Status_ is one of: - - + running -The thread is running. This is the initial status of a thread. Please -note that threads waiting for something are considered running too. - - + false -The _Goal_ of the thread has been completed and failed. - - + true -The _Goal_ of the thread has been completed and succeeded. - - + exited( _Term_) -The _Goal_ of the thread has been terminated using thread_exit/1 -with _Term_ as argument. If the underlying native thread has -exited (using pthread_exit()) _Term_ is unbound. - - + exception( _Term_) -The _Goal_ of the thread has been terminated due to an uncaught -exception (see throw/1 and catch/3). - - - -*/ - -/** @pred thread_statistics(+ _Id_, + _Key_, - _Value_) - - -Obtains statistical information on thread _Id_ as `statistics/2` -does in single-threaded applications. This call returns all keys -of `statistics/2`, although only information statistics about the -stacks and CPU time yield different values for each thread. - - + mutex_statistics - - -Print usage statistics on internal mutexes and mutexes associated -with dynamic predicates. For each mutex two numbers are printed: -the number of times the mutex was acquired and the number of -collisions: the number times the calling thread has to -wait for the mutex. The collision-count is not available on -Windows as this would break portability to Windows-95/98/ME or -significantly harm performance. Generally collision count is -close to zero on single-CPU hardware. - - + threads - - -Prints a table of current threads and their status. - - - -@} */ - -/** @defgroup Thread_Communication Thread communication -@ingroup Threads -@{ - -Prolog threads can exchange data using dynamic predicates, database -records, and other globally shared data. These provide no suitable means -to wait for data or a condition as they can only be checked in an -expensive polling loop. Message queues provide a means for -threads to wait for data or conditions without using the CPU. - -Each thread has a message-queue attached to it that is identified -by the thread. Additional queues are created using -`message_queue_create/2`. - - - - @pred thread_send_message(+ _Term_) - - -Places _Term_ in the message-queue of the thread running the goal. -Any term can be placed in a message queue, but note that the term is -copied to the receiving thread and variable-bindings are thus lost. -This call returns immediately. - - -*/ - -/** @pred thread_send_message(+ _QueueOrThreadId_, + _Term_) - -Place _Term_ in the given queue or default queue of the indicated -thread (which can even be the message queue of itself (see -thread_self/1). Any term can be placed in a message queue, but note that -the term is copied to the receiving thread and variable-bindings are -thus lost. This call returns immediately. - -If more than one thread is waiting for messages on the given queue and -at least one of these is waiting with a partially instantiated - _Term_, the waiting threads are all sent a wakeup signal, -starting a rush for the available messages in the queue. This behaviour -can seriously harm performance with many threads waiting on the same -queue as all-but-the-winner perform a useless scan of the queue. If -there is only one waiting thread or all waiting threads wait with an -unbound variable an arbitrary thread is restarted to scan the queue. - - - - - -*/ - -/** @pred thread_get_message(? _Term_) - - -Examines the thread message-queue and if necessary blocks execution -until a term that unifies to _Term_ arrives in the queue. After -a term from the queue has been unified unified to _Term_, the -term is deleted from the queue and this predicate returns. - -Please note that not-unifying messages remain in the queue. After -the following has been executed, thread 1 has the term `gnu` -in its queue and continues execution using _A_ is `gnat`. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - thread_get_message(a(A)), - - - thread_send_message(b(gnu)), - thread_send_message(a(gnat)), -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -See also thread_peek_message/1. - - -*/ - -/** @pred message_queue_create(? _Queue_) - - -If _Queue_ is an atom, create a named queue. To avoid ambiguity -on `thread_send_message/2`, the name of a queue may not be in use -as a thread-name. If _Queue_ is unbound an anonymous queue is -created and _Queue_ is unified to its identifier. - - -*/ - -/** @pred message_queue_destroy(+ _Queue_) - - -Destroy a message queue created with message_queue_create/1. It is -not allows to destroy the queue of a thread. Neither is it -allowed to destroy a queue other threads are waiting for or, for -anonymous message queues, may try to wait for later. - - -*/ - -/** @pred thread_get_message(+ _Queue_, ? _Term_) - -As thread_get_message/1, operating on a given queue. It is allowed to -peek into another thread's message queue, an operation that can be used -to check whether a thread has swallowed a message sent to it. - - -*/ - -/** @pred thread_peek_message(? _Term_) - - -Examines the thread message-queue and compares the queued terms -with _Term_ until one unifies or the end of the queue has been -reached. In the first case the call succeeds (possibly instantiating - _Term_. If no term from the queue unifies this call fails. - - -*/ - -/** @pred thread_peek_message(+ _Queue_, ? _Term_) - -As thread_peek_message/1, operating on a given queue. It is allowed to -peek into another thread's message queue, an operation that can be used -to check whether a thread has swallowed a message sent to it. - - - -Explicit message queues are designed with the worker-pool model -in mind, where multiple threads wait on a single queue and pick up the -first goal to execute. Below is a simple implementation where the -workers execute arbitrary Prolog goals. Note that this example provides -no means to tell when all work is done. This must be realised using -additional synchronisation. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -% create_workers(+Id, +N) -% -% Create a pool with given Id and number of workers. - -create_workers(Id, N) :- - message_queue_create(Id), - forall(between(1, N, _), - thread_create(do_work(Id), _, [])). - -do_work(Id) :- - repeat, - thread_get_message(Id, Goal), - ( catch(Goal, E, print_message(error, E)) - -> true - ; print_message(error, goal_failed(Goal, worker(Id))) - ), - fail. - -% work(+Id, +Goal) -% -% Post work to be done by the pool - -work(Id, Goal) :- - thread_send_message(Id, Goal). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -@} */ - -/** @defgroup Signalling_Threads Signalling Threads -@ingroup Threadas -@{ - -These predicates provide a mechanism to make another thread execute some -goal as an interrupt. Signalling threads is safe as these -interrupts are only checked at safe points in the virtual machine. -Nevertheless, signalling in multi-threaded environments should be -handled with care as the receiving thread may hold a mutex -(see with_mutex/2). Signalling probably only makes sense to start -debugging threads and to cancel no-longer-needed threads with throw/1, -where the receiving thread should be designed carefully do handle -exceptions at any point. - - -*/ - -/** @pred thread_signal(+ _ThreadId_, : _Goal_) - - -Make thread _ThreadId_ execute _Goal_ at the first -opportunity. In the current implementation, this implies at the first -pass through the Call-port. The predicate thread_signal/2 -itself places _Goal_ into the signalled-thread's signal queue -and returns immediately. - -Signals (interrupts) do not cooperate well with the world of -multi-threading, mainly because the status of mutexes cannot be -guaranteed easily. At the call-port, the Prolog virtual machine -holds no locks and therefore the asynchronous execution is safe. - - _Goal_ can be any valid Prolog goal, including throw/1 to make -the receiving thread generate an exception and trace/0 to start -tracing the receiving thread. - - - - -@} */ - -/** @defgroup Threads_and_Dynamic_Predicates Threads and Dynamic Predicates -@ingroup Threads -@{ - -Besides queues threads can share and exchange data using dynamic -predicates. The multi-threaded version knows about two types of -dynamic predicates. By default, a predicate declared dynamic -(see dynamic/1) is shared by all threads. Each thread may -assert, retract and run the dynamic predicate. Synchronisation inside -Prolog guarantees the consistency of the predicate. Updates are -logical: visible clauses are not affected by assert/retract -after a query started on the predicate. In many cases primitive from -thread synchronisation should be used to ensure application invariants on -the predicate are maintained. - -Besides shared predicates, dynamic predicates can be declared with the -thread_local/1 directive. Such predicates share their -attributes, but the clause-list is different in each thread. - - -*/ - -/** @pred thread_local( _+Functor/Arity_) - - -related to the dynamic/1 directive. It tells the system that the -predicate may be modified using assert/1, retract/1, -etc, during execution of the program. Unlike normal shared dynamic -data however each thread has its own clause-list for the predicate. -As a thread starts, this clause list is empty. If there are still -clauses as the thread terminates these are automatically reclaimed by -the system. The `thread_local` property implies -the property `dynamic`. - -Thread-local dynamic predicates are intended for maintaining -thread-specific state or intermediate results of a computation. - -It is not recommended to put clauses for a thread-local predicate into -a file as in the example below as the clause is only visible from the -thread that loaded the source-file. All other threads start with an -empty clause-list. - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- thread_local - foo/1. - -foo(gnat). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup Thread_Synchronisation Thread Synchronisation - -All@{ - internal Prolog operations are thread-safe. This implies two Prolog -threads can operate on the same dynamic predicate without corrupting the -consistency of the predicate. This section deals with user-level -mutexes (called monitors in ADA or -critical-sections by Microsoft). A mutex is a -MUTual EXclusive device, which implies at most one thread -can hold a mutex. - -Mutexes are used to realise related updates to the Prolog database. -With `related', we refer to the situation where a `transaction' implies -two or more changes to the Prolog database. For example, we have a -predicate `address/2`, representing the address of a person and we want -to change the address by retracting the old and asserting the new -address. Between these two operations the database is invalid: this -person has either no address or two addresses, depending on the -assert/retract order. - -Here is how to realise a correct update: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- initialization - mutex_create(addressbook). - -change_address(Id, Address) :- - mutex_lock(addressbook), - retractall(address(Id, _)), - asserta(address(Id, Address)), - mutex_unlock(addressbook). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred mutex_create(? _MutexId_) - - -Create a mutex. if _MutexId_ is an atom, a named mutex is -created. If it is a variable, an anonymous mutex reference is returned. -There is no limit to the number of mutexes that can be created. - - -*/ - -/** @pred mutex_destroy(+ _MutexId_) - - -Destroy a mutex. After this call, _MutexId_ becomes invalid and -further references yield an `existence_error` exception. - - -*/ - -/** @pred with_mutex(+ _MutexId_, : _Goal_) - - -Execute _Goal_ while holding _MutexId_. If _Goal_ leaves -choicepoints, these are destroyed (as in once/1). The mutex is unlocked -regardless of whether _Goal_ succeeds, fails or raises an exception. -An exception thrown by _Goal_ is re-thrown after the mutex has been -successfully unlocked. See also `mutex_create/2`. - -Although described in the thread-section, this predicate is also -available in the single-threaded version, where it behaves simply as -once/1. - - -*/ - -/** @pred mutex_lock(+ _MutexId_) - - -Lock the mutex. Prolog mutexes are recursive mutexes: they -can be locked multiple times by the same thread. Only after unlocking -it as many times as it is locked, the mutex becomes available for -locking by other threads. If another thread has locked the mutex the -calling thread is suspended until to mutex is unlocked. - -If _MutexId_ is an atom, and there is no current mutex with that -name, the mutex is created automatically using mutex_create/1. This -implies named mutexes need not be declared explicitly. - -Please note that locking and unlocking mutexes should be paired -carefully. Especially make sure to unlock mutexes even if the protected -code fails or raises an exception. For most common cases use -with_mutex/2, which provides a safer way for handling Prolog-level -mutexes. - - -*/ - -/** @pred mutex_trylock(+ _MutexId_) - - -As mutex_lock/1, but if the mutex is held by another thread, this -predicates fails immediately. - - -*/ - -/** @pred mutex_unlock(+ _MutexId_) - - -Unlock the mutex. This can only be called if the mutex is held by the -calling thread. If this is not the case, a `permission_error` -exception is raised. - - -*/ - -/** @pred mutex_unlock_all - - -Unlock all mutexes held by the current thread. This call is especially -useful to handle thread-termination using abort/0 or exceptions. See -also thread_signal/2. - - -*/ - -/** @pred current_mutex(? _MutexId_, ? _ThreadId_, ? _Count_) - - -Enumerates all existing mutexes. If the mutex is held by some thread, - _ThreadId_ is unified with the identifier of the holding thread and - _Count_ with the recursive count of the mutex. Otherwise, - _ThreadId_ is `[]` and _Count_ is 0. - - - -@} */ - -/** @defgroup Parallelism Parallelism -@ingroup YAPPackages -@{ - -There has been a sizeable amount of work on an or-parallel -implementation for YAP, called *YAPOr*. Most of this work has -been performed by Ricardo Rocha. In this system parallelism is exploited -implicitly by running several alternatives in or-parallel. This option -can be enabled from the `configure` script or by checking the -system's `Makefile`. - - *YAPOr* is still a very experimental system, going through rapid -development. The following restrictions are of note: - - + *YAPOr* currently only supports the Linux/X86 and SPARC/Solaris -platforms. Porting to other Unix-like platforms should be straightforward. - - + *YAPOr* does not support parallel updates to the -data-base. - - + *YAPOr* does not support opening or closing of streams during -parallel execution. - - + Garbage collection and stack shifting are not supported in - *YAPOr*. - - + Built-ins that cause side-effects can only be executed when -left-most in the search-tree. There are no primitives to provide -asynchronous or cavalier execution of these built-ins, as in Aurora or -Muse. - - + YAP does not support voluntary suspension of work. - - -We expect that some of these restrictions will be removed in future -releases. - - -@} */ - -/** @defgroup Tabling Tabling -@ingroup YAPBuiltins -@{ - - *YAPTab* is the tabling engine that extends YAP's execution -model to support tabled evaluation for definite programs. YAPTab was -implemented by Ricardo Rocha and its implementation is largely based -on the ground-breaking design of the XSB Prolog system, which -implements the SLG-WAM. Tables are implemented using tries and YAPTab -supports the dynamic intermixing of batched scheduling and local -scheduling at the subgoal level. Currently, the following restrictions -are of note: - - + YAPTab does not handle tabled predicates with loops through negation (undefined behaviour). - + YAPTab does not handle tabled predicates with cuts (undefined behaviour). - + YAPTab does not support coroutining (configure error). - + YAPTab does not support tabling dynamic predicates (permission error). - - -To experiment with YAPTab use `--enable-tabling` in the configure -script or add `-DTABLING` to `YAP_EXTRAS` in the system's -`Makefile`. We next describe the set of built-ins predicates -designed to interact with YAPTab and control tabled execution: - - -*/ - -/** @pred table + _P_ - - -Declares predicate _P_ (or a list of predicates - _P1_,..., _Pn_ or [ _P1_,..., _Pn_]) as a tabled -predicate. _P_ must be written in the form - _name/arity_. Examples: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- table son/3. -:- table father/2. -:- table mother/2. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - or - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- table son/3, father/2, mother/2. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - or - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:- table [son/3, father/2, mother/2]. -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -*/ - -/** @pred is_tabled(+ _P_) - - -Succeeds if the predicate _P_ (or a list of predicates - _P1_,..., _Pn_ or [ _P1_,..., _Pn_]), of the form - _name/arity_, is a tabled predicate. - - -*/ - -/** @pred tabling_mode(+ _P_,? _Mode_) - - -Sets or reads the default tabling mode for a tabled predicate _P_ -(or a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). The list of _Mode_ options includes: - - + batched -Defines that, by default, batched scheduling is the scheduling -strategy to be used to evaluated calls to predicate _P_. - + local -Defines that, by default, local scheduling is the scheduling -strategy to be used to evaluated calls to predicate _P_. - + exec_answers -Defines that, by default, when a call to predicate _P_ is -already evaluated (completed), answers are obtained by executing -compiled WAM-like code directly from the trie data -structure. This reduces the loading time when backtracking, but -the order in which answers are obtained is undefined. - + load_answers -Defines that, by default, when a call to predicate _P_ is -already evaluated (completed), answers are obtained (as a -consumer) by loading them from the trie data structure. This -guarantees that answers are obtained in the same order as they -were found. Somewhat less efficient but creates less choice-points. - -The default tabling mode for a new tabled predicate is `batched` -and `exec_answers`. To set the tabling mode for all predicates at -once you can use the yap_flag/2 predicate as described next. - - -*/ - -/** @pred yap_flag(tabling_mode,? _Mode_) -Sets or reads the tabling mode for all tabled predicates. The list of - _Mode_ options includes: - - + default -Defines that (i) all calls to tabled predicates are evaluated -using the predicate default mode, and that (ii) answers for all -completed calls are obtained by using the predicate default mode. - + batched -Defines that all calls to tabled predicates are evaluated using -batched scheduling. This option ignores the default tabling mode -of each predicate. - + local -Defines that all calls to tabled predicates are evaluated using -local scheduling. This option ignores the default tabling mode -of each predicate. - + exec_answers -Defines that answers for all completed calls are obtained by -executing compiled WAM-like code directly from the trie data -structure. This option ignores the default tabling mode -of each predicate. - + load_answers -Defines that answers for all completed calls are obtained by -loading them from the trie data structure. This option ignores -the default tabling mode of each predicate. - - - -*/ - -/** @pred abolish_table(+ _P_) - - -Removes all the entries from the table space for predicate _P_ (or -a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). The predicate remains as a tabled predicate. - - -*/ - -/** @pred abolish_all_tables/0 - - -Removes all the entries from the table space for all tabled -predicates. The predicates remain as tabled predicates. - - -*/ - -/** @pred show_table(+ _P_) - - -Prints table contents (subgoals and answers) for predicate _P_ -(or a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). - - -*/ - -/** @pred table_statistics(+ _P_) - - -Prints table statistics (subgoals and answers) for predicate _P_ -(or a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). - - -*/ - -/** @pred tabling_statistics/0 - - -Prints statistics on space used by all tables. - - - -@} */ - -/** @defgroup Low_Level_Tracing Tracing at Low Level -@ingroup YAPBuiltins -@{ - -It is possible to follow the flow at abstract machine level if -YAP is compiled with the flag `LOW_LEVEL_TRACER`. Note -that this option is of most interest to implementers, as it quickly generates -an huge amount of information. - -Low level tracing can be toggled from an interrupt handler by using the -option `T`. There are also two built-ins that activate and -deactivate low level tracing: - - -*/ - -/** @pred start_low_level_trace - - -Begin display of messages at procedure entry and retry. - - + stop_low_level_trace - - -Stop display of messages at procedure entry and retry. - - -Note that this compile-time option will slow down execution. - - -@} */ - -/** @defgroup Low_Level_Profiling Profiling the Abstract Machine - -Imp@{ -lementors may be interested in detecting on which abstract machine -instructions are executed by a program. The `ANALYST` flag can give -WAM level information. Note that this option slows down execution very -substantially, and is only of interest to developers of the system -internals, or to system debuggers. - - -*/ - -/** @pred reset_op_counters - - -Reinitialize all counters. - - -*/ - -/** @pred show_op_counters(+ _A_) - - -Display the current value for the counters, using label _A_. The -label must be an atom. - - -*/ - -/** @pred show_ops_by_group(+ _A_) - - -Display the current value for the counters, organized by groups, using -label _A_. The label must be an atom. - - - - -@} */ - -/** @defgroup Debugging Debugging -@ingroup YAPBuiltins -@{ - - -@} */ - -/** @defgroup Deb_Preds Debugging Predicates - -The@{ - following predicates are available to control the debugging of -programs: - - + debug - -Switches the debugger on. - - + debugging - - -Outputs status information about the debugger which includes the leash -mode and the existing spy-points, when the debugger is on. - - + nodebug - - -Switches the debugger off. - - -*/ - -/** @pred spy + _P_ - - -Sets spy-points on all the predicates represented by - _P_. _P_ can either be a single specification or a list of -specifications. Each one must be of the form _Name/Arity_ -or _Name_. In the last case all predicates with the name - _Name_ will be spied. As in C-Prolog, system predicates and -predicates written in C, cannot be spied. - - -*/ - -/** @pred nospy + _P_ - - -Removes spy-points from all predicates specified by _P_. -The possible forms for _P_ are the same as in `spy P`. - - -*/ - -/** @pred nospyall - - -Removes all existing spy-points. - - -*/ - -/** @pred leash(+ _M_) - - -Sets leashing mode to _M_. -The mode can be specified as: - - + full -prompt on Call, Exit, Redo and Fail - + tight -prompt on Call, Redo and Fail - + half -prompt on Call and Redo - + loose -prompt on Call - + off -never prompt - + none -never prompt, same as `off` - -The initial leashing mode is `full`. - -The user may also specify directly the debugger ports -where he wants to be prompted. If the argument for leash -is a number _N_, each of lower four bits of the number is used to -control prompting at one the ports of the box model. The debugger will -prompt according to the following conditions: - - + -if `N/\\ 1 =\\= 0` prompt on fail - + -if `N/\\ 2 =\\= 0` prompt on redo - + -if `N/\\ 4 =\\= 0` prompt on exit - + -if `N/\\ 8 =\\= 0` prompt on call - -Therefore, `leash(15)` is equivalent to `leash(full)` and -`leash(0)` is equivalent to `leash(off)`. - -Another way of using `leash` is to give it a list with the names of -the ports where the debugger should stop. For example, -`leash([call,exit,redo,fail])` is the same as `leash(full)` or -`leash(15)` and `leash([fail])` might be used instead of -`leash(1)`. - - -*/ - -/** @pred spy_write(+ _Stream_,Term) - - -If defined by the user, this predicate will be used to print goals by -the debugger instead of `write/2`. - - -*/ - -/** @pred trace - - -Switches on the debugger and starts tracing. - - -*/ - -/** @pred notrace - - -Ends tracing and exits the debugger. This is the same as -nodebug/0. - - - - -@} */ - -/** @defgroup Deb_Interaction Interacting with the debugger - -Deb@{ -ugging with YAP is similar to debugging with C-Prolog. Both systems -include a procedural debugger, based on Byrd's four port model. In this -model, execution is seen at the procedure level: each activation of a -procedure is seen as a box with control flowing into and out of that -box. - -In the four port model control is caught at four key points: before -entering the procedure, after exiting the procedure (meaning successful -evaluation of all queries activated by the procedure), after backtracking but -before trying new alternative to the procedure and after failing the -procedure. Each one of these points is named a port: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -@group - *--------------------------------------* - Call | | Exit ----------> + descendant(X,Y) :- offspring(X,Y). + ---------> - | | - | descendant(X,Z) :- | -<--------- + offspring(X,Y), descendant(Y,Z). + <--------- - Fail | | Redo - *--------------------------------------* -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - + Call -The call port is activated before initial invocation of -procedure. Afterwards, execution will try to match the goal with the -head of existing clauses for the procedure. - + Exit -This port is activated if the procedure succeeds. -Control will now leave the procedure and return to its ancestor. - + Redo -if the goal, or goals, activated after the call port -fail then backtracking will eventually return control to this procedure -through the redo port. - + Fail -If all clauses for this predicate fail, then the -invocation fails, and control will try to redo the ancestor of this -invocation. - - -To start debugging, the user will either call `trace` or spy the -relevant procedures, entering debug mode, and start execution of the -program. When finding the first spy-point, YAP's debugger will take -control and show a message of the form: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -* (1) call: quicksort([1,2,3],_38) ? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The debugger message will be shown while creeping, or at spy-points, -and it includes four or five fields: - - + -The first three characters are used to point out special states of the -debugger. If the port is exit and the first character is '?', the -current call is non-deterministic, that is, it still has alternatives to -be tried. If the second character is a `\*`, execution is at a -spy-point. If the third character is a `\>`, execution has returned -either from a skip, a fail or a redo command. - + -The second field is the activation number, and uniquely identifies the -activation. The number will start from 1 and will be incremented for -each activation found by the debugger. - + -In the third field, the debugger shows the active port. - + -The fourth field is the goal. The goal is written by -`write_term/3` on the standard error stream, using the options -given by debugger_print_options. - - -If the active port is leashed, the debugger will prompt the user with a -`?`, and wait for a command. A debugger command is just a -character, followed by a return. By default, only the call and redo -entries are leashed, but the leash/1 predicate can be used in -order to make the debugger stop where needed. - -There are several commands available, but the user only needs to -remember the help command, which is `h`. This command shows all the -available options, which are: - - + c - creep -this command makes YAP continue execution and stop at the next -leashed port. - + return - creep -the same as c - + l - leap -YAP will execute until it meets a port for a spied predicate; this mode -keeps all computation history for debugging purposes, so it is more -expensive than standard execution. Use k or z for fast execution. - + k - quasi-leap -similar to leap but faster since the computation history is -not kept; useful when leap becomes too slow. - + z - zip -same as k - + s - skip -YAP will continue execution without showing any messages until -returning to the current activation. Spy-points will be ignored in this -mode. Note that this command keeps all debugging history, use t for fast execution. This command is meaningless, and therefore illegal, in the fail -and exit ports. - + t - fast-skip -similar to skip but faster since computation history is not -kept; useful if skip becomes slow. - + f [ _GoalId_] - fail -If given no argument, forces YAP to fail the goal, skipping the fail -port and backtracking to the parent. -If f receives a goal number as -the argument, the command fails all the way to the goal. If goal _GoalId_ has completed execution, YAP fails until meeting the first active ancestor. - + r [ _GoalId_] - retry -This command forces YAP to jump back call to the port. Note that any -side effects of the goal cannot be undone. This command is not available -at the call port. If f receives a goal number as the argument, the -command retries goal _GoalId_ instead. If goal _GoalId_ has -completed execution, YAP fails until meeting the first active ancestor. - - + a - abort -execution will be aborted, and the interpreter will return to the -top-level. YAP disactivates debug mode, but spypoints are not removed. - + n - nodebug -stop debugging and continue execution. The command will not clear active -spy-points. - + e - exit -leave YAP. - + h - help -show the debugger commands. - + ! Query -execute a query. YAP will not show the result of the query. - + b - break -break active execution and launch a break level. This is the same as `!break`. - + + - spy this goal -start spying the active goal. The same as `! spy G` where _G_ -is the active goal. - + - - nospy this goal -stop spying the active goal. The same as `! nospy G` where _G_ is -the active goal. - + p - print -shows the active goal using print/1 - + d - display -shows the active goal using display/1 - + \deterministic programs often -boils down to a recursive loop of the form: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -loop(Env) :- - do_something(Env,NewEnv), - loop(NewEnv). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - - - -@} */ - -/** @defgroup Indexing Indexing - -The@{ - indexation mechanism restricts the set of clauses to be tried in a -procedure by using information about the status of the instantiated -arguments of the goal. These arguments are then used as a key, -selecting a restricted set of a clauses from all the clauses forming the -procedure. - -As an example, the two clauses for concatenate: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -concatenate([],L,L). -concatenate([H|T],A,[H|NT]) :- concatenate(T,A,NT). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If the first argument for the goal is a list, then only the second clause -is of interest. If the first argument is the nil atom, the system needs to -look only for the first clause. The indexation generates instructions that -test the value of the first argument, and then proceed to a selected clause, -or group of clauses. - -Note that if the first argument was a free variable, then both clauses -should be tried. In general, indexation will not be useful if the first -argument is a free variable. - -When activating a predicate, a Prolog system needs to store state -information. This information, stored in a structure known as choice point -or fail point, is necessary when backtracking to other clauses for the -predicate. The operations of creating and using a choice point are very -expensive, both in the terms of space used and time spent. -Creating a choice point is not necessary if there is only a clause for -the predicate as there are no clauses to backtrack to. With indexation, this -situation is extended: in the example, if the first argument was the atom -nil, then only one clause would really be of interest, and it is pointless to -create a choice point. This feature is even more useful if the first argument -is a list: without indexation, execution would try the first clause, creating -a choice point. The clause would fail, the choice point would then be used to -restore the previous state of the computation and the second clause would -be tried. The code generated by the indexation mechanism would behave -much more efficiently: it would test the first argument and see whether it -is a list, and then proceed directly to the second clause. - -An important side effect concerns the use of "cut". In the above -example, some programmers would use a "cut" in the first clause just to -inform the system that the predicate is not backtrackable and force the -removal the choice point just created. As a result, less space is needed but -with a great loss in expressive power: the "cut" would prevent some uses of -the procedure, like generating lists through backtracking. Of course, with -indexation the "cut" becomes useless: the choice point is not even created. - -Indexation is also very important for predicates with a large number -of clauses that are used like tables: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -logician(aristoteles,greek). -logician(frege,german). -logician(russel,english). -logician(godel,german). -logician(whitehead,english). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -An interpreter like C-Prolog, trying to answer the query: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -?- logician(godel,X). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -would blindly follow the standard Prolog strategy, trying first the -first clause, then the second, the third and finally finding the -relevant clause. Also, as there are some more clauses after the -important one, a choice point has to be created, even if we know the -next clauses will certainly fail. A "cut" would be needed to prevent -some possible uses for the procedure, like generating all logicians. In -this situation, the indexing mechanism generates instructions that -implement a search table. In this table, the value of the first argument -would be used as a key for fast search of possibly matching clauses. For -the query of the last example, the result of the search would be just -the fourth clause, and again there would be no need for a choice point. - -If the first argument is a complex term, indexation will select clauses -just by testing its main functor. However, there is an important -exception: if the first argument of a clause is a list, the algorithm -also uses the list's head if not a variable. For instance, with the -following clauses, - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -rules([],B,B). -rules([n(N)|T],I,O) :- rules_for_noun(N,I,N), rules(T,N,O). -rules([v(V)|T],I,O) :- rules_for_verb(V,I,N), rules(T,N,O). -rules([q(Q)|T],I,O) :- rules_for_qualifier(Q,I,N), rules(T,N,O). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -if the first argument of the goal is a list, its head will be tested, and only -the clauses matching it will be tried during execution. - -Some advice on how to take a good advantage of this mechanism: - - - - + -Try to make the first argument an input argument. - - + -Try to keep together all clauses whose first argument is not a -variable, that will decrease the number of tests since the other clauses are -always tried. - - + -Try to avoid predicates having a lot of clauses with the same key. -For instance, the procedure: - - - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -type(n(mary),person). -type(n(john), person). -type(n(chair),object). -type(v(eat),active). -type(v(rest),passive). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -becomes more efficient with: - -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -type(n(N),T) :- type_of_noun(N,T). -type(v(V),T) :- type_of_verb(V,T). - -type_of_noun(mary,person). -type_of_noun(john,person). -type_of_noun(chair,object). - -type_of_verb(eat,active). -type_of_verb(rest,passive). -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -*/ - -/** @page ChYInterface C Language interface to YAP - -YAP provides the user with three facilities for writing -predicates in a language other than Prolog. Under Unix systems, -most language implementations were linkable to `C`, and the first interface exported the YAP machinery to the C language. YAP also implements most of the SWI-Prolog foreign language interface. -This gives portability with a number of SWI-Prolog packages. Last, a new C++ based interface is -being designed to work with the swig (@url(www.swig.org}) interface compiler. - - + The @ref c-interface YAP C-interface exports the YAP engine. - + The @ref swi-c-interface emulates Jan Wielemaker's SWI foreign language interface. - + The @ref yap-cplus-interface is desiged to interface with Object-Oriented systems. - - - - -@} */ - -/** @defgroup Loading_Objects Loading Object Files - -The@{ - primitive predicate - - -*/ - -/** @pred load_foreign_files( _Files_, _Libs_, _InitRoutine_) - -should be used, from inside YAP, to load object files produced by the C -compiler. The argument _ObjectFiles_ should be a list of atoms -specifying the object files to load, _Libs_ is a list (possibly -empty) of libraries to be passed to the unix loader (`ld`) and -InitRoutine is the name of the C routine (to be called after the files -are loaded) to perform the necessary declarations to YAP of the -predicates defined in the files. - -YAP will search for _ObjectFiles_ in the current directory first. If -it cannot find them it will search for the files using the environment -variable: - - + YAPLIBDIR - -if defined, or in the default library. - -YAP also supports the SWI-Prolog interface to loading foreign code: - - -*/ - -/** @pred open_shared_object(+ _File_, - _Handle_) - -File is the name of a shared object file (called dynamic load -library in MS-Windows). This file is attached to the current process -and _Handle_ is unified with a handle to the library. Equivalent to -`open_shared_object(File, [], Handle)`. See also -load_foreign_library/1 and `load_foreign_library/2`. - -On errors, an exception `shared_object`( _Action_, - _Message_) is raised. _Message_ is the return value from -dlerror(). - - -*/ - -/** @pred open_shared_object(+ _File_, - _Handle_, + _Options_) - -As `open_shared_object/2`, but allows for additional flags to -be passed. _Options_ is a list of atoms. `now` implies the -symbols are -resolved immediately rather than lazily (default). `global` implies -symbols of the loaded object are visible while loading other shared -objects (by default they are local). Note that these flags may not -be supported by your operating system. Check the documentation of -`dlopen()` or equivalent on your operating system. Unsupported -flags are silently ignored. - - -*/ - -/** @pred close_shared_object(+ _Handle_) - -Detach the shared object identified by _Handle_. - - -*/ - -/** @pred call_shared_object_function(+ _Handle_, + _Function_) - - -Call the named function in the loaded shared library. The function -is called without arguments and the return-value is -ignored. In SWI-Prolog, normally this function installs foreign -language predicates using calls to `PL_register_foreign()`. - - - -@} */ - -/** @defgroup SavebQeERest Saving and Restoring - -YAP@{ -4 currently does not support `save` and `restore` for object code -loaded with `load_foreign_files/3`. We plan to support save and restore -in future releases of YAP. - -*/ diff --git a/docs/yapdocs.yap b/docs/yapdocs.yap deleted file mode 100644 index aaeefaaae..000000000 --- a/docs/yapdocs.yap +++ /dev/null @@ -1,15552 +0,0 @@ -/** - -@defgroup YAPControl Control Predicates -@ingroup builtins -@{ - -*/ - - -/** @pred true is iso - - -Succeeds once. - - -*/ - -/** @pred fail is iso - - -Always fails. - - -*/ - -/** @pred false is iso - - -The same as fail. - - -*/ - -/** @pred repeat is iso -Succeeds repeatedly. - -In the next example, `repeat` is used as an efficient way to implement -a loop. The next example reads all terms in a file: -~~~~~~~~~~~~~{.prolog} - a :- repeat, read(X), write(X), nl, X=end_of_file, !. -~~~~~~~~~~~~~ -the loop is effectively terminated by the cut-goal, when the test-goal -`X=end` succeeds. While the test fails, the goals `read(X)`, -`write(X)`, and `nl` are executed repeatedly, because -backtracking is caught by the `repeat` goal. - -The built-in `repeat/0` could be defined in Prolog by: - -~~~~~{.prolog} - repeat. - repeat :- repeat. -~~~~~ - -The predicate between/3 can be used to iterate for a pre-defined -number of steps. - -*/ - -/** @pred call(+ _P_) is iso -Meta-call predicate. - -If _P_ is instantiated to an atom or a compound term, the goal `call( -_P_)` is executed as if the clause was originally written as _P_ -instead as call( _P_ ), except that any "cut" occurring in _P_ only -cuts alternatives in the execution of _P_. - - -*/ - -/** @pred incore(+ _P_) - - -The same as call/1. - - -*/ - -/** @pred call(+ _Closure_,...,? _Ai_,...) is iso - - -Meta-call where _Closure_ is a closure that is converted into a goal by -appending the _Ai_ additional arguments. The number of arguments varies -between 0 and 10. - - -*/ - -/** @pred call_with_args(+ _Name_,...,? _Ai_,...) - - -Meta-call where _Name_ is the name of the procedure to be called and -the _Ai_ are the arguments. The number of arguments varies between 0 -and 10. New code should use `call/N` for better portability. - -If _Name_ is a complex term, then call_with_args/n behaves as -call/n: - -~~~~~{.prolog} -call(p(X1,...,Xm), Y1,...,Yn) :- p(X1,...,Xm,Y1,...,Yn). -~~~~~ - - -*/ - - -/** @pred + _P_ is nondet - -The same as `call( _P_)`. This feature has been kept to provide -compatibility with C-Prolog. When compiling a goal, YAP -generates a `call( _X_)` whenever a variable _X_ is found as -a goal. - -~~~~~{.prolog} - a(X) :- X. -~~~~~ -is converted to: - -~~~~~{.prolog} - a(X) :- call(X). -~~~~~ - - -*/ - -/** @pred if(? _G_,? _H_,? _I_) - -Call goal _H_ once per each solution of goal _H_. If goal - _H_ has no solutions, call goal _I_. - -The built-in `if/3` is similar to `->/3`, with the difference -that it will backtrack over the test goal. Consider the following -small data-base: - -~~~~~{.prolog} -a(1). b(a). c(x). -a(2). b(b). c(y). -~~~~~ - -Execution of an `if/3` query will proceed as follows: - -~~~~~{.prolog} - ?- if(a(X),b(Y),c(Z)). - -X = 1, -Y = a ? ; - -X = 1, -Y = b ? ; - -X = 2, -Y = a ? ; - -X = 2, -Y = b ? ; - -no -~~~~~ - -The system will backtrack over the two solutions for `a/1` and the -two solutions for `b/1`, generating four solutions. - -Cuts are allowed inside the first goal _G_, but they will only prune -over _G_. - -If you want _G_ to be deterministic you should use if-then-else, as -it is both more efficient and more portable. - - -*/ - -/** @pred once(: _G_) is iso - - -Execute the goal _G_ only once. The predicate is defined by: - -~~~~~{.prolog} - once(G) :- call(G), !. -~~~~~ - -Note that cuts inside once/1 can only cut the other goals inside -once/1. - - -*/ - -/** @pred forall(: _Cond_,: _Action_) - - -For all alternative bindings of _Cond_ _Action_ can be -proven. The example verifies that all arithmetic statements in the list - _L_ are correct. It does not say which is wrong if one proves wrong. - -~~~~~{.prolog} -?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), - Result =:= Formula). -~~~~~ - - -*/ - -/** @pred ignore(: _Goal_) - - -Calls _Goal_ as once/1, but succeeds, regardless of whether -`Goal` succeeded or not. Defined as: - -~~~~~{.prolog} -ignore(Goal) :- - Goal, !. -ignore(_). -~~~~~ - - -*/ - -/** @pred abort - - -Abandons the execution of the current goal and returns to top level. All -break levels (see break/0 below) are terminated. It is mainly -used during debugging or after a serious execution error, to return to -the top-level. - - -*/ - -/** @pred break - - -Suspends the execution of the current goal and creates a new execution -level similar to the top level, displaying the following message: - -~~~~~{.prolog} - [ Break (level ) ] -~~~~~ -telling the depth of the break level just entered. To return to the -previous level just type the end-of-file character or call the -end_of_file predicate. This predicate is especially useful during -debugging. - - -*/ - -/** @pred halt is iso - - -Halts Prolog, and exits to the calling application. In YAP, -halt/0 returns the exit code `0`. - - -*/ - -/** @pred halt(+ _I_) is iso - -Halts Prolog, and exits to the calling application returning the code -given by the integer _I_. - - -*/ - -/** @pred catch( : _Goal_,+ _Exception_,+ _Action_) is iso - - -The goal `catch( _Goal_, _Exception_, _Action_)` tries to -execute goal _Goal_. If during its execution, _Goal_ throws an -exception _E'_ and this exception unifies with _Exception_, the -exception is considered to be caught and _Action_ is executed. If -the exception _E'_ does not unify with _Exception_, control -again throws the exception. - -The top-level of YAP maintains a default exception handler that -is responsible to capture uncaught exceptions. - - -*/ - -/** @pred throw(+ _Ball_) is iso - - -The goal `throw( _Ball_)` throws an exception. Execution is -stopped, and the exception is sent to the ancestor goals until reaching -a matching catch/3, or until reaching top-level. - - -*/ - -/** @pred garbage_collect - - -The goal `garbage_collect` forces a garbage collection. - - -*/ - -/** @pred garbage_collect_atoms - - -The goal `garbage_collect` forces a garbage collection of the atoms -in the data-base. Currently, only atoms are recovered. - - -*/ - -/** @pred gc - - -The goal `gc` enables garbage collection. The same as -`yap_flag(gc,on)`. - - -*/ - -/** @pred nogc - - -The goal `nogc` disables garbage collection. The same as -`yap_flag(gc,off)`. - - -*/ - -/** @pred grow_heap(+ _Size_) -Increase heap size _Size_ kilobytes. - - -*/ - -/** @pred grow_stack(+ _Size_) - - -Increase stack size _Size_ kilobytes - - - */ - -/** @defgroup Undefined_Procedures Handling Undefined Procedures -@ingroup builtins -@{ - -A predicate in a module is said to be undefined if there are no clauses -defining the predicate, and if the predicate has not been declared to be -dynamic. What YAP does when trying to execute undefined predicates can -be specified in three different ways: - - -+ By setting an YAP flag, through the yap_flag/2 or -set_prolog_flag/2 built-ins. This solution generalizes the -ISO standard. -+ By using the unknown/2 built-in (this solution is -compatible with previous releases of YAP). -+ By defining clauses for the hook predicate -`user:unknown_predicate_handler/3`. This solution is compatible -with SICStus Prolog. - - -In more detail: - - - -*/ - -/** @pred unknown(- _O_,+ _N_) - - -Specifies an handler to be called is a program tries to call an -undefined static procedure _P_. - -The arity of _N_ may be zero or one. If the arity is `0`, the -new action must be one of `fail`, `warning`, or -`error`. If the arity is `1`, _P_ is an user-defined -handler and at run-time, the argument to the handler _P_ will be -unified with the undefined goal. Note that _N_ must be defined prior -to calling unknown/2, and that the single argument to _N_ must -be unbound. - -In YAP, the default action is to `fail` (note that in the ISO -Prolog standard the default action is `error`). - -After defining `undefined/1` by: - -~~~~~{.prolog} -undefined(A) :- format('Undefined predicate: ~w~n',[A]), fail. -~~~~~ -and executing the goal: - -~~~~~{.prolog} -unknown(U,undefined(X)). -~~~~~ -a call to a predicate for which no clauses were defined will result in -the output of a message of the form: - -~~~~~{.prolog} -Undefined predicate: user:xyz(A1,A2) -~~~~~ -followed by the failure of that call. - - -*/ - -/** @pred yap_flag(unknown,+ _SPEC_) - -Alternatively, one can use yap_flag/2, -current_prolog_flag/2, or set_prolog_flag/2, to set this -functionality. In this case, the first argument for the built-ins should -be `unknown`, and the second argument should be either -`error`, `warning`, `fail`, or a goal. - - -*/ - -/** @pred user:unknown_predicate_handler(+G,+M,?NG) - - -The user may also define clauses for -`user:unknown_predicate_handler/3` hook predicate. This -user-defined procedure is called before any system processing for the -undefined procedure, with the first argument _G_ set to the current -goal, and the second _M_ set to the current module. The predicate - _G_ will be called from within the user module. - -If `user:unknown_predicate_handler/3` succeeds, the system will -execute _NG_. If `user:unknown_predicate_handler/3` fails, the -system will execute default action as specified by unknown/2. - - -*/ - -/** @pred exception(+ _Exception_, + _Context_, - _Action_) - - -Dynamic predicate, normally not defined. Called by the Prolog system on run-time exceptions that can be repaired `just-in-time`. The values for _Exception_ are described below. See also catch/3 and throw/1. -If this hook predicate succeeds it must instantiate the _Action_ argument to the atom `fail` to make the operation fail silently, `retry` to tell Prolog to retry the operation or `error` to make the system generate an exception. The action `retry` only makes sense if this hook modified the environment such that the operation can now succeed without error. - -+ `undefined_predicate` - _Context_ is instantiated to a predicate-indicator ( _Module:Name/Arity_). If the predicate fails Prolog will generate an existence_error exception. The hook is intended to implement alternatives to the SWI built-in autoloader, such as autoloading code from a database. Do not use this hook to suppress existence errors on predicates. See also `unknown`. -+ `undefined_global_variable` - _Context_ is instantiated to the name of the missing global variable. The hook must call nb_setval/2 or b_setval/2 before returning with the action retry. - - - - - - */ - -/** @defgroup Messages Message Handling -@ingroup builtins -@{ - -The interaction between YAP and the user relies on YAP's ability to -portray messages. These messages range from prompts to error -information. All message processing is performed through the builtin -print_message/2, in two steps: - -+ The message is processed into a list of commands -+ The commands in the list are sent to the `format/3` builtin -in sequence. - - -The first argument to print_message/2 specifies the importance of -the message. The options are: - -+ `error` -error handling -+ `warning` -compilation and run-time warnings, -+ `informational` -generic informational messages -+ `help` -help messages (not currently implemented in YAP) -+ `query` -query used in query processing (not currently implemented in YAP) -+ `silent` -messages that do not produce output but that can be intercepted by hooks. - - -The next table shows the main predicates and hooks associated to message -handling in YAP: - - -*/ - -/** @pred print_message(+ _Kind_, _Term_) - -The predicate print_message/2 is used to print messages, notably from -exceptions in a human-readable format. _Kind_ is one of -`informational`, `banner`, `warning`, `error`, -`help` or `silent`. A human-readable message is printed to -the stream user_error. - -If the Prolog flag verbose is `silent`, messages with - _Kind_ `informational`, or `banner` are treated as -silent.@c See \cmdlineoption{-q}. - -This predicate first translates the _Term_ into a list of `message -lines` (see print_message_lines/3 for details). Next it will -call the hook message_hook/3 to allow the user intercepting the -message. If message_hook/3 fails it will print the message unless - _Kind_ is silent. - -If you need to report errors from your own predicates, we advise you to -stick to the existing error terms if you can; but should you need to -invent new ones, you can define corresponding error messages by -asserting clauses for `prolog:message/2`. You will need to declare -the predicate as multifile. - - -*/ - -/** @pred print_message_lines(+ _Stream_, + _Prefix_, + _Lines_) - - -Print a message (see print_message/2) that has been translated to -a list of message elements. The elements of this list are: - -+ _Format_-_Args_ -Where _Format_ is an atom and _Args_ is a list -of format argument. Handed to `format/3`. -+ `flush` -If this appears as the last element, _Stream_ is flushed -(see `flush_output/1`) and no final newline is generated. -+ `at_same_line` -If this appears as first element, no prefix is printed for -the first line and the line-position is not forced to 0 -(see `format/1`, `~N`). -+ `` -Handed to `format/3` as `format(Stream, Format, [])`. -+ nl -A new line is started and if the message is not complete -the _Prefix_ is printed too. - - - -*/ - -/** @pred user:message_hook(+ _Term_, + _Kind_, + _Lines_) - - -Hook predicate that may be define in the module `user` to intercept -messages from print_message/2. _Term_ and _Kind_ are the -same as passed to print_message/2. _Lines_ is a list of -format statements as described with print_message_lines/3. - -This predicate should be defined dynamic and multifile to allow other -modules defining clauses for it too. - - -*/ - -/** @pred message_to_string(+ _Term_, - _String_) - - -Translates a message-term into a string object. Primarily intended for SWI-Prolog emulation. - - - - */ - -/** @defgroup Testing_Terms Predicates on terms -@ingroup builtins -@{ - - - - -*/ - -/** @pred var( _T_) is iso - - -Succeeds if _T_ is currently a free variable, otherwise fails. - - -*/ - -/** @pred atom( _T_) is iso - - -Succeeds if and only if _T_ is currently instantiated to an atom. - - -*/ - -/** @pred atomic(T) is iso - - -Checks whether _T_ is an atomic symbol (atom or number). - - -*/ - -/** @pred compound( _T_) is iso - - -Checks whether _T_ is a compound term. - - -*/ - -/** @pred db_reference( _T_) - - -Checks whether _T_ is a database reference. - - -*/ - -/** @pred float( _T_) is iso - - -Checks whether _T_ is a floating point number. - - -*/ - -/** @pred rational( _T_) - - -Checks whether `T` is a rational number. - - -*/ - -/** @pred integer( _T_) is iso - - -Succeeds if and only if _T_ is currently instantiated to an integer. - - -*/ - -/** @pred nonvar( _T_) is iso - - -The opposite of `var( _T_)`. - - -*/ - -/** @pred number( _T_) is iso - - -Checks whether `T` is an integer, rational or a float. - - -*/ - -/** @pred primitive( _T_) - - -Checks whether _T_ is an atomic term or a database reference. - - -*/ - -/** @pred simple( _T_) - - -Checks whether _T_ is unbound, an atom, or a number. - - -*/ - -/** @pred callable( _T_) is iso - - -Checks whether _T_ is a callable term, that is, an atom or a -compound term. - - -*/ - -/** @pred numbervars( _T_,+ _N1_,- _Nn_) - - -Instantiates each variable in term _T_ to a term of the form: -`$VAR( _I_)`, with _I_ increasing from _N1_ to _Nn_. - - -*/ - -/** @pred unnumbervars( _T_,+ _NT_) - - -Replace every `$VAR( _I_)` by a free variable. - - -*/ - -/** @pred ground( _T_) is iso - - -Succeeds if there are no free variables in the term _T_. - - -*/ - -/** @pred acyclic_term( _T_) is iso - - -Succeeds if there are loops in the term _T_, that is, it is an infinite term. - - -*/ - -/** @pred arg(+ _N_,+ _T_, _A_) is iso - - -Succeeds if the argument _N_ of the term _T_ unifies with - _A_. The arguments are numbered from 1 to the arity of the term. - -The current version will generate an error if _T_ or _N_ are -unbound, if _T_ is not a compound term, of if _N_ is not a positive -integer. Note that previous versions of YAP would fail silently -under these errors. - - -*/ - -/** @pred functor( _T_, _F_, _N_) is iso - - -The top functor of term _T_ is named _F_ and has arity _N_. - -When _T_ is not instantiated, _F_ and _N_ must be. If - _N_ is 0, _F_ must be an atomic symbol, which will be unified -with _T_. If _N_ is not 0, then _F_ must be an atom and - _T_ becomes instantiated to the most general term having functor - _F_ and arity _N_. If _T_ is instantiated to a term then - _F_ and _N_ are respectively unified with its top functor name -and arity. - -In the current version of YAP the arity _N_ must be an -integer. Previous versions allowed evaluable expressions, as long as the -expression would evaluate to an integer. This feature is not available -in the ISO Prolog standard. - - -*/ - -/** @pred _T_ =.. _L_ is iso - - -The list _L_ is built with the functor and arguments of the term - _T_. If _T_ is instantiated to a variable, then _L_ must be -instantiated either to a list whose head is an atom, or to a list -consisting of just a number. - - -*/ - -/** @pred _X_ = _Y_ is iso - - -Tries to unify terms _X_ and _Y_. - - -*/ - -/** @pred _X_ \= _Y_ is iso - - -Succeeds if terms _X_ and _Y_ are not unifiable. - - -*/ - -/** @pred unify_with_occurs_check(?T1,?T2) is iso - - -Obtain the most general unifier of terms _T1_ and _T2_, if there -is one. - -This predicate implements the full unification algorithm. An example:n - -~~~~~{.prolog} -unify_with_occurs_check(a(X,b,Z),a(X,A,f(B)). -~~~~~ -will succeed with the bindings `A = b` and `Z = f(B)`. On the -other hand: - -~~~~~{.prolog} -unify_with_occurs_check(a(X,b,Z),a(X,A,f(Z)). -~~~~~ -would fail, because `Z` is not unifiable with `f(Z)`. Note that -`(=)/2` would succeed for the previous examples, giving the following -bindings `A = b` and `Z = f(Z)`. - - -*/ - -/** @pred copy_term(? _TI_,- _TF_) is iso - - -Term _TF_ is a variant of the original term _TI_, such that for -each variable _V_ in the term _TI_ there is a new variable _V'_ -in term _TF_. Notice that: - -+ suspended goals and attributes for attributed variables in _TI_ are also duplicated; -+ ground terms are shared between the new and the old term. - -If you do not want any sharing to occur please use -duplicate_term/2. - - -*/ - -/** @pred duplicate_term(? _TI_,- _TF_) - - -Term _TF_ is a variant of the original term _TI_, such that -for each variable _V_ in the term _TI_ there is a new variable - _V'_ in term _TF_, and the two terms do not share any -structure. All suspended goals and attributes for attributed variables -in _TI_ are also duplicated. - -Also refer to copy_term/2. - - -*/ - -/** @pred is_list(+ _List_) - - -True when _List_ is a proper list. That is, _List_ -is bound to the empty list (nil) or a term with functor '.' and arity 2. - - -*/ - -/** @pred subsumes_term(? _Subsumer_, ? _Subsumed_) - - - -Succeed if _Submuser_ subsumes _Subsuned_ but does not bind any -variable in _Subsumer_. - - -*/ - -/** @pred term_subsumer(? _T1_, ? _T2_, ? _Subsumer_) - - - -Succeed if _Subsumer_ unifies with the least general -generalization over _T1_ and - _T2_. - - -*/ - -/** @pred term_variables(? _Term_, - _Variables_) is iso - - - -Unify _Variables_ with the list of all variables of term - _Term_. The variables occur in the order of their first -appearance when traversing the term depth-first, left-to-right. - - -*/ - -/** @pred rational_term_to_tree(? _TI_,- _TF_, ?SubTerms, ?MoreSubterms) - - -The term _TF_ is a forest representation (without cycles and repeated -terms) for the Prolog term _TI_. The term _TF_ is the main term. The -difference list _SubTerms_-_MoreSubterms_ stores terms of the form -_V=T_, where _V_ is a new variable occuring in _TF_, and _T_ is a copy -of a sub-term from _TI_. - - -*/ - -/** @pred term_factorized(? _TI_,- _TF_, ?SubTerms) - - -Similar to rational_term_to_tree/4, but _SubTerms_ is a proper list. - - -*/ - - -/** @defgroup Predicates_on_Atoms Predicates on Atoms -@ingroup builtins -@{ - -The following predicates are used to manipulate atoms: - - - -*/ - -/** @pred name( _A_, _L_) - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ will -be unified with an atomic symbol and _L_ with the list of the ASCII -codes for the characters of the external representation of _A_. - -~~~~~{.prolog} - name(yap,L). -~~~~~ -will return: - -~~~~~{.prolog} - L = [121,97,112]. -~~~~~ -and - -~~~~~{.prolog} - name(3,L). -~~~~~ -will return: - -~~~~~{.prolog} - L = [51]. -~~~~~ - - -*/ - -/** @pred atom_chars(? _A_,? _L_) is iso - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ must -be unifiable with an atom, and the argument _L_ with the list of the -characters of _A_. - - -*/ - -/** @pred atom_codes(? _A_,? _L_) is iso - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ will -be unified with an atom and _L_ with the list of the ASCII -codes for the characters of the external representation of _A_. - - -*/ - -/** @pred atom_concat(+ _As_,? _A_) - - -The predicate holds when the first argument is a list of atoms, and the -second unifies with the atom obtained by concatenating all the atoms in -the first list. - - -*/ - -/** @pred atomic_concat(+ _As_,? _A_) - - -The predicate holds when the first argument is a list of atomic terms, and -the second unifies with the atom obtained by concatenating all the -atomic terms in the first list. The first argument thus may contain -atoms or numbers. - - -*/ - -/** @pred atomic_list_concat(+ _As_,? _A_) - - -The predicate holds when the first argument is a list of atomic terms, and -the second unifies with the atom obtained by concatenating all the -atomic terms in the first list. The first argument thus may contain -atoms or numbers. - - -*/ - -/** @pred atomic_list_concat(? _As_,+ _Separator_,? _A_) - -Creates an atom just like atomic_list_concat/2, but inserts - _Separator_ between each pair of atoms. For example: - -~~~~~{.prolog} -?- atomic_list_concat([gnu, gnat], `, `, A). - -A = `gnu, gnat` -~~~~~ - -YAP emulates the SWI-Prolog version of this predicate that can also be -used to split atoms by instantiating _Separator_ and _Atom_ as -shown below. - -~~~~~{.prolog} -?- atomic_list_concat(L, -, 'gnu-gnat'). - -L = [gnu, gnat] -~~~~~ - - -*/ - -/** @pred atom_length(+ _A_,? _I_) is iso - - -The predicate holds when the first argument is an atom, and the second -unifies with the number of characters forming that atom. - - -*/ - -/** @pred atom_concat(? _A1_,? _A2_,? _A12_) is iso - -The predicate holds when the third argument unifies with an atom, and -the first and second unify with atoms such that their representations -concatenated are the representation for _A12_. - -If _A1_ and _A2_ are unbound, the built-in will find all the atoms -that concatenated give _A12_. - - -*/ - -/** @pred number_chars(? _I_,? _L_) is iso - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _I_ must -be unifiable with a number, and the argument _L_ with the list of the -characters of the external representation of _I_. - - -*/ - -/** @pred number_codes(? _A_,? _L_) is iso - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _A_ -will be unified with a number and _L_ with the list of the ASCII -codes for the characters of the external representation of _A_. - - -*/ - -/** @pred atom_number(? _Atom_,? _Number_) - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). If the argument - _Atom_ is an atom, _Number_ must be the number corresponding -to the characters in _Atom_, otherwise the characters in - _Atom_ must encode a number _Number_. - - -*/ - -/** @pred number_atom(? _I_,? _L_) - - - -The predicate holds when at least one of the arguments is ground -(otherwise, an error message will be displayed). The argument _I_ must -be unifiable with a number, and the argument _L_ must be unifiable -with an atom representing the number. - - -*/ - -/** @pred sub_atom(+ _A_,? _Bef_, ? _Size_, ? _After_, ? _At_out_) is iso - - -True when _A_ and _At_out_ are atoms such that the name of - _At_out_ has size _Size_ and is a sub-string of the name of - _A_, such that _Bef_ is the number of characters before and - _After_ the number of characters afterwards. - -Note that _A_ must always be known, but _At_out_ can be unbound when -calling this built-in. If all the arguments for sub_atom/5 but _A_ -are unbound, the built-in will backtrack through all possible -sub-strings of _A_. - - - - - */ - -/** @defgroup Predicates_on_Characters Predicates on Characters -@ingroup builtins -@{ - -The following predicates are used to manipulate characters: - - - -*/ - -/** @pred char_code(? _A_,? _I_) is iso - - -The built-in succeeds with _A_ bound to character represented as an -atom, and _I_ bound to the character code represented as an -integer. At least, one of either _A_ or _I_ must be bound before -the call. - - -*/ - -/** @pred char_type(? _Char_, ? _Type_) - - -Tests or generates alternative _Types_ or _Chars_. The -character-types are inspired by the standard `C` -`` primitives. - -+ `alnum` - _Char_ is a letter (upper- or lowercase) or digit. - -+ `alpha` - _Char_ is a letter (upper- or lowercase). - -+ `csym` - _Char_ is a letter (upper- or lowercase), digit or the underscore (_). These are valid C- and Prolog symbol characters. - -+ `csymf` - _Char_ is a letter (upper- or lowercase) or the underscore (_). These are valid first characters for C- and Prolog symbols - -+ `ascii` - _Char_ is a 7-bits ASCII character (0..127). - -+ `white` - _Char_ is a space or tab. E.i. white space inside a line. - -+ `cntrl` - _Char_ is an ASCII control-character (0..31). - -+ `digit` - _Char_ is a digit. - -+ `digit( _Weight_)` - _Char_ is a digit with value _Weight_. I.e. `char_type(X, digit(6))` yields X = aaasaá'6'. Useful for parsing numbers. - -+ `xdigit( _Weight_)` - _Char_ is a hexa-decimal digit with value _Weight_. I.e. char_type(a, xdigit(X) yields X = '10'. Useful for parsing numbers. - -+ `graph` - _Char_ produces a visible mark on a page when printed. Note that the space is not included! - -+ `lower` - _Char_ is a lower-case letter. - -+ `lower(Upper)` - _Char_ is a lower-case version of _Upper_. Only true if _Char_ is lowercase and _Upper_ uppercase. - -+ `to_lower(Upper)` - _Char_ is a lower-case version of Upper. For non-letters, or letter without case, _Char_ and Lower are the same. See also upcase_atom/2 and downcase_atom/2. - -+ `upper` - _Char_ is an upper-case letter. - -+ `upper(Lower)` - _Char_ is an upper-case version of Lower. Only true if _Char_ is uppercase and Lower lowercase. - -+ `to_upper(Lower)` - _Char_ is an upper-case version of Lower. For non-letters, or letter without case, _Char_ and Lower are the same. See also upcase_atom/2 and downcase_atom/2. - -+ `punct` - _Char_ is a punctuation character. This is a graph character that is not a letter or digit. - -+ `space` - _Char_ is some form of layout character (tab, vertical-tab, newline, etc.). - -+ `end_of_file` - _Char_ is -1. - -+ `end_of_line` - _Char_ ends a line (ASCII: 10..13). - -+ `newline` - _Char_ is a the newline character (10). - -+ `period` - _Char_ counts as the end of a sentence (.,!,?). - -+ `quote` - _Char_ is a quote-character. - -+ `paren(Close)` - _Char_ is an open-parenthesis and Close is the corresponding close-parenthesis. - - -+ `code_type(? _Code_, ? _Type_)` - - -As char_type/2, but uses character-codes rather than -one-character atoms. Please note that both predicates are as -flexible as possible. They handle either representation if the -argument is instantiated and only will instantiate with an integer -code or one-character atom depending of the version used. See also -the prolog-flag double_quotes and the built-in predicates -atom_chars/2 and atom_codes/2. - - - - - */ - -/** @defgroup Comparing_Terms Comparing Terms -@ingroup builtins -@{ - -The following predicates are used to compare and order terms, using the -standard ordering: - -+ -variables come before numbers, numbers come before atoms which in turn -come before compound terms, i.e.: variables @< numbers @< atoms @< -compound terms. -+ -Variables are roughly ordered by "age" (the "oldest" variable is put -first); -+ -Floating point numbers are sorted in increasing order; -+ -Rational numbers are sorted in increasing order; -+ -Integers are sorted in increasing order; -+ -Atoms are sorted in lexicographic order; -+ -Compound terms are ordered first by arity of the main functor, then by -the name of the main functor, and finally by their arguments in -left-to-right order. - - - - - -*/ - -/** @pred compare( _C_, _X_, _Y_) is iso - - -As a result of comparing _X_ and _Y_, _C_ may take one of -the following values: - -+ -`=` if _X_ and _Y_ are identical; -+ -`<` if _X_ precedes _Y_ in the defined order; -+ -`>` if _Y_ precedes _X_ in the defined order; - - -+ _X_ == _Y_ is iso - - -Succeeds if terms _X_ and _Y_ are strictly identical. The -difference between this predicate and =/2 is that, if one of the -arguments is a free variable, it only succeeds when they have already -been unified. - -~~~~~{.prolog} -?- X == Y. -~~~~~ -fails, but, - -~~~~~{.prolog} -?- X = Y, X == Y. -~~~~~ -succeeds. - -~~~~~{.prolog} -?- X == 2. -~~~~~ -fails, but, - -~~~~~{.prolog} -?- X = 2, X == 2. -~~~~~ -succeeds. - - -*/ - -/** @pred _X_ \== _Y_ is iso - - -Terms _X_ and _Y_ are not strictly identical. - - -*/ - -/** @pred _X_ @< _Y_ is iso - - -Term _X_ precedes term _Y_ in the standard order. - - -*/ - -/** @pred _X_ @=< _Y_ is iso - - -Term _X_ does not follow term _Y_ in the standard order. - - -*/ - -/** @pred _X_ @> _Y_ is iso - - -Term _X_ follows term _Y_ in the standard order. - - -*/ - -/** @pred _X_ @>= _Y_ is iso - - -Term _X_ does not precede term _Y_ in the standard order. - - -*/ - -/** @pred sort(+ _L_,- _S_) is iso - - -Unifies _S_ with the list obtained by sorting _L_ and merging -identical (in the sense of `==`) elements. - - -*/ - -/** @pred keysort(+ _L_, _S_) is iso - - -Assuming L is a list of the form ` _Key_- _Value_`, -`keysort(+ _L_, _S_)` unifies _S_ with the list obtained -from _L_, by sorting its elements according to the value of - _Key_. - -~~~~~{.prolog} -?- keysort([3-a,1-b,2-c,1-a,1-b],S). -~~~~~ -would return: - -~~~~~{.prolog} -S = [1-b,1-a,1-b,2-c,3-a] -~~~~~ - - -*/ - -/** @pred predsort(+ _Pred_, + _List_, - _Sorted_) - - -Sorts similar to sort/2, but determines the order of two terms by -calling _Pred_(- _Delta_, + _E1_, + _E2_) . This call must -unify _Delta_ with one of `<`, `>` or `=`. If -built-in predicate compare/3 is used, the result is the same as -sort/2. - - -*/ - -/** @pred length(? _L_,? _S_) - - -Unify the well-defined list _L_ with its length. The procedure can -be used to find the length of a pre-defined list, or to build a list -of length _S_. - - - - - */ - -/** @defgroup Arithmetic Arithmetic -@ingroup builtins -@{ - -@copydoc arithmetic - - * See @ref arithmetic_preds for the predicates that implement arithment - - * See @ref arithmetic_cmps for the arithmetic comparisons supported in YAP - - * See @ref arithmetic_operators for how to call arithmetic operations in YAP - - - */ - -/** @defgroup InputOutput Input/Output Predicates -@ingroup builtins -@{ - -Some of the Input/Output predicates described below will in certain conditions -provide error messages and abort only if the file_errors flag is set. -If this flag is cleared the same predicates will just fail. Details on -setting and clearing this flag are given under 7.7. - - - */ - -/** @defgroup Streams_and_Files Handling Streams and Files -@ingroup builtins -@{ - - - - -*/ - -/** @pred open(+ _F_,+ _M_,- _S_) is iso - - -Opens the file with name _F_ in mode _M_ (`read`, `write` or -`append`), returning _S_ unified with the stream name. - -At most, there are 17 streams opened at the same time. Each stream is -either an input or an output stream but not both. There are always 3 -open streams: user_input for reading, user_output for writing -and user_error for writing. If there is no ambiguity, the atoms -user_input and user_output may be referred to as `user`. - -The `file_errors` flag controls whether errors are reported when in -mode `read` or `append` the file _F_ does not exist or is not -readable, and whether in mode `write` or `append` the file is not -writable. - -*/ - -/** @pred open(+ _F_,+ _M_,- _S_,+ _Opts_) is iso - -Opens the file with name _F_ in mode _M_ (`read`, `write` or -`append`), returning _S_ unified with the stream name, and following -these options: - - - -+ `type(+ _T_)` is iso - - Specify whether the stream is a `text` stream (default), or a -`binary` stream. - -+ `reposition(+ _Bool_)` is iso - Specify whether it is possible to reposition the stream (`true`), or -not (`false`). By default, YAP enables repositioning for all -files, except terminal files and sockets. - -+ `eof(+ _Action_)` is iso - - Specify the action to take if attempting to input characters from a -stream where we have previously found an `end_of_file`. The possible -actions are `error`, that raises an error, `reset`, that tries to -reset the stream and is used for `tty` type files, and `eof_code`, -which generates a new `end_of_file` (default for non-tty files). - -+ `alias(+ _Name_)` is iso - - Specify an alias to the stream. The alias Name must be an atom. The -alias can be used instead of the stream descriptor for every operation -concerning the stream. - - The operation will fail and give an error if the alias name is already -in use. YAP allows several aliases for the same file, but only -one is returned by stream_property/2 - -+ `bom(+ _Bool_)` - - If present and `true`, a BOM (Byte Order Mark) was -detected while opening the file for reading or a BOM was written while -opening the stream. See BOM for details. - -+ `encoding(+ _Encoding_)` - -Set the encoding used for text. See Encoding for an overview of -wide character and encoding issues. - -+ `representation_errors(+ _Mode_)` - - Change the behaviour when writing characters to the stream that cannot -be represented by the encoding. The behaviour is one of `error` -(throw and Input/Output error exception), `prolog` (write `\u...\` -escape code or `xml` (write `\&#...;` XML character entity). -The initial mode is `prolog` for the user streams and -`error` for all other streams. See also Encoding. - -+ `expand_filename(+ _Mode_)` - - If _Mode_ is `true` then do filename expansion, then ask Prolog -to do file name expansion before actually trying to opening the file: -this includes processing `~` characters and processing `$` -environment variables at the beginning of the file. Otherwise, just try -to open the file using the given name. - - The default behavior is given by the Prolog flag -open_expands_filename. - - - - -*/ - -/** @pred close(+ _S_) is iso - - -Closes the stream _S_. If _S_ does not stand for a stream -currently opened an error is reported. The streams user_input, -user_output, and user_error can never be closed. - - -*/ - -/** @pred close(+ _S_,+ _O_) is iso - -Closes the stream _S_, following options _O_. - -The only valid options are `force(true)` and `force(false)`. -YAP currently ignores these options. - - -*/ - -/** @pred time_file(+ _File_,- _Time_) - - -Unify the last modification time of _File_ with - _Time_. _Time_ is a floating point number expressing the seconds -elapsed since Jan 1, 1970. - - -*/ - -/** @pred access_file(+ _F_,+ _M_) - -Is the file accessible? - - -*/ - -/** @pred file_base_name(+ _Name_,- _FileName_) - - -Give the path a full path _FullPath_ extract the _FileName_. - - -*/ - -/** @pred file_name_extension(? _Base_,? _Extension_, ? _Name_) - - - -This predicate is used to add, remove or test filename extensions. The -main reason for its introduction is to deal with different filename -properties in a portable manner. If the file system is -case-insensitive, testing for an extension will be done -case-insensitive too. _Extension_ may be specified with or -without a leading dot (.). If an _Extension_ is generated, it -will not have a leading dot. - - -*/ - -/** @pred current_stream( _F_, _M_, _S_) - - -Defines the relation: The stream _S_ is opened on the file _F_ -in mode _M_. It might be used to obtain all open streams (by -backtracking) or to access the stream for a file _F_ in mode - _M_, or to find properties for a stream _S_. Notice that some -streams might not be associated to a file: in this case YAP tries to -return the file number. If that is not available, YAP unifies _F_ -with _S_. - - -*/ - -/** @pred is_stream( _S_) - - -Succeeds if _S_ is a currently open stream. - - -*/ - -/** @pred flush_output is iso - - -Send out all data in the output buffer of the current output stream. - - -*/ - -/** @pred flush_output(+ _S_) is iso - -Send all data in the output buffer for stream _S_. - - -*/ - -/** @pred set_input(+ _S_) is iso - - -Set stream _S_ as the current input stream. Predicates like read/1 -and get/1 will start using stream _S_. - - -*/ - -/** @pred set_output(+ _S_) is iso - - -Set stream _S_ as the current output stream. Predicates like -write/1 and put/1 will start using stream _S_. - - -*/ - -/** @pred stream_select(+ _STREAMS_,+ _TIMEOUT_,- _READSTREAMS_) - - -Given a list of open _STREAMS_ opened in read mode and a _TIMEOUT_ -return a list of streams who are now available for reading. - -If the _TIMEOUT_ is instantiated to `off`, -stream_select/3 will wait indefinitely for a stream to become -open. Otherwise the timeout must be of the form `SECS:USECS` where -`SECS` is an integer gives the number of seconds to wait for a timeout -and `USECS` adds the number of micro-seconds. - -This built-in is only defined if the system call `select` is -available in the system. - - -*/ - -/** @pred current_input(- _S_) is iso - - -Unify _S_ with the current input stream. - - -*/ - -/** @pred current_output(- _S_) is iso - - -Unify _S_ with the current output stream. - - -*/ - -/** @pred at_end_of_stream is iso - - -Succeed if the current stream has stream position end-of-stream or -past-end-of-stream. - - -*/ - -/** @pred at_end_of_stream(+ _S_) is iso - -Succeed if the stream _S_ has stream position end-of-stream or -past-end-of-stream. Note that _S_ must be a readable stream. - - -*/ - -/** @pred set_stream_position(+ _S_, + _POS_) is iso - - -Given a stream position _POS_ for a stream _S_, set the current -stream position for _S_ to be _POS_. - - -*/ - -/** @pred stream_property(? _Stream_,? _Prop_) is iso - - - -Obtain the properties for the open streams. If the first argument is -unbound, the procedure will backtrack through all open -streams. Otherwise, the first argument must be a stream term (you may -use `current_stream` to obtain a current stream given a file name). - -The following properties are recognized: - - - -+ file_name( _P_) -An atom giving the file name for the current stream. The file names are -user_input, user_output, and user_error for the -standard streams. - -+ mode( _P_) -The mode used to open the file. It may be one of `append`, -`read`, or `write`. - -+ input -The stream is readable. - -+ output -The stream is writable. - -+ alias( _A_) -ISO-Prolog primitive for stream aliases. YAP returns one of the -existing aliases for the stream. - -+ position( _P_) -A term describing the position in the stream. - -+ end_of_stream( _E_) -Whether the stream is `at` the end of stream, or it has found the -end of stream and is `past`, or whether it has `not` yet -reached the end of stream. - -+ eof_action( _A_) -The action to take when trying to read after reaching the end of -stream. The action may be one of `error`, generate an error, -`eof_code`, return character code `-1`, or `reset` the -stream. - -+ reposition( _B_) -Whether the stream can be repositioned or not, that is, whether it is -seekable. - -+ type( _T_) -Whether the stream is a `text` stream or a `binary` stream. - -+ bom(+ _Bool_) -If present and `true`, a BOM (Byte Order Mark) was -detected while opening the file for reading or a BOM was written while -opening the stream. See BOM for details. - -+ encoding(+ _Encoding_) -Query the encoding used for text. See Encoding for an -overview of wide character and encoding issues in YAP. - -+ representation_errors(+ _Mode_) -Behaviour when writing characters to the stream that cannot be -represented by the encoding. The behaviour is one of `error` -(throw and Input/Output error exception), `prolog` (write `\u...\` -escape code or `xml` (write `\&#...;` XML character entity). -The initial mode is `prolog` for the user streams and -`error` for all other streams. See also Encoding and -`open/4`. - - - -+ current_line_number(- _LineNumber_) - - -Unify _LineNumber_ with the line number for the current stream. - - -*/ - -/** @pred current_line_number(+ _Stream_,- _LineNumber_) - -Unify _LineNumber_ with the line number for the _Stream_. - - -*/ - -/** @pred line_count(+ _Stream_,- _LineNumber_) - - -Unify _LineNumber_ with the line number for the _Stream_. - - -*/ - -/** @pred character_count(+ _Stream_,- _CharacterCount_) - - -Unify _CharacterCount_ with the number of characters written to or -read to _Stream_. - - -*/ - -/** @pred line_position(+ _Stream_,- _LinePosition_) - - -Unify _LinePosition_ with the position on current text stream - _Stream_. - - -*/ - -/** @pred stream_position(+ _Stream_,- _StreamPosition_) - - -Unify _StreamPosition_ with the packaged information of position on -current stream _Stream_. Use stream_position_data/3 to -retrieve information on character or line count. - - -*/ - -/** @pred stream_position_data(+ _Field_,+ _StreamPosition_,- _Info_) - - -Given the packaged stream position term _StreamPosition_, unify - _Info_ with _Field_ `line_count`, `byte_count`, or -`char_count`. - - - - - */ - -/** @defgroup ChYProlog_File_Handling C-Prolog File Handling -@ingroup builtins -@{ - - - - -*/ - -/** @pred tell(+ _S_) - - -If _S_ is a currently opened stream for output, it becomes the -current output stream. If _S_ is an atom it is taken to be a -filename. If there is no output stream currently associated with it, -then it is opened for output, and the new output stream created becomes -the current output stream. If it is not possible to open the file, an -error occurs. If there is a single opened output stream currently -associated with the file, then it becomes the current output stream; if -there are more than one in that condition, one of them is chosen. - -Whenever _S_ is a stream not currently opened for output, an error -may be reported, depending on the state of the file_errors flag. The -predicate just fails, if _S_ is neither a stream nor an atom. - - -*/ - -/** @pred telling(- _S_) - - -The current output stream is unified with _S_. - - -*/ - -/** @pred told - - -Closes the current output stream, and the user's terminal becomes again -the current output stream. It is important to remember to close streams -after having finished using them, as the maximum number of -simultaneously opened streams is 17. - - -*/ - -/** @pred see(+ _S_) - - -If _S_ is a currently opened input stream then it is assumed to be -the current input stream. If _S_ is an atom it is taken as a -filename. If there is no input stream currently associated with it, then -it is opened for input, and the new input stream thus created becomes -the current input stream. If it is not possible to open the file, an -error occurs. If there is a single opened input stream currently -associated with the file, it becomes the current input stream; if there -are more than one in that condition, then one of them is chosen. - -When _S_ is a stream not currently opened for input, an error may be -reported, depending on the state of the `file_errors` flag. If - _S_ is neither a stream nor an atom the predicates just fails. - - -*/ - -/** @pred seeing(- _S_) - - -The current input stream is unified with _S_. - - -*/ - -/** @pred seen - - -Closes the current input stream (see 6.7.). - - - - - */ - -/** @defgroup InputOutput_of_Terms Handling Input/Output of Terms -@ingroup builtins -@{ - - - - -*/ - -/** @pred read(- _T_) is iso - - -Reads the next term from the current input stream, and unifies it with - _T_. The term must be followed by a dot (`.`) and any blank-character -as previously defined. The syntax of the term must match the current -declarations for operators (see op). If the end-of-stream is reached, - _T_ is unified with the atom `end_of_file`. Further reads from of -the same stream may cause an error failure (see open/3). - -*/ - -/** @pred read_term(- _T_,+ _Options_) is iso - - -Reads term _T_ from the current input stream with execution -controlled by the following options: - -+ term_position(- _Position_) - -Unify _Position_ with a term describing the position of the stream -at the start of parse. Use stream_position_data/3 to obtain extra -information. - -+ singletons(- _Names_) - -Unify _Names_ with a list of the form _Name=Var_, where - _Name_ is the name of a non-anonymous singleton variable in the -original term, and `Var` is the variable's representation in -YAP. -The variables occur in left-to-right traversal order. - -+ syntax_errors(+ _Val_) - -Control action to be taken after syntax errors. See yap_flag/2 -for detailed information. - -+ variables(- _Names_) - -Unify _Names_ with a list of the form _Name=Var_, where _Name_ is -the name of a non-anonymous variable in the original term, and _Var_ -is the variable's representation in YAP. -The variables occur in left-to-right traversal order. - - -*/ - -/** @pred char_conversion(+ _IN_,+ _OUT_) is iso - - -While reading terms convert unquoted occurrences of the character - _IN_ to the character _OUT_. Both _IN_ and _OUT_ must be -bound to single characters atoms. - -Character conversion only works if the flag `char_conversion` is -on. This is default in the `iso` and `sicstus` language -modes. As an example, character conversion can be used for instance to -convert characters from the ISO-LATIN-1 character set to ASCII. - -If _IN_ is the same character as _OUT_, char_conversion/2 -will remove this conversion from the table. - - -*/ - -/** @pred current_char_conversion(? _IN_,? _OUT_) is iso - - -If _IN_ is unbound give all current character -translations. Otherwise, give the translation for _IN_, if one -exists. - - -*/ - -/** @pred write( _T_) is iso - - -The term _T_ is written to the current output stream according to -the operator declarations in force. - - -*/ - -/** @pred writeln( _T_) is iso - - -Same as write/1 followed by nl/0. - - -*/ - -/** @pred display(+ _T_) - - -Displays term _T_ on the current output stream. All Prolog terms are -written in standard parenthesized prefix notation. - - -*/ - -/** @pred write_canonical(+ _T_) is iso - - -Displays term _T_ on the current output stream. Atoms are quoted -when necessary, and operators are ignored, that is, the term is written -in standard parenthesized prefix notation. - - -*/ - -/** @pred write_term(+ _T_, + _Opts_) is iso - - -Displays term _T_ on the current output stream, according to the -following options: - -+ quoted(+ _Bool_) is iso -If `true`, quote atoms if this would be necessary for the atom to -be recognized as an atom by YAP's parser. The default value is -`false`. - -+ ignore_ops(+ _Bool_) is iso -If `true`, ignore operator declarations when writing the term. The -default value is `false`. - -+ numbervars(+ _Bool_) is iso -If `true`, output terms of the form -`$VAR(N)`, where _N_ is an integer, as a sequence of capital -letters. The default value is `false`. - -+ portrayed(+ _Bool_) -If `true`, use portray/1 to portray bound terms. The default -value is `false`. - -+ portray(+ _Bool_) -If `true`, use portray/1 to portray bound terms. The default -value is `false`. - -+ max_depth(+ _Depth_) -If `Depth` is a positive integer, use Depth as -the maximum depth to portray a term. The default is `0`, that is, -unlimited depth. - -+ priority(+ _Piority_) -If `Priority` is a positive integer smaller than `1200`, -give the context priority. The default is `1200`. - -+ cycles(+ _Bool_) -Do not loop in rational trees (default). - - - -*/ - -/** @pred writeq( _T_) is iso - - -Writes the term _T_, quoting names to make the result acceptable to -the predicate `read` whenever necessary. - - -*/ - -/** @pred print( _T_) - - -Prints the term _T_ to the current output stream using write/1 -unless T is bound and a call to the user-defined predicate -`portray/1` succeeds. To do pretty printing of terms the user should -define suitable clauses for `portray/1` and use print/1. - - -*/ - -/** @pred format(+ _T_,+ _L_) - - -Print formatted output to the current output stream. The arguments in -list _L_ are output according to the string or atom _T_. - -A control sequence is introduced by a `w`. The following control -sequences are available in YAP: - - - -+ `~~` -Print a single tilde. - -+ `~a` -The next argument must be an atom, that will be printed as if by `write`. - -+ `~Nc` -The next argument must be an integer, that will be printed as a -character code. The number _N_ is the number of times to print the -character (default 1). - -+ `~Ne` -+ `~NE` -+ `~Nf` -+ `~Ng` -+ `~NG` -The next argument must be a floating point number. The float _F_, the number - _N_ and the control code `c` will be passed to `printf` as: - -~~~~~{.prolog} - printf("%s.Nc", F) -~~~~~ - -As an example: - -~~~~~{.prolog} -?- format("~8e, ~8E, ~8f, ~8g, ~8G~w", - [3.14,3.14,3.14,3.14,3.14,3.14]). -3.140000e+00, 3.140000E+00, 3.140000, 3.14, 3.143.14 -~~~~~ - -+ `~Nd` -The next argument must be an integer, and _N_ is the number of digits -after the decimal point. If _N_ is `0` no decimal points will be -printed. The default is _N = 0_. - -~~~~~{.prolog} -?- format("~2d, ~d",[15000, 15000]). -150.00, 15000 -~~~~~ - -+ `~ND` -Identical to `~Nd`, except that commas are used to separate groups -of three digits. - -~~~~~{.prolog} -?- format("~2D, ~D",[150000, 150000]). -1,500.00, 150,000 -~~~~~ - -+ `~i` -Ignore the next argument in the list of arguments: - -~~~~~{.prolog} -?- format('The ~i met the boregrove',[mimsy]). -The met the boregrove -~~~~~ - -+ `~k` -Print the next argument with `write_canonical`: - -~~~~~{.prolog} -?- format("Good night ~k",a+[1,2]). -Good night +(a,[1,2]) -~~~~~ - -+ `~Nn` -Print _N_ newlines (where _N_ defaults to 1). - -+ `~NN` -Print _N_ newlines if at the beginning of the line (where _N_ -defaults to 1). - -+ `~Nr` -The next argument must be an integer, and _N_ is interpreted as a -radix, such that `2 <= N <= 36` (the default is 8). - -~~~~~{.prolog} -?- format("~2r, 0x~16r, ~r", - [150000, 150000, 150000]). -100100100111110000, 0x249f0, 444760 -~~~~~ - -Note that the letters `a-z` denote digits larger than 9. - -+ `~NR` -Similar to `~NR`. The next argument must be an integer, and _N_ is -interpreted as a radix, such that `2 <= N <= 36` (the default is 8). - -~~~~~{.prolog} -?- format("~2r, 0x~16r, ~r", - [150000, 150000, 150000]). -100100100111110000, 0x249F0, 444760 -~~~~~ - -The only difference is that letters `A-Z` denote digits larger than 9. - -+ `~p` -Print the next argument with print/1: - -~~~~~{.prolog} -?- format("Good night ~p",a+[1,2]). -Good night a+[1,2] -~~~~~ - -+ `~q` -Print the next argument with writeq/1: - -~~~~~{.prolog} -?- format("Good night ~q",'Hello'+[1,2]). -Good night 'Hello'+[1,2] -~~~~~ - -+ `~Ns` -The next argument must be a list of character codes. The system then -outputs their representation as a string, where _N_ is the maximum -number of characters for the string ( _N_ defaults to the length of the -string). - -~~~~~{.prolog} -?- format("The ~s are ~4s",["woods","lovely"]). -The woods are love -~~~~~ - -+ `~w` -Print the next argument with write/1: - -~~~~~ -?- format("Good night ~w",'Hello'+[1,2]). -Good night Hello+[1,2] -~~~~~ - - -The number of arguments, `N`, may be given as an integer, or it -may be given as an extra argument. The next example shows a small -procedure to write a variable number of `a` characters: - -~~~~~ -write_many_as(N) :- - format("~*c",[N,0'a]). -~~~~~ - -The format/2 built-in also allows for formatted output. One can -specify column boundaries and fill the intermediate space by a padding -character: - -+ `~N|` -Set a column boundary at position _N_, where _N_ defaults to the -current position. - -+ `~N+` -Set a column boundary at _N_ characters past the current position, where - _N_ defaults to `8`. - -+ `~Nt` -Set padding for a column, where _N_ is the fill code (default is -`SPC`). - - - -The next example shows how to align columns and padding. We first show -left-alignment: - -~~~~~ - ?- format("~n*Hello~16+*~n",[]). -*Hello * -~~~~~ - -Note that we reserve 16 characters for the column. - -The following example shows how to do right-alignment: - -~~~~~ - ?- format("*~tHello~16+*~n",[]). -* Hello* - -~~~~~ - -The `~t` escape sequence forces filling before `Hello`. - -We next show how to do centering: - -~~~~~ - ?- format("*~tHello~t~16+*~n",[]). -* Hello * -~~~~~ - -The two `~t` escape sequence force filling both before and after -`Hello`. Space is then evenly divided between the right and the -left sides. - - -*/ - -/** @pred format(+ _T_) - -Print formatted output to the current output stream. - - -*/ - -/** @pred format(+ _S_,+ _T_,+ _L_) - -Print formatted output to stream _S_. - - -*/ - -/** @pred with_output_to(+ _Ouput_,: _Goal_) - - -Run _Goal_ as once/1, while characters written to the current -output are sent to _Output_. The predicate is SWI-Prolog -specific. - -Applications should generally avoid creating atoms by breaking and -concatenating other atoms as the creation of large numbers of -intermediate atoms generally leads to poor performance, even more so in -multi-threaded applications. This predicate supports creating -difference-lists from character data efficiently. The example below -defines the DCG rule `term/3` to insert a term in the output: - -~~~~~ - term(Term, In, Tail) :- - with_output_to(codes(In, Tail), write(Term)). - -?- phrase(term(hello), X). - -X = [104, 101, 108, 108, 111] -~~~~~ - -+ A Stream handle or alias -Temporary switch current output to the given stream. Redirection using with_output_to/2 guarantees the original output is restored, also if Goal fails or raises an exception. See also call_cleanup/2. -+ atom(- _Atom_) -Create an atom from the emitted characters. Please note the remark above. -+ string(- _String_) -Create a string-object (not supported in YAP). -+ codes(- _Codes_) -Create a list of character codes from the emitted characters, similar to atom_codes/2. -+ codes(- _Codes_, - _Tail_) -Create a list of character codes as a difference-list. -+ chars(- _Chars_) -Create a list of one-character-atoms codes from the emitted characters, similar to atom_chars/2. -+ chars(- _Chars_, - _Tail_) -Create a list of one-character-atoms as a difference-list. - - - - - - */ - -/** @defgroup InputOutput_of_Characters Handling Input/Output of Characters -@ingroup builtins -@{ - - - - -*/ - -/** @pred put(+ _N_) - - -Outputs to the current output stream the character whose ASCII code is - _N_. The character _N_ must be a legal ASCII character code, an -expression yielding such a code, or a list in which case only the first -element is used. - - -*/ - -/** @pred put_byte(+ _N_) is iso - - -Outputs to the current output stream the character whose code is - _N_. The current output stream must be a binary stream. - - -*/ - -/** @pred put_char(+ _N_) is iso - - -Outputs to the current output stream the character who is used to build -the representation of atom `A`. The current output stream must be a -text stream. - - -*/ - -/** @pred put_code(+ _N_) is iso - - -Outputs to the current output stream the character whose ASCII code is - _N_. The current output stream must be a text stream. The character - _N_ must be a legal ASCII character code, an expression yielding such -a code, or a list in which case only the first element is used. - - -*/ - -/** @pred get(- _C_) - - -The next non-blank character from the current input stream is unified -with _C_. Blank characters are the ones whose ASCII codes are not -greater than 32. If there are no more non-blank characters in the -stream, _C_ is unified with -1. If `end_of_stream` has already -been reached in the previous reading, this call will give an error message. - - -*/ - -/** @pred get0(- _C_) - - -The next character from the current input stream is consumed, and then -unified with _C_. There are no restrictions on the possible -values of the ASCII code for the character, but the character will be -internally converted by YAP. - - -*/ - -/** @pred get_byte(- _C_) is iso - - -If _C_ is unbound, or is a character code, and the current stream is a -binary stream, read the next byte from the current stream and unify its -code with _C_. - - -*/ - -/** @pred get_char(- _C_) is iso - - -If _C_ is unbound, or is an atom representation of a character, and -the current stream is a text stream, read the next character from the -current stream and unify its atom representation with _C_. - - -*/ - -/** @pred get_code(- _C_) is iso - - -If _C_ is unbound, or is the code for a character, and -the current stream is a text stream, read the next character from the -current stream and unify its code with _C_. - - -*/ - -/** @pred peek_byte(- _C_) is iso - - -If _C_ is unbound, or is a character code, and the current stream is a -binary stream, read the next byte from the current stream and unify its -code with _C_, while leaving the current stream position unaltered. - - -*/ - -/** @pred peek_char(- _C_) is iso - - -If _C_ is unbound, or is an atom representation of a character, and -the current stream is a text stream, read the next character from the -current stream and unify its atom representation with _C_, while -leaving the current stream position unaltered. - - -*/ - -/** @pred peek_code(- _C_) is iso - - -If _C_ is unbound, or is the code for a character, and -the current stream is a text stream, read the next character from the -current stream and unify its code with _C_, while -leaving the current stream position unaltered. - - -*/ - -/** @pred skip(+ _N_) - - -Skips input characters until the next occurrence of the character with -ASCII code _N_. The argument to this predicate can take the same forms -as those for `put` (see 6.11). - - -*/ - -/** @pred tab(+ _N_) - - -Outputs _N_ spaces to the current output stream. - - -*/ - -/** @pred nl is iso - - -Outputs a new line to the current output stream. - - - - - */ - -/** @defgroup InputOutput_for_Streams Input/Output Predicates applied to Streams -@ingroup builtins -@{ - - - - -*/ - -/** @pred read(+ _S_,- _T_) is iso - -Reads term _T_ from the stream _S_ instead of from the current input -stream. - - -*/ - -/** @pred read_term(+ _S_,- _T_,+ _Options_) is iso - -Reads term _T_ from stream _S_ with execution controlled by the -same options as read_term/2. - - -*/ - -/** @pred write(+ _S_, _T_) is iso - -Writes term _T_ to stream _S_ instead of to the current output -stream. - - -*/ - -/** @pred write_canonical(+ _S_,+ _T_) is iso - -Displays term _T_ on the stream _S_. Atoms are quoted when -necessary, and operators are ignored. - - -*/ - -/** @pred write_term(+ _S_, + _T_, + _Opts_) is iso - -Displays term _T_ on the current output stream, according to the same -options used by `write_term/3`. - - -*/ - -/** @pred writeq(+ _S_, _T_) is iso - -As writeq/1, but the output is sent to the stream _S_. - - -*/ - -/** @pred display(+ _S_, _T_) - -Like display/1, but using stream _S_ to display the term. - - -*/ - -/** @pred print(+ _S_, _T_) - -Prints term _T_ to the stream _S_ instead of to the current output -stream. - - -*/ - -/** @pred put(+ _S_,+ _N_) - -As `put(N)`, but to stream _S_. - - -*/ - -/** @pred put_byte(+ _S_,+ _N_) is iso - -As `put_byte(N)`, but to binary stream _S_. - - -*/ - -/** @pred put_char(+ _S_,+ _A_) is iso - -As `put_char(A)`, but to text stream _S_. - - -*/ - -/** @pred put_code(+ _S_,+ _N_) is iso - -As `put_code(N)`, but to text stream _S_. - - -*/ - -/** @pred get(+ _S_,- _C_) - -The same as `get(C)`, but from stream _S_. - - -*/ - -/** @pred get0(+ _S_,- _C_) - -The same as `get0(C)`, but from stream _S_. - - -*/ - -/** @pred get_byte(+ _S_,- _C_) is iso - -If _C_ is unbound, or is a character code, and the stream _S_ is a -binary stream, read the next byte from that stream and unify its -code with _C_. - - -*/ - -/** @pred get_char(+ _S_,- _C_) is iso - -If _C_ is unbound, or is an atom representation of a character, and -the stream _S_ is a text stream, read the next character from that -stream and unify its representation as an atom with _C_. - - -*/ - -/** @pred get_code(+ _S_,- _C_) is iso - -If _C_ is unbound, or is a character code, and the stream _S_ is a -text stream, read the next character from that stream and unify its -code with _C_. - - -*/ - -/** @pred peek_byte(+ _S_,- _C_) is iso - -If _C_ is unbound, or is a character code, and _S_ is a binary -stream, read the next byte from the current stream and unify its code -with _C_, while leaving the current stream position unaltered. - - -*/ - -/** @pred peek_char(+ _S_,- _C_) is iso - -If _C_ is unbound, or is an atom representation of a character, and -the stream _S_ is a text stream, read the next character from that -stream and unify its representation as an atom with _C_, while leaving -the current stream position unaltered. - - -*/ - -/** @pred peek_code(+ _S_,- _C_) is iso - -If _C_ is unbound, or is an atom representation of a character, and -the stream _S_ is a text stream, read the next character from that -stream and unify its representation as an atom with _C_, while leaving -the current stream position unaltered. - - -*/ - -/** @pred skip(+ _S_,- _C_) - -Like skip/1, but using stream _S_ instead of the current -input stream. - - -*/ - -/** @pred tab(+ _S_,+ _N_) - -The same as tab/1, but using stream _S_. - - -*/ - -/** @pred nl(+ _S_) is iso - -Outputs a new line to stream _S_. - - - - - */ - -/** @defgroup ChYProlog_to_Terminal Compatible C-Prolog predicates for Terminal Input/Output -@ingroup builtins -@{ - - - - -*/ - -/** @pred ttyput(+ _N_) - - -As `put(N)` but always to user_output. - - -*/ - -/** @pred ttyget(- _C_) - - -The same as `get(C)`, but from stream user_input. - - -*/ - -/** @pred ttyget0(- _C_) - - -The same as `get0(C)`, but from stream user_input. - - -*/ - -/** @pred ttyskip(- _C_) - - -Like skip/1, but always using stream user_input. -stream. - - -*/ - -/** @pred ttynl - - -Outputs a new line to stream user_output. - - - - - */ - -/** @defgroup InputOutput_Control Controlling Input/Output -@ingroup builtins -@{ - - - - -*/ - -/** @pred exists(+ _F_) - - -Checks if file _F_ exists in the current directory. - -*/ - -/** @pred nofileerrors - - -Switches off the file_errors flag, so that the predicates see/1, -tell/1, open/3 and close/1 just fail, instead of producing -an error message and aborting whenever the specified file cannot be -opened or closed. - -*/ - -/** @pred fileerrors - - -Switches on the file_errors flag so that in certain error conditions -Input/Output predicates will produce an appropriated message and abort. - - */ - -/** @defgroup Sockets Using Sockets From YAP -@ingroup builtins -@{ - -YAP includes a SICStus Prolog compatible socket interface. In YAP-6.3 -this uses the `clib` package to emulate the old low level interface that -provides direct access to the major socket system calls. These calls -can be used both to open a new connection in the network or connect to -a networked server. Socket connections are described as read/write -streams, and standard Input/Output built-ins can be used to write on or read -from sockets. The following calls are available: - - - - -*/ - -/** @pred socket(+ _DOMAIN_,+ _TYPE_,+ _PROTOCOL_,- _SOCKET_) - - -Corresponds to the BSD system call `socket`. Create a socket for -domain _DOMAIN_ of type _TYPE_ and protocol - _PROTOCOL_. Both _DOMAIN_ and _TYPE_ should be atoms, -whereas _PROTOCOL_ must be an integer. -The new socket object is -accessible through a descriptor bound to the variable _SOCKET_. - -The current implementation of YAP accepts socket -domains `AF_INET` and `AF_UNIX`. -Socket types depend on the -underlying operating system, but at least the following types are -supported: `SOCK_STREAM'` and `SOCK_DGRAM'` (untested in 6.3). - - -*/ - -/** @pred socket(+ _DOMAIN_,- _SOCKET_) - - -Call socket/4 with _TYPE_ bound to `SOCK_STREAM'` and - _PROTOCOL_ bound to `0`. - - -*/ - -/** @pred socket_close(+ _SOCKET_) - - - -Close socket _SOCKET_. Note that sockets used in -`socket_connect` (that is, client sockets) should not be closed with -`socket_close`, as they will be automatically closed when the -corresponding stream is closed with close/1 or `close/2`. - - -*/ - -/** @pred socket_bind(+ _SOCKET_, ? _PORT_) - - - -Interface to system call `bind`, as used for servers: bind socket -to a port. Port information depends on the domain: - -+ 'AF_UNIX'(+ _FILENAME_) (unsupported) -+ 'AF_FILE'(+ _FILENAME_) -use file name _FILENAME_ for UNIX or local sockets. - -+ 'AF_INET'(? _HOST_,?PORT) -If _HOST_ is bound to an atom, bind to host _HOST_, otherwise -if unbound bind to local host ( _HOST_ remains unbound). If port - _PORT_ is bound to an integer, try to bind to the corresponding -port. If variable _PORT_ is unbound allow operating systems to -choose a port number, which is unified with _PORT_. - - - - -*/ - -/** @pred socket_connect(+ _SOCKET_, + _PORT_, - _STREAM_) - - - -Interface to system call `connect`, used for clients: connect -socket _SOCKET_ to _PORT_. The connection results in the -read/write stream _STREAM_. - -Port information depends on the domain: - -+ 'AF_UNIX'(+ _FILENAME_) -+ 'AF_FILE'(+ _FILENAME_) -connect to socket at file _FILENAME_. - -+ 'AF_INET'(+ _HOST_,+ _PORT_) -Connect to socket at host _HOST_ and port _PORT_. - - - -*/ - -/** @pred socket_listen(+ _SOCKET_, + _LENGTH_) - - -Interface to system call `listen`, used for servers to indicate -willingness to wait for connections at socket _SOCKET_. The -integer _LENGTH_ gives the queue limit for incoming connections, -and should be limited to `5` for portable applications. The socket -must be of type `SOCK_STREAM` or `SOCK_SEQPACKET`. - - -*/ - -/** @pred socket_accept(+ _SOCKET_, - _CLIENT_, - _STREAM_) - - -Interface to system call `accept`, used for servers to wait for -connections at socket _SOCKET_. The stream descriptor _STREAM_ -represents the resulting connection. If the socket belongs to the -domain `AF_INET`, _CLIENT_ unifies with an atom containing -the IP address for the client in numbers and dots notation. - - -*/ - -/** @pred socket_accept(+ _SOCKET_, - _STREAM_) - -Accept a connection but do not return client information. - - -*/ - -/** @pred socket_buffering(+ _SOCKET_, - _MODE_, - _OLD_, + _NEW_) - - -Set buffering for _SOCKET_ in `read` or `write` - _MODE_. _OLD_ is unified with the previous status, and _NEW_ -receives the new status which may be one of `unbuf` or -`fullbuf`. - - -*/ - -/** @pred socket_select(+ _SOCKETS_, - _NEWSTREAMS_, + _TIMEOUT_, + _STREAMS_, - _READSTREAMS_) [unsupported in YAP-6.3] - -Interface to system call `select`, used for servers to wait for -connection requests or for data at sockets. The variable - _SOCKETS_ is a list of form _KEY-SOCKET_, where _KEY_ is -an user-defined identifier and _SOCKET_ is a socket descriptor. The -variable _TIMEOUT_ is either `off`, indicating execution will -wait until something is available, or of the form _SEC-USEC_, where - _SEC_ and _USEC_ give the seconds and microseconds before -socket_select/5 returns. The variable _SOCKETS_ is a list of -form _KEY-STREAM_, where _KEY_ is an user-defined identifier -and _STREAM_ is a stream descriptor - -Execution of socket_select/5 unifies _READSTREAMS_ from - _STREAMS_ with readable data, and _NEWSTREAMS_ with a list of -the form _KEY-STREAM_, where _KEY_ was the key for a socket -with pending data, and _STREAM_ the stream descriptor resulting -from accepting the connection. - - -*/ - -/** @pred current_host(? _HOSTNAME_) - -Unify _HOSTNAME_ with an atom representing the fully qualified -hostname for the current host. Also succeeds if _HOSTNAME_ is bound -to the unqualified hostname. - - -*/ - -/** @pred hostname_address(? _HOSTNAME_,? _IP_ADDRESS_) - - _HOSTNAME_ is an host name and _IP_ADDRESS_ its IP -address in number and dots notation. - - - - -*/ - -/** @defgroup Database Using the Clausal Data Base -@ingroup builtins -@{ - -Predicates in YAP may be dynamic or static. By default, when -consulting or reconsulting, predicates are assumed to be static: -execution is faster and the code will probably use less space. -Static predicates impose some restrictions: in general there can be no -addition or removal of clauses for a procedure if it is being used in the -current execution. - -Dynamic predicates allow programmers to change the Clausal Data Base with -the same flexibility as in C-Prolog. With dynamic predicates it is -always possible to add or remove clauses during execution and the -semantics will be the same as for C-Prolog. But the programmer should be -aware of the fact that asserting or retracting are still expensive operations, -and therefore he should try to avoid them whenever possible. - - - - -*/ - -/** @pred dynamic( + _P_ ) - - -Declares predicate _P_ or list of predicates [ _P1_,..., _Pn_] -as a dynamic predicate. _P_ must be written as a predicate indicator, that is in form - _Name/Arity_ or _Module:Name/Arity_. - -~~~~~ -:- dynamic god/1. -~~~~~ - - -a more convenient form can be used: - -~~~~~ -:- dynamic son/3, father/2, mother/2. -~~~~~ - -or, equivalently, - -~~~~~ -:- dynamic [son/3, father/2, mother/2]. -~~~~~ - -Note: - -a predicate is assumed to be dynamic when -asserted before being defined. - - -*/ - -/** @pred dynamic_predicate(+ _P_,+ _Semantics_) - - -Declares predicate _P_ or list of predicates [ _P1_,..., _Pn_] -as a dynamic predicate following either `logical` or -`immediate` semantics. - - -*/ - -/** @pred compile_predicates(: _ListOfNameArity_) - - - -Compile a list of specified dynamic predicates (see dynamic/1 and -assert/1 into normal static predicates. This call tells the -Prolog environment the definition will not change anymore and further -calls to assert/1 or retract/1 on the named predicates -raise a permission error. This predicate is designed to deal with parts -of the program that is generated at runtime but does not change during -the remainder of the program execution. - - - - - */ - -/** @defgroup Modifying_the_Database Modification of the Data Base -@ingroup builtins -@{ - -These predicates can be used either for static or for dynamic -predicates: - - - - -*/ - -/** @pred assert(+ _C_) - - -Same as assertz/1. Adds clause _C_ to the program. If the predicate is undefined, -declare it as dynamic. New code should use assertz/1 for better portability. - -Most Prolog systems only allow asserting clauses for dynamic -predicates. This is also as specified in the ISO standard. YAP allows -asserting clauses for static predicates, as long as the predicate is not -in use and the language flag is cprolog. Note that this feature is -deprecated, if you want to assert clauses for static procedures you -should use assert_static/1. - - -*/ - -/** @pred asserta(+ _C_) is iso - - -Adds clause _C_ to the beginning of the program. If the predicate is -undefined, declare it as dynamic. - - -*/ - -/** @pred assertz(+ _C_) is iso - - -Adds clause _C_ to the end of the program. If the predicate is -undefined, declare it as dynamic. - -Most Prolog systems only allow asserting clauses for dynamic -predicates. This is also as specified in the ISO standard. YAP allows -asserting clauses for static predicates. The current version of YAP -supports this feature, but this feature is deprecated and support may go -away in future versions. - - -*/ - -/** @pred abolish(+ _PredSpec_) is iso - - -Deletes the predicate given by _PredSpec_ from the database. If - _PredSpec_ is an unbound variable, delete all predicates for the -current module. The -specification must include the name and arity, and it may include module -information. Under iso language mode this built-in will only abolish -dynamic procedures. Under other modes it will abolish any procedures. - - -*/ - -/** @pred abolish(+ _P_,+ _N_) - -Deletes the predicate with name _P_ and arity _N_. It will remove -both static and dynamic predicates. - - -*/ - -/** @pred assert_static(: _C_) - - -Adds clause _C_ to a static procedure. Asserting a static clause -for a predicate while choice-points for the predicate are available has -undefined results. - - -*/ - -/** @pred asserta_static(: _C_) - - -Adds clause _C_ to the beginning of a static procedure. - - -*/ - -/** @pred assertz_static(: _C_) - - -Adds clause _C_ to the end of a static procedure. Asserting a -static clause for a predicate while choice-points for the predicate are -available has undefined results. - - - -The following predicates can be used for dynamic predicates and for -static predicates, if source mode was on when they were compiled: - - - - -*/ - -/** @pred clause(+ _H_, _B_) is iso - - -A clause whose head matches _H_ is searched for in the -program. Its head and body are respectively unified with _H_ and - _B_. If the clause is a unit clause, _B_ is unified with - _true_. - -This predicate is applicable to static procedures compiled with -`source` active, and to all dynamic procedures. - - -*/ - -/** @pred clause(+ _H_, _B_,- _R_) - -The same as clause/2, plus _R_ is unified with the -reference to the clause in the database. You can use instance/2 -to access the reference's value. Note that you may not use -erase/1 on the reference on static procedures. - - -*/ - -/** @pred nth_clause(+ _H_, _I_,- _R_) - - -Find the _I_th clause in the predicate defining _H_, and give -a reference to the clause. Alternatively, if the reference _R_ is -given the head _H_ is unified with a description of the predicate -and _I_ is bound to its position. - - - -The following predicates can only be used for dynamic predicates: - - - - -*/ - -/** @pred retract(+ _C_) is iso - - -Erases the first clause in the program that matches _C_. This -predicate may also be used for the static predicates that have been -compiled when the source mode was `on`. For more information on -source/0 ( (see Setting the Compiler)). - - -*/ - -/** @pred retractall(+ _G_) is iso - - -Retract all the clauses whose head matches the goal _G_. Goal - _G_ must be a call to a dynamic predicate. - - - - - */ - -/** @defgroup Looking_at_the_Database Looking at the Data Base -@ingroup builtins -@{ - - - - -*/ - -/** @pred listing - - -Lists in the current output stream all the clauses for which source code -is available (these include all clauses for dynamic predicates and -clauses for static predicates compiled when source mode was `on`). - - -*/ - -/** @pred listing(+ _P_) - -Lists predicate _P_ if its source code is available. - - -*/ - -/** @pred portray_clause(+ _C_) - - -Write clause _C_ as if written by listing/0. - - -*/ - -/** @pred portray_clause(+ _S_,+ _C_) - -Write clause _C_ on stream _S_ as if written by listing/0. - - -*/ - -/** @pred current_atom( _A_) - - -Checks whether _A_ is a currently defined atom. It is used to find all -currently defined atoms by backtracking. - - -*/ - -/** @pred current_predicate( _F_) is iso - - - _F_ is the predicate indicator for a currently defined user or -library predicate. _F_ is of the form _Na/Ar_, where the atom - _Na_ is the name of the predicate, and _Ar_ its arity. - - -*/ - -/** @pred current_predicate( _A_, _P_) - -Defines the relation: _P_ is a currently defined predicate whose -name is the atom _A_. - - -*/ - -/** @pred system_predicate( _A_, _P_) - - -Defines the relation: _P_ is a built-in predicate whose name -is the atom _A_. - - -*/ - -/** @pred predicate_property( _P_, _Prop_) is iso - - -For the predicates obeying the specification _P_ unify _Prop_ -with a property of _P_. These properties may be: - -+ `built_in ` -true for built-in predicates, - -+ `dynamic` -true if the predicate is dynamic - -+ `static ` -true if the predicate is static - -+ `meta_predicate( _M_) ` -true if the predicate has a meta_predicate declaration _M_. - -+ `multifile ` -true if the predicate was declared to be multifile - -+ `imported_from( _Mod_) ` -true if the predicate was imported from module _Mod_. - -+ `exported ` -true if the predicate is exported in the current module. - -+ `public` -true if the predicate is public; note that all dynamic predicates are -public. - -+ `tabled ` -true if the predicate is tabled; note that only static predicates can -be tabled in YAP. - -+ `source (predicate_property flag) ` -true if source for the predicate is available. - -+ `number_of_clauses( _ClauseCount_) ` -Number of clauses in the predicate definition. Always one if external -or built-in. - - - -*/ - -/** @pred predicate_statistics( _P_, _NCls_, _Sz_, _IndexSz_) - - -Given predicate _P_, _NCls_ is the number of clauses for - _P_, _Sz_ is the amount of space taken to store those clauses -(in bytes), and _IndexSz_ is the amount of space required to store -indices to those clauses (in bytes). - - -*/ - -/** @pred predicate_erased_statistics( _P_, _NCls_, _Sz_, _IndexSz_) - - -Given predicate _P_, _NCls_ is the number of erased clauses for - _P_ that could not be discarded yet, _Sz_ is the amount of space -taken to store those clauses (in bytes), and _IndexSz_ is the amount -of space required to store indices to those clauses (in bytes). - - - - - */ - -/** @defgroup Database_References Using Data Base References -@ingroup builtins -@{ - -Data Base references are a fast way of accessing terms. The predicates -erase/1 and `instance/1` also apply to these references and may -sometimes be used instead of retract/1 and clause/2. - - - - -*/ - -/** @pred assert(+ _C_,- _R_) - -The same as `assert(C)` ( (see Modifying the Database)) but -unifies _R_ with the database reference that identifies the new -clause, in a one-to-one way. Note that `asserta/2` only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - - -*/ - -/** @pred asserta(+ _C_,- _R_) - -The same as `asserta(C)` but unifying _R_ with -the database reference that identifies the new clause, in a -one-to-one way. Note that `asserta/2` only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - - -*/ - -/** @pred assertz(+ _C_,- _R_) - -The same as `assertz(C)` but unifying _R_ with -the database reference that identifies the new clause, in a -one-to-one way. Note that `asserta/2` only works for dynamic -predicates. If the predicate is undefined, it will automatically be -declared dynamic. - - -*/ - -/** @pred retract(+ _C_,- _R_) - -Erases from the program the clause _C_ whose -database reference is _R_. The predicate must be dynamic. - - - - - */ - -/** @defgroup Internal_Database Internal Data Base -@ingroup builtins -@{ - -Some programs need global information for, e.g. counting or collecting -data obtained by backtracking. As a rule, to keep this information, the -internal data base should be used instead of asserting and retracting -clauses (as most novice programmers do), . -In YAP (as in some other Prolog systems) the internal data base (i.d.b. -for short) is faster, needs less space and provides a better insulation of -program and data than using asserted/retracted clauses. -The i.d.b. is implemented as a set of terms, accessed by keys that -unlikely what happens in (non-Prolog) data bases are not part of the -term. Under each key a list of terms is kept. References are provided so that -terms can be identified: each term in the i.d.b. has a unique reference -(references are also available for clauses of dynamic predicates). - -There is a strong analogy between the i.d.b. and the way dynamic -predicates are stored. In fact, the main i.d.b. predicates might be -implemented using dynamic predicates: - -~~~~~ -recorda(X,T,R) :- asserta(idb(X,T),R). -recordz(X,T,R) :- assertz(idb(X,T),R). -recorded(X,T,R) :- clause(idb(X,T),R). -~~~~~ -We can take advantage of this, the other way around, as it is quite -easy to write a simple Prolog interpreter, using the i.d.b.: - -~~~~~ -asserta(G) :- recorda(interpreter,G,_). -assertz(G) :- recordz(interpreter,G,_). -retract(G) :- recorded(interpreter,G,R), !, erase(R). -call(V) :- var(V), !, fail. -call((H :- B)) :- !, recorded(interpreter,(H :- B),_), call(B). -call(G) :- recorded(interpreter,G,_). -~~~~~ -In YAP, much attention has been given to the implementation of the -i.d.b., especially to the problem of accelerating the access to terms kept in -a large list under the same key. Besides using the key, YAP uses an internal -lookup function, transparent to the user, to find only the terms that might -unify. For instance, in a data base containing the terms - -~~~~~ -b -b(a) -c(d) -e(g) -b(X) -e(h) -~~~~~ - -stored under the key k/1, when executing the query - -~~~~~ -:- recorded(k(_),c(_),R). -~~~~~ - -`recorded` would proceed directly to the third term, spending almost the -time as if `a(X)` or `b(X)` was being searched. -The lookup function uses the functor of the term, and its first three -arguments (when they exist). So, `recorded(k(_),e(h),_)` would go -directly to the last term, while `recorded(k(_),e(_),_)` would find -first the fourth term, and then, after backtracking, the last one. - -This mechanism may be useful to implement a sort of hierarchy, where -the functors of the terms (and eventually the first arguments) work as -secondary keys. - -In the YAP's i.d.b. an optimized representation is used for -terms without free variables. This results in a faster retrieval of terms -and better space usage. Whenever possible, avoid variables in terms in terms stored in the i.d.b. - - - -*/ - -/** @pred recorda(+ _K_, _T_,- _R_) - - -Makes term _T_ the first record under key _K_ and unifies _R_ -with its reference. - - -*/ - -/** @pred recordz(+ _K_, _T_,- _R_) - - -Makes term _T_ the last record under key _K_ and unifies _R_ -with its reference. - - -*/ - -/** @pred recorda_at(+ _R0_, _T_,- _R_) - - -Makes term _T_ the record preceding record with reference - _R0_, and unifies _R_ with its reference. - - -*/ - -/** @pred recordz_at(+ _R0_, _T_,- _R_) - - -Makes term _T_ the record following record with reference - _R0_, and unifies _R_ with its reference. - - -*/ - -/** @pred recordaifnot(+ _K_, _T_,- _R_) - - -If a term equal to _T_ up to variable renaming is stored under key - _K_ fail. Otherwise, make term _T_ the first record under key - _K_ and unify _R_ with its reference. - - -*/ - -/** @pred recordzifnot(+ _K_, _T_,- _R_) - - -If a term equal to _T_ up to variable renaming is stored under key - _K_ fail. Otherwise, make term _T_ the first record under key - _K_ and unify _R_ with its reference. - -This predicate is YAP specific. - - -*/ - -/** @pred recorded(+ _K_, _T_, _R_) - - -Searches in the internal database under the key _K_, a term that -unifies with _T_ and whose reference matches _R_. This -built-in may be used in one of two ways: - -+ _K_ may be given, in this case the built-in will return all -elements of the internal data-base that match the key. -+ _R_ may be given, if so returning the key and element that -match the reference. - - - -*/ - -/** @pred erase(+ _R_) - - -The term referred to by _R_ is erased from the internal database. If -reference _R_ does not exist in the database, `erase` just fails. - - -*/ - -/** @pred erased(+ _R_) - - -Succeeds if the object whose database reference is _R_ has been -erased. - - -*/ - -/** @pred instance(+ _R_,- _T_) - - -If _R_ refers to a clause or a recorded term, _T_ is unified -with its most general instance. If _R_ refers to an unit clause - _C_, then _T_ is unified with ` _C_ :- true`. When - _R_ is not a reference to an existing clause or to a recorded term, -this goal fails. - - -*/ - -/** @pred eraseall(+ _K_) - - -All terms belonging to the key `K` are erased from the internal -database. The predicate always succeeds. - - -*/ - -/** @pred current_key(? _A_,? _K_) - - -Defines the relation: _K_ is a currently defined database key whose -name is the atom _A_. It can be used to generate all the keys for -the internal data-base. - - -*/ - -/** @pred nth_instance(? _Key_,? _Index_,? _R_) - - -Fetches the _Index_nth entry in the internal database under the key - _Key_. Entries are numbered from one. If the key _Key_ or the - _Index_ are bound, a reference is unified with _R_. Otherwise, -the reference _R_ must be given, and YAP will find -the matching key and index. - - -*/ - -/** @pred nth_instance(? _Key_,? _Index_, _T_,? _R_) - -Fetches the _Index_nth entry in the internal database under the key - _Key_. Entries are numbered from one. If the key _Key_ or the - _Index_ are bound, a reference is unified with _R_. Otherwise, -the reference _R_ must be given, and YAP will find -the matching key and index. - - -*/ - -/** @pred key_statistics(+ _K_,- _Entries_,- _Size_,- _IndexSize_) - - -Returns several statistics for a key _K_. Currently, it says how -many entries we have for that key, _Entries_, what is the -total size spent on entries, _Size_, and what is the amount of -space spent in indices. - - -*/ - -/** @pred key_statistics(+ _K_,- _Entries_,- _TotalSize_) - -Returns several statistics for a key _K_. Currently, it says how -many entries we have for that key, _Entries_, what is the -total size spent on this key. - - -*/ - -/** @pred get_value(+ _A_,- _V_) - - -In YAP, atoms can be associated with constants. If one such -association exists for atom _A_, unify the second argument with the -constant. Otherwise, unify _V_ with `[]`. - -This predicate is YAP specific. - - -*/ - -/** @pred set_value(+ _A_,+ _C_) - - -Associate atom _A_ with constant _C_. - -The `set_value` and `get_value` built-ins give a fast alternative to -the internal data-base. This is a simple form of implementing a global -counter. - -~~~~~ - read_and_increment_counter(Value) :- - get_value(counter, Value), - Value1 is Value+1, - set_value(counter, Value1). -~~~~~ -This predicate is YAP specific. - - - - - -*/ - -/** @defgroup BlackBoard The Blackboard -@ingroup builtins -@{ - -YAP implements a blackboard in the style of the SICStus Prolog -blackboard. The blackboard uses the same underlying mechanism as the -internal data-base but has several important differences: - -+ It is module aware, in contrast to the internal data-base. -+ Keys can only be atoms or integers, and not compound terms. -+ A single term can be stored per key. -+ An atomic update operation is provided; this is useful for -parallelism. - - - - -*/ - -/** @pred bb_put(+ _Key_,? _Term_) - - -Store term table _Term_ in the blackboard under key _Key_. If a -previous term was stored under key _Key_ it is simply forgotten. - - -*/ - -/** @pred bb_get(+ _Key_,? _Term_) - - -Unify _Term_ with a term stored in the blackboard under key - _Key_, or fail silently if no such term exists. - - -*/ - -/** @pred bb_delete(+ _Key_,? _Term_) - - -Delete any term stored in the blackboard under key _Key_ and unify -it with _Term_. Fail silently if no such term exists. - - -*/ - -/** @pred bb_update(+ _Key_,? _Term_,? _New_) - - -Atomically unify a term stored in the blackboard under key _Key_ -with _Term_, and if the unification succeeds replace it by - _New_. Fail silently if no such term exists or if unification fails. - - - - - */ - -/** @defgroup Sets Collecting Solutions to a Goal -@ingroup builtins -@{ - -When there are several solutions to a goal, if the user wants to collect all -the solutions he may be led to use the data base, because backtracking will -forget previous solutions. - -YAP allows the programmer to choose from several system -predicates instead of writing his own routines. findall/3 gives you -the fastest, but crudest solution. The other built-in predicates -post-process the result of the query in several different ways: - - - - -*/ - -/** @pred findall( _T_,+ _G_,- _L_) is iso - - -Unifies _L_ with a list that contains all the instantiations of the -term _T_ satisfying the goal _G_. - -With the following program: - -~~~~~ -a(2,1). -a(1,1). -a(2,2). -~~~~~ -the answer to the query - -~~~~~ -findall(X,a(X,Y),L). -~~~~~ -would be: - -~~~~~ -X = _32 -Y = _33 -L = [2,1,2]; -no -~~~~~ - - -*/ - -/** @pred findall( _T_,+ _G_,+ _L_,- _L0_) - -Similar to findall/3, but appends all answers to list _L0_. - - -*/ - -/** @pred all( _T_,+ _G_,- _L_) - - -Similar to `findall( _T_, _G_, _L_)` but eliminate -repeated elements. Thus, assuming the same clauses as in the above -example, the reply to the query - -~~~~~ -all(X,a(X,Y),L). -~~~~~ -would be: - -~~~~~ -X = _32 -Y = _33 -L = [2,1]; -no -~~~~~ - -Note that all/3 will fail if no answers are found. - - -*/ - -/** @pred bagof( _T_,+ _G_,- _L_) is iso - - -For each set of possible instances of the free variables occurring in - _G_ but not in _T_, generates the list _L_ of the instances of - _T_ satisfying _G_. Again, assuming the same clauses as in the -examples above, the reply to the query - -~~~~~ -bagof(X,a(X,Y),L). - -would be: -X = _32 -Y = 1 -L = [2,1]; -X = _32 -Y = 2 -L = [2]; -no -~~~~~ - - -*/ - -/** @pred setof( _X_,+ _P_,- _B_) is iso - - -Similar to `bagof( _T_, _G_, _L_)` but sorts list - _L_ and keeping only one copy of each element. Again, assuming the -same clauses as in the examples above, the reply to the query - -~~~~~ -setof(X,a(X,Y),L). -~~~~~ -would be: - -~~~~~ -X = _32 -Y = 1 -L = [1,2]; -X = _32 -Y = 2 -L = [2]; -no -~~~~~ - - - - - */ - -/** @defgroup Grammars Grammar Rules -@ingroup builtins -@{ - -Grammar rules in Prolog are both a convenient way to express definite -clause grammars and an extension of the well known context-free grammars. - -A grammar rule is of the form: - -~~~~~ -head --> body -~~~~~ -where both \a head and \a body are sequences of one or more items -linked by the standard conjunction operator `,`. - -Items can be: - -+ -a non-terminal symbol may be either a complex term or an atom. -+ -a terminal symbol may be any Prolog symbol. Terminals are -written as Prolog lists. -+ -an empty body is written as the empty list `[ ]`. -+ -extra conditions may be inserted as Prolog procedure calls, by being -written inside curly brackets `{` and `}`. -+ -the left side of a rule consists of a nonterminal and an optional list -of terminals. -+ -alternatives may be stated in the right-hand side of the rule by using -the disjunction operator `;`. -+ -the cut and conditional symbol (`->`) may be inserted in the -right hand side of a grammar rule - - -Grammar related built-in predicates: - - - - -*/ - -/** @pred expand_term( _T_,- _X_) - - - -This predicate is used by YAP for preprocessing each top level -term read when consulting a file and before asserting or executing it. -It rewrites a term _T_ to a term _X_ according to the following -rules: first try term_expansion/2 in the current module, and then try to use the user defined predicate -`user:term_expansion/2`. If this call fails then the translating process -for DCG rules is applied, together with the arithmetic optimizer -whenever the compilation of arithmetic expressions is in progress. - - -*/ - -/** @pred _CurrentModule_:term_expansion( _T_,- _X_), user:term_expansion( _T_,- _X_) - - -This user-defined predicate is called by `expand_term/3` to -preprocess all terms read when consulting a file. If it succeeds: - -+ -If _X_ is of the form `:- G` or `?- G`, it is processed as -a directive. -+ -If _X_ is of the form `$source_location`( _File_, _Line_): _Clause_` it is processed as if from `File` and line `Line`. - -+ -If _X_ is a list, all terms of the list are asserted or processed -as directives. -+ The term _X_ is asserted instead of _T_. - - - -*/ - -/** @pred _CurrentModule_:goal_expansion(+ _G_,+ _M_,- _NG_), user:goal_expansion(+ _G_,+ _M_,- _NG_) - - -YAP now supports goal_expansion/3. This is an user-defined -procedure that is called after term expansion when compiling or -asserting goals for each sub-goal in a clause. The first argument is -bound to the goal and the second to the module under which the goal - _G_ will execute. If goal_expansion/3 succeeds the new -sub-goal _NG_ will replace _G_ and will be processed in the same -way. If goal_expansion/3 fails the system will use the default -rules. - - -*/ - -/** @pred phrase(+ _P_, _L_, _R_) - - -This predicate succeeds when the difference list ` _L_- _R_` -is a phrase of type _P_. - - -*/ - -/** @pred phrase(+ _P_, _L_) - -This predicate succeeds when _L_ is a phrase of type _P_. The -same as `phrase(P,L,[])`. - -Both this predicate and the previous are used as a convenient way to -start execution of grammar rules. - - -*/ - -/** @pred `C`( _S1_, _T_, _S2_) - - -This predicate is used by the grammar rules compiler and is defined as -`C`([H|T],H,T)`. - - - - - */ - -/** @defgroup OS Access to Operating System Functionality -@ingroup builtins -@{ - -The following built-in predicates allow access to underlying -Operating System functionality: - - - - -*/ - -/** @pred cd(+ _D_) - - -Changes the current directory (on UNIX environments). - - -*/ - -/** @pred cd - -Changes the current directory (on UNIX environments) to the user's home directory. - - -*/ - -/** @pred environ(+ _E_,- _S_) - - - - - -Given an environment variable _E_ this predicate unifies the second argument _S_ with its value. - - -*/ - -/** @pred getcwd(- _D_) - - -Unify the current directory, represented as an atom, with the argument - _D_. - - -*/ - -/** @pred pwd - - -Prints the current directory. - - -*/ - -/** @pred ls - - -Prints a list of all files in the current directory. - - -*/ - -/** @pred putenv(+ _E_,+ _S_) - - -Set environment variable _E_ to the value _S_. If the -environment variable _E_ does not exist, create a new one. Both the -environment variable and the value must be atoms. - - -*/ - -/** @pred rename(+ _F_,+ _G_) - - -Renames file _F_ to _G_. - - -*/ - -/** @pred sh - - -Creates a new shell interaction. - - -*/ - -/** @pred system(+ _S_) - - -Passes command _S_ to the Bourne shell (on UNIX environments) or the -current command interpreter in WIN32 environments. - - -*/ - -/** @pred unix(+ _S_) - - -Access to Unix-like functionality: - -+ argv/1 -Return a list of arguments to the program. These are the arguments that -follow a `--`, as in the usual Unix convention. -+ cd/0 -Change to home directory. -+ cd/1 -Change to given directory. Acceptable directory names are strings or -atoms. -+ environ/2 -If the first argument is an atom, unify the second argument with the -value of the corresponding environment variable. -+ getcwd/1 -Unify the first argument with an atom representing the current directory. -+ putenv/2 -Set environment variable _E_ to the value _S_. If the -environment variable _E_ does not exist, create a new one. Both the -environment variable and the value must be atoms. -+ shell/1 -Execute command under current shell. Acceptable commands are strings or -atoms. -+ system/1 -Execute command with `/bin/sh`. Acceptable commands are strings or -atoms. -+ shell/0 -Execute a new shell. - - - -*/ - -/** @pred working_directory(- _CurDir_,? _NextDir_) - - -Fetch the current directory at _CurDir_. If _NextDir_ is bound -to an atom, make its value the current working directory. - - -*/ - -/** @pred alarm(+ _Seconds_,+ _Callable_,+ _OldAlarm_) - - -Arranges for YAP to be interrupted in _Seconds_ seconds, or in -[ _Seconds_| _MicroSeconds_]. When interrupted, YAP will execute - _Callable_ and then return to the previous execution. If - _Seconds_ is `0`, no new alarm is scheduled. In any event, -any previously set alarm is canceled. - -The variable _OldAlarm_ unifies with the number of seconds remaining -until any previously scheduled alarm was due to be delivered, or with -`0` if there was no previously scheduled alarm. - -Note that execution of _Callable_ will wait if YAP is -executing built-in predicates, such as Input/Output operations. - -The next example shows how _alarm/3_ can be used to implement a -simple clock: - -~~~~~ -loop :- loop. - -ticker :- write('.'), flush_output, - get_value(tick, yes), - alarm(1,ticker,_). - -:- set_value(tick, yes), alarm(1,ticker,_), loop. -~~~~~ - -The clock, `ticker`, writes a dot and then checks the flag -`tick` to see whether it can continue ticking. If so, it calls -itself again. Note that there is no guarantee that the each dot -corresponds a second: for instance, if the YAP is waiting for -user input, `ticker` will wait until the user types the entry in. - -The next example shows how alarm/3 can be used to guarantee that -a certain procedure does not take longer than a certain amount of time: - -~~~~~ -loop :- loop. - -:- catch((alarm(10, throw(ball), _),loop), - ball, - format('Quota exhausted.~n',[])). -~~~~~ -In this case after `10` seconds our `loop` is interrupted, -`ball` is thrown, and the handler writes `Quota exhausted`. -Execution then continues from the handler. - -Note that in this case `loop/0` always executes until the alarm is -sent. Often, the code you are executing succeeds or fails before the -alarm is actually delivered. In this case, you probably want to disable -the alarm when you leave the procedure. The next procedure does exactly so: - -~~~~~ -once_with_alarm(Time,Goal,DoOnAlarm) :- - catch(execute_once_with_alarm(Time, Goal), alarm, DoOnAlarm). - -execute_once_with_alarm(Time, Goal) :- - alarm(Time, alarm, _), - ( call(Goal) -> alarm(0, alarm, _) ; alarm(0, alarm, _), fail). -~~~~~ - -The procedure `once_with_alarm/3` has three arguments: -the _Time_ to wait before the alarm is -sent; the _Goal_ to execute; and the goal _DoOnAlarm_ to execute -if the alarm is sent. It uses catch/3 to handle the case the -`alarm` is sent. Then it starts the alarm, calls the goal - _Goal_, and disables the alarm on success or failure. - - -*/ - -/** @pred on_signal(+ _Signal_,? _OldAction_,+ _Callable_) - - -Set the interrupt handler for soft interrupt _Signal_ to be - _Callable_. _OldAction_ is unified with the previous handler. - -Only a subset of the software interrupts (signals) can have their -handlers manipulated through on_signal/3. -Their POSIX names, YAP names and default behavior is given below. -The "YAP name" of the signal is the atom that is associated with -each signal, and should be used as the first argument to -on_signal/3. It is chosen so that it matches the signal's POSIX -name. - -on_signal/3 succeeds, unless when called with an invalid -signal name or one that is not supported on this platform. No checks -are made on the handler provided by the user. - -+ sig_up (Hangup) -SIGHUP in Unix/Linux; Reconsult the initialization files -~/.yaprc, ~/.prologrc and ~/prolog.ini. -+ sig_usr1 and sig_usr2 (User signals) -SIGUSR1 and SIGUSR2 in Unix/Linux; Print a message and halt. - - -A special case is made, where if _Callable_ is bound to -`default`, then the default handler is restored for that signal. - -A call in the form `on_signal( _S_, _H_, _H_)` can be used -to retrieve a signal's current handler without changing it. - -It must be noted that although a signal can be received at all times, -the handler is not executed while YAP is waiting for a query at the -prompt. The signal will be, however, registered and dealt with as soon -as the user makes a query. - -Please also note, that neither POSIX Operating Systems nor YAP guarantee -that the order of delivery and handling is going to correspond with the -order of dispatch. - - - - - */ - -/** @defgroup Term_Modification Term Modification -@ingroup builtins -@{ - -It is sometimes useful to change the value of instantiated -variables. Although, this is against the spirit of logic programming, it -is sometimes useful. As in other Prolog systems, YAP has -several primitives that allow updating Prolog terms. Note that these -primitives are also backtrackable. - -The `setarg/3` primitive allows updating any argument of a Prolog -compound terms. The `mutable` family of predicates provides -mutable variables. They should be used instead of `setarg/3`, -as they allow the encapsulation of accesses to updatable -variables. Their implementation can also be more efficient for long -deterministic computations. - - - -*/ - -/** @pred setarg(+ _I_,+ _S_,? _T_) - - -Set the value of the _I_th argument of term _S_ to term _T_. - - -*/ - -/** @pred create_mutable(+ _D_,- _M_) - - -Create new mutable variable _M_ with initial value _D_. - - -*/ - -/** @pred is_mutable(? _D_) - - -Holds if _D_ is a mutable term. - - -*/ - -/** @pred get_mutable(? _D_,+ _M_) - - -Unify the current value of mutable term _M_ with term _D_. - - -*/ - -/** @pred update_mutable(+ _D_,+ _M_) - - -Set the current value of mutable term _M_ to term _D_. - - - - */ - -/** @defgroup Global_Variables Global Variables -@ingroup builtins -@{ - -Global variables are associations between names (atoms) and -terms. They differ in various ways from storing information using -assert/1 or recorda/3. - -+ The value lives on the Prolog (global) stack. This implies that -lookup time is independent from the size of the term. This is -particularly interesting for large data structures such as parsed XML -documents or the CHR global constraint store. - -+ They support both global assignment using nb_setval/2 and -backtrackable assignment using b_setval/2. - -+ Only one value (which can be an arbitrary complex Prolog term) -can be associated to a variable at a time. - -+ Their value cannot be shared among threads. Each thread has its own -namespace and values for global variables. - - -Currently global variables are scoped globally. We may consider module -scoping in future versions. Both b_setval/2 and -nb_setval/2 implicitly create a variable if the referenced name -does not already refer to a variable. - -Global variables may be initialised from directives to make them -available during the program lifetime, but some considerations are -necessary for saved-states and threads. Saved-states to not store -global variables, which implies they have to be declared with -initialization/1 to recreate them after loading the saved -state. Each thread has its own set of global variables, starting with -an empty set. Using `thread_initialization/1` to define a global -variable it will be defined, restored after reloading a saved state -and created in all threads that are created after the -registration. Finally, global variables can be initialised using the -exception hook called exception/3. The latter technique is used -by CHR. - - - -*/ - -/** @pred b_setval(+ _Name_, + _Value_) - - -Associate the term _Value_ with the atom _Name_ or replaces -the currently associated value with _Value_. If _Name_ does -not refer to an existing global variable a variable with initial value -[] is created (the empty list). On backtracking the assignment is -reversed. - - -*/ - -/** @pred b_getval(+ _Name_, - _Value_) - - -Get the value associated with the global variable _Name_ and unify -it with _Value_. Note that this unification may further -instantiate the value of the global variable. If this is undesirable -the normal precautions (double negation or copy_term/2) must be -taken. The b_getval/2 predicate generates errors if _Name_ is not -an atom or the requested variable does not exist. - -Notice that for compatibility with other systems _Name_ must be already associated with a term: otherwise the system will generate an error. - - -*/ - -/** @pred nb_setval(+ _Name_, + _Value_) - - -Associates a copy of _Value_ created with duplicate_term/2 with -the atom _Name_. Note that this can be used to set an initial -value other than `[]` prior to backtrackable assignment. - - -*/ - -/** @pred nb_getval(+ _Name_, - _Value_) - - -The nb_getval/2 predicate is a synonym for b_getval/2, -introduced for compatibility and symmetry. As most scenarios will use -a particular global variable either using non-backtrackable or -backtrackable assignment, using nb_getval/2 can be used to -document that the variable is used non-backtrackable. - - -*/ - -/** @pred nb_linkval(+ _Name_, + _Value_) - - -Associates the term _Value_ with the atom _Name_ without -copying it. This is a fast special-purpose variation of nb_setval/2 -intended for expert users only because the semantics on backtracking -to a point before creating the link are poorly defined for compound -terms. The principal term is always left untouched, but backtracking -behaviour on arguments is undone if the original assignment was -trailed and left alone otherwise, which implies that the history that -created the term affects the behaviour on backtracking. Please -consider the following example: - -~~~~~ -demo_nb_linkval :- - T = nice(N), - ( N = world, - nb_linkval(myvar, T), - fail - ; nb_getval(myvar, V), - writeln(V) - ). -~~~~~ - - -*/ - -/** @pred nb_set_shared_val(+ _Name_, + _Value_) - - -Associates the term _Value_ with the atom _Name_, but sharing -non-backtrackable terms. This may be useful if you want to rewrite a -global variable so that the new copy will survive backtracking, but -you want to share structure with the previous term. - -The next example shows the differences between the three built-ins: - -~~~~~ -?- nb_setval(a,a(_)),nb_getval(a,A),nb_setval(b,t(C,A)),nb_getval(b,B). -A = a(_A), -B = t(_B,a(_C)) ? - -?- nb_setval(a,a(_)),nb_getval(a,A),nb_set_shared_val(b,t(C,A)),nb_getval(b,B). - -?- nb_setval(a,a(_)),nb_getval(a,A),nb_linkval(b,t(C,A)),nb_getval(b,B). -A = a(_A), -B = t(C,a(_A)) ? -~~~~~ - - -*/ - -/** @pred nb_setarg(+{Arg], + _Term_, + _Value_) - - - -Assigns the _Arg_-th argument of the compound term _Term_ with -the given _Value_ as setarg/3, but on backtracking the assignment -is not reversed. If _Term_ is not atomic, it is duplicated using -duplicate_term/2. This predicate uses the same technique as -nb_setval/2. We therefore refer to the description of -nb_setval/2 for details on non-backtrackable assignment of -terms. This predicate is compatible to GNU-Prolog -`setarg(A,T,V,false)`, removing the type-restriction on - _Value_. See also nb_linkarg/3. Below is an example for -counting the number of solutions of a goal. Note that this -implementation is thread-safe, reentrant and capable of handling -exceptions. Realising these features with a traditional implementation -based on assert/retract or flag/3 is much more complicated. - -~~~~~ - succeeds_n_times(Goal, Times) :- - Counter = counter(0), - ( Goal, - arg(1, Counter, N0), - N is N0 + 1, - nb_setarg(1, Counter, N), - fail - ; arg(1, Counter, Times) - ). -~~~~~ - - -*/ - -/** @pred nb_set_shared_arg(+ _Arg_, + _Term_, + _Value_) - - - -As nb_setarg/3, but like nb_linkval/2 it does not -duplicate the global sub-terms in _Value_. Use with extreme care -and consult the documentation of nb_linkval/2 before use. - - -*/ - -/** @pred nb_linkarg(+ _Arg_, + _Term_, + _Value_) - - - -As nb_setarg/3, but like nb_linkval/2 it does not -duplicate _Value_. Use with extreme care and consult the -documentation of nb_linkval/2 before use. - - -*/ - -/** @pred nb_current(? _Name_, ? _Value_) - - -Enumerate all defined variables with their value. The order of -enumeration is undefined. - - -*/ - -/** @pred nb_delete(+ _Name_) - - -Delete the named global variable. - - -Global variables have been introduced by various Prolog -implementations recently. We follow the implementation of them in -SWI-Prolog, itself based on hProlog by Bart Demoen. - -GNU-Prolog provides a rich set of global variables, including -arrays. Arrays can be implemented easily in YAP and SWI-Prolog using -functor/3 and `setarg/3` due to the unrestricted arity of -compound terms. - - - */ - -/** @defgroup Profiling Profiling Prolog Programs -@ingroup builtins -@{ - -YAP includes two profilers. The count profiler keeps information on the -number of times a predicate was called. This information can be used to -detect what are the most commonly called predicates in the program. The -count profiler can be compiled by setting YAP's flag profiling -to `on`. The time-profiler is a `gprof` profiler, and counts -how many ticks are being spent on specific predicates, or on other -system functions such as internal data-base accesses or garbage collects. - -The YAP profiling sub-system is currently under -development. Functionality for this sub-system will increase with newer -implementation. - - - */ - -/** @defgroup The_Count_Profiler The Count Profiler -@ingroup builtins -@{ - - *Notes:* - -The count profiler works by incrementing counters at procedure entry or -backtracking. It provides exact information: - -+ Profiling works for both static and dynamic predicates. -+ Currently only information on entries and retries to a predicate -are maintained. This may change in the future. -+ As an example, the following user-level program gives a list of -the most often called procedures in a program. The procedure -`list_profile` shows all procedures, irrespective of module, and -the procedure `list_profile/1` shows the procedures being used in -a specific module. - -~~~~~ -list_profile :- - % get number of calls for each profiled procedure - setof(D-[M:P|D1],(current_module(M),profile_data(M:P,calls,D),profile_data(M:P,retries,D1)),LP), - % output so that the most often called - % predicates will come last: - write_profile_data(LP). - -list_profile(Module) :- - % get number of calls for each profiled procedure - setof(D-[Module:P|D1],(profile_data(Module:P,calls,D),profile_data(Module:P,retries,D1)),LP), - % output so that the most often called - % predicates will come last: - write_profile_data(LP). - -write_profile_data([]). -write_profile_data([D-[M:P|R]|SLP]) :- - % swap the two calls if you want the most often - % called predicates first. - format('~a:~w: ~32+~t~d~12+~t~d~12+~n', [M,P,D,R]), - write_profile_data(SLP). -~~~~~ - - -These are the current predicates to access and clear profiling data: - - - -*/ - -/** @pred profile_data(? _Na/Ar_, ? _Parameter_, - _Data_) - - -Give current profile data on _Parameter_ for a predicate described -by the predicate indicator _Na/Ar_. If any of _Na/Ar_ or - _Parameter_ are unbound, backtrack through all profiled predicates -or stored parameters. Current parameters are: - -+ calls -Number of times a procedure was called. - -+ retries -Number of times a call to the procedure was backtracked to and retried. - - -+ profile_reset - - -Reset all profiling information. - - - - - */ - -/** @defgroup Tick_Profiler Tick Profiler -@ingroup builtins -@{ - -The tick profiler works by interrupting the Prolog code every so often -and checking at each point the code was. The profiler must be able to -retrace the state of the abstract machine at every moment. The major -advantage of this approach is that it gives the actual amount of time -being spent per procedure, or whether garbage collection dominates -execution time. The major drawback is that tracking down the state of -the abstract machine may take significant time, and in the worst case -may slow down the whole execution. - -The following procedures are available: - -+ profinit - - -Initialise the data-structures for the profiler. Unnecessary for -dynamic profiler. - -+ profon - - -Start profiling. - -+ profoff - - -Stop profiling. - - -*/ - -/** @pred showprofres - - -Show profiling info. - - -*/ - -/** @pred showprofres( _N_) - -Show profiling info for the top-most _N_ predicates. - - - -The showprofres/0 and `showprofres/1` predicates call a user-defined multifile hook predicate, `user:prolog_predicate_name/2`, that can be used for converting a possibly explicitly-qualified callable term into an atom that will used when printing the profiling information. - - - */ - -/** @defgroup Call_Counting Counting Calls -@ingroup builtins -@{ - -Predicates compiled with YAP's flag call_counting set to -`on` update counters on the numbers of calls and of -retries. Counters are actually decreasing counters, so that they can be -used as timers. Three counters are available: - -+ `calls`: number of predicate calls since execution started or since -system was reset; -+ `retries`: number of retries for predicates called since -execution started or since counters were reset; -+ `calls_and_retries`: count both on predicate calls and -retries. - -These counters can be used to find out how many calls a certain -goal takes to execute. They can also be used as timers. - -The code for the call counters piggybacks on the profiling -code. Therefore, activating the call counters also activates the profiling -counters. - -These are the predicates that access and manipulate the call counters: - - - -*/ - -/** @pred call_count_data(- _Calls_, - _Retries_, - _CallsAndRetries_) - - -Give current call count data. The first argument gives the current value -for the _Calls_ counter, next the _Retries_ counter, and last -the _CallsAndRetries_ counter. - -*/ - -/** @pred call_count_reset - - -Reset call count counters. All timers are also reset. - -*/ - -/** @pred call_count(? _CallsMax_, ? _RetriesMax_, ? _CallsAndRetriesMax_) - - -Set call counters as timers. YAP will generate an exception -if one of the instantiated call counters decreases to 0: - -+ _CallsMax_ - - throw the exception `call_counter` when the -counter `calls` reaches 0; - -+ _RetriesMax_ - - throw the exception `retry_counter` when the -counter `retries` reaches 0; - -+ _CallsAndRetriesMax_ - - throw the exception -`call_and_retry_counter` when the counter `calls_and_retries` -reaches 0. - - YAP will ignore counters that are called with unbound arguments. - -Next, we show a simple example of how to use call counters: - -~~~~~{.prolog} - ?- yap_flag(call_counting,on), [-user]. l :- l. end_of_file. yap_flag(call_counting,off). - -yes - -yes - ?- catch((call_count(10000,_,_),l),call_counter,format("limit_exceeded.~n",[])). - -limit_exceeded. - -yes -~~~~~ -Notice that we first compile the looping predicate `l/0` with -call_counting `on`. Next, we catch/3 to handle an -exception when `l/0` performs more than 10000 reductions. - - - */ - -/** @defgroup Arrays Arrays -@ingroup builtins -@{ - -The YAP system includes experimental support for arrays. The -support is enabled with the option `YAP_ARRAYS`. - -There are two very distinct forms of arrays in YAP. The -dynamic arrays are a different way to access compound terms -created during the execution. Like any other terms, any bindings to -these terms and eventually the terms themselves will be destroyed during -backtracking. Our goal in supporting dynamic arrays is twofold. First, -they provide an alternative to the standard arg/3 -built-in. Second, because dynamic arrays may have name that are globally -visible, a dynamic array can be visible from any point in the -program. In more detail, the clause - -~~~~~ -g(X) :- array_element(a,2,X). -~~~~~ -will succeed as long as the programmer has used the built-in array/2 -to create an array term with at least 3 elements in the current -environment, and the array was associated with the name `a`. The -element `X` is a Prolog term, so one can bind it and any such -bindings will be undone when backtracking. Note that dynamic arrays do -not have a type: each element may be any Prolog term. - -The static arrays are an extension of the database. They provide -a compact way for manipulating data-structures formed by characters, -integers, or floats imperatively. They can also be used to provide -two-way communication between YAP and external programs through -shared memory. - -In order to efficiently manage space elements in a static array must -have a type. Currently, elements of static arrays in YAP should -have one of the following predefined types: - -+ `byte`: an 8-bit signed character. -+ `unsigned_byte`: an 8-bit unsigned character. -+ `int`: Prolog integers. Size would be the natural size for -the machine's architecture. -+ `float`: Prolog floating point number. Size would be equivalent -to a double in `C`. -+ `atom`: a Prolog atom. -+ `dbref`: an internal database reference. -+ `term`: a generic Prolog term. Note that this will term will -not be stored in the array itself, but instead will be stored in the -Prolog internal database. - - -Arrays may be named or anonymous. Most arrays will be -named, that is associated with an atom that will be used to find -the array. Anonymous arrays do not have a name, and they are only of -interest if the `TERM_EXTENSIONS` compilation flag is enabled. In -this case, the unification and parser are extended to replace -occurrences of Prolog terms of the form `X[I]` by run-time calls to -array_element/3, so that one can use array references instead of -extra calls to arg/3. As an example: - -~~~~~ -g(X,Y,Z,I,J) :- X[I] is Y[J]+Z[I]. -~~~~~ -should give the same results as: - -~~~~~ -G(X,Y,Z,I,J) :- - array_element(X,I,E1), - array_element(Y,J,E2), - array_element(Z,I,E3), - E1 is E2+E3. -~~~~~ - -Note that the only limitation on array size are the stack size for -dynamic arrays; and, the heap size for static (not memory mapped) -arrays. Memory mapped arrays are limited by available space in the file -system and in the virtual memory space. - -The following predicates manipulate arrays: - - - - -*/ - -/** @pred array(+ _Name_, + _Size_) - - -Creates a new dynamic array. The _Size_ must evaluate to an -integer. The _Name_ may be either an atom (named array) or an -unbound variable (anonymous array). - -Dynamic arrays work as standard compound terms, hence space for the -array is recovered automatically on backtracking. - - -*/ - -/** @pred static_array(+ _Name_, + _Size_, + _Type_) - - -Create a new static array with name _Name_. Note that the _Name_ -must be an atom (named array). The _Size_ must evaluate to an -integer. The _Type_ must be bound to one of types mentioned -previously. - - -*/ - -/** @pred reset_static_array(+ _Name_) - - -Reset static array with name _Name_ to its initial value. - - -*/ - -/** @pred static_array_location(+ _Name_, - _Ptr_) - - -Give the location for a static array with name - _Name_. - - -*/ - -/** @pred static_array_properties(? _Name_, ? _Size_, ? _Type_) - - -Show the properties size and type of a static array with name - _Name_. Can also be used to enumerate all current -static arrays. - -This built-in will silently fail if the there is no static array with -that name. - - -*/ - -/** @pred static_array_to_term(? _Name_, ? _Term_) - - -Convert a static array with name - _Name_ to a compound term of name _Name_. - -This built-in will silently fail if the there is no static array with -that name. - - -*/ - -/** @pred mmapped_array(+ _Name_, + _Size_, + _Type_, + _File_) - - -Similar to static_array/3, but the array is memory mapped to file - _File_. This means that the array is initialized from the file, and -that any changes to the array will also be stored in the file. - -This built-in is only available in operating systems that support the -system call `mmap`. Moreover, mmapped arrays do not store generic -terms (type `term`). - - -*/ - -/** @pred close_static_array(+ _Name_) - - -Close an existing static array of name _Name_. The _Name_ must -be an atom (named array). Space for the array will be recovered and -further accesses to the array will return an error. - - -*/ - -/** @pred resize_static_array(+ _Name_, - _OldSize_, + _NewSize_) - - -Expand or reduce a static array, The _Size_ must evaluate to an -integer. The _Name_ must be an atom (named array). The _Type_ -must be bound to one of `int`, `dbref`, `float` or -`atom`. - -Note that if the array is a mmapped array the size of the mmapped file -will be actually adjusted to correspond to the size of the array. - - -*/ - -/** @pred array_element(+ _Name_, + _Index_, ? _Element_) - - -Unify _Element_ with _Name_[ _Index_]. It works for both -static and dynamic arrays, but it is read-only for static arrays, while -it can be used to unify with an element of a dynamic array. - - -*/ - -/** @pred update_array(+ _Name_, + _Index_, ? _Value_) - - -Attribute value _Value_ to _Name_[ _Index_]. Type -restrictions must be respected for static arrays. This operation is -available for dynamic arrays if `MULTI_ASSIGNMENT_VARIABLES` is -enabled (true by default). Backtracking undoes _update_array/3_ for -dynamic arrays, but not for static arrays. - -Note that update_array/3 actually uses `setarg/3` to update -elements of dynamic arrays, and `setarg/3` spends an extra cell for -every update. For intensive operations we suggest it may be less -expensive to unify each element of the array with a mutable terms and -to use the operations on mutable terms. - - -*/ - -/** @pred add_to_array_element(+ _Name_, + _Index_, + _Number_, ? _NewValue_) - - -Add _Number_ _Name_[ _Index_] and unify _NewValue_ with -the incremented value. Observe that _Name_[ _Index_] must be an -number. If _Name_ is a static array the type of the array must be -`int` or `float`. If the type of the array is `int` you -only may add integers, if it is `float` you may add integers or -floats. If _Name_ corresponds to a dynamic array the array element -must have been previously bound to a number and `Number` can be -any kind of number. - -The `add_to_array_element/3` built-in actually uses -`setarg/3` to update elements of dynamic arrays. For intensive -operations we suggest it may be less expensive to unify each element -of the array with a mutable terms and to use the operations on mutable -terms. - - - - - */ - -/** @defgroup Preds Predicate Information -@ingroup builtins -@{ - -Built-ins that return information on the current predicates and modules: - - - - -*/ - -/** @pred current_module( _M_) - - -Succeeds if _M_ are defined modules. A module is defined as soon as some -predicate defined in the module is loaded, as soon as a goal in the -module is called, or as soon as it becomes the current type-in module. - - -*/ - -/** @pred current_module( _M_, _F_) - -Succeeds if _M_ are current modules associated to the file _F_. - - - - - */ - -/** @defgroup Misc Miscellaneous -@ingroup builtins -@{ - - - - -*/ - -/** @pred statistics/0 - - -Send to the current user error stream general information on space used and time -spent by the system. - -~~~~~ -?- statistics. -memory (total) 4784124 bytes - program space 3055616 bytes: 1392224 in use, 1663392 free - 2228132 max - stack space 1531904 bytes: 464 in use, 1531440 free - global stack: 96 in use, 616684 max - local stack: 368 in use, 546208 max - trail stack 196604 bytes: 8 in use, 196596 free - - 0.010 sec. for 5 code, 2 stack, and 1 trail space overflows - 0.130 sec. for 3 garbage collections which collected 421000 bytes - 0.000 sec. for 0 atom garbage collections which collected 0 bytes - 0.880 sec. runtime - 1.020 sec. cputime - 25.055 sec. elapsed time - -~~~~~ -The example shows how much memory the system spends. Memory is divided -into Program Space, Stack Space and Trail. In the example we have 3MB -allocated for program spaces, with less than half being actually -used. YAP also shows the maximum amount of heap space having been used -which was over 2MB. - -The stack space is divided into two stacks which grow against each -other. We are in the top level so very little stack is being used. On -the other hand, the system did use a lot of global and local stack -during the previous execution (we refer the reader to a WAM tutorial in -order to understand what are the global and local stacks). - -YAP also shows information on how many memory overflows and garbage -collections the system executed, and statistics on total execution -time. Cputime includes all running time, runtime excludes garbage -collection and stack overflow time. - - -*/ - -/** @pred statistics(? _Param_,- _Info_) - -Gives statistical information on the system parameter given by first -argument: - - - -+ atoms - -`[ _NumberOfAtoms_, _SpaceUsedBy Atoms_]` - - -This gives the total number of atoms `NumberOfAtoms` and how much -space they require in bytes, _SpaceUsedBy Atoms_. - -+ cputime - -`[ _Time since Boot_, _Time From Last Call to Cputime_]` - - -This gives the total cputime in milliseconds spent executing Prolog code, -garbage collection and stack shifts time included. - -+ dynamic_code - -`[ _Clause Size_, _Index Size_, _Tree Index Size_, _Choice Point Instructions Size_, _Expansion Nodes Size_, _Index Switch Size_]` - - -Size of static code in YAP in bytes: _Clause Size_, the number of -bytes allocated for clauses, plus - _Index Size_, the number of bytes spent in the indexing code. The -indexing code is divided into main tree, _Tree Index Size_, -tables that implement choice-point manipulation, _Choice xsPoint Instructions Size_, tables that cache clauses for future expansion of the index -tree, _Expansion Nodes Size_, and -tables such as hash tables that select according to value, _Index Switch Size_. - -+ garbage_collection - -`[ _Number of GCs_, _Total Global Recovered_, _Total Time Spent_]` - - -Number of garbage collections, amount of space recovered in kbytes, and -total time spent doing garbage collection in milliseconds. More detailed -information is available using `yap_flag(gc_trace,verbose)`. - -+ global_stack - -`[ _Global Stack Used_, _Execution Stack Free_]` - - -Space in kbytes currently used in the global stack, and space available for -expansion by the local and global stacks. - -+ local_stack - -`[ _Local Stack Used_, _Execution Stack Free_]` - - -Space in kbytes currently used in the local stack, and space available for -expansion by the local and global stacks. - -+ heap - -`[ _Heap Used_, _Heap Free_]` - - -Total space in kbytes not recoverable -in backtracking. It includes the program code, internal data base, and, -atom symbol table. - -+ program - -`[ _Program Space Used_, _Program Space Free_]` - - -Equivalent to heap. - -+ runtime - -`[ _Time since Boot_, _Time From Last Call to Runtime_]` - - -This gives the total cputime in milliseconds spent executing Prolog -code, not including garbage collections and stack shifts. Note that -until YAP4.1.2 the runtime statistics would return time spent on -garbage collection and stack shifting. - -+ stack_shifts - -`[ _Number of Heap Shifts_, _Number of Stack Shifts_, _Number of Trail Shifts_]` - - -Number of times YAP had to -expand the heap, the stacks, or the trail. More detailed information is -available using `yap_flag(gc_trace,verbose)`. - -+ static_code - -`[ _Clause Size_, _Index Size_, _Tree Index Size_, _Expansion Nodes Size_, _Index Switch Size_]` - - -Size of static code in YAP in bytes: _Clause Size_, the number of -bytes allocated for clauses, plus - _Index Size_, the number of bytes spent in the indexing code. The -indexing code is divided into a main tree, _Tree Index Size_, table that cache clauses for future expansion of the index -tree, _Expansion Nodes Size_, and and -tables such as hash tables that select according to value, _Index Switch Size_. - -+ trail - -`[ _Trail Used_, _Trail Free_]` - - -Space in kbytes currently being used and still available for the trail. - -+ walltime - -`[ _Time since Boot_, _Time From Last Call to Walltime_]` - - -This gives the clock time in milliseconds since starting Prolog. - - - - -*/ - -/** @pred time(: _Goal_) - - -Prints the CPU time and the wall time for the execution of _Goal_. -Possible choice-points of _Goal_ are removed. Based on the SWI-Prolog -definition (minus reporting the number of inferences, which YAP currently -does not support). - - -*/ - -/** @pred yap_flag(? _Param_,? _Value_) - - -Set or read system properties for _Param_: - - -+ `argv ` - - Read-only flag. It unifies with a list of atoms that gives the -arguments to YAP after `--`. - -+ `agc_margin ` - - An integer: if this amount of atoms has been created since the last -atom-garbage collection, perform atom garbage collection at the first -opportunity. Initial value is 10,000. May be changed. A value of 0 -(zero) disables atom garbage collection. - -+ `associate ` - - Read-write flag telling a suffix for files associated to Prolog -sources. It is `yap` by default. - -+ `bounded is iso ` - - Read-only flag telling whether integers are bounded. The value depends -on whether YAP uses the GMP library or not. - -+ `profiling ` - - If `off` (default) do not compile call counting information for -procedures. If `on` compile predicates so that they calls and -retries to the predicate may be counted. Profiling data can be read through the -call_count_data/3 built-in. - -+ `char_conversion is iso` - - Writable flag telling whether a character conversion table is used when -reading terms. The default value for this flag is `off` except in -`sicstus` and `iso` language modes, where it is `on`. - -+ `character_escapes is iso ` - - Writable flag telling whether a character escapes are enables, -`true`, or disabled, `false`. The default value for this flag is -`on`. - -+ `debug is iso ` - - If _Value_ is unbound, tell whether debugging is `true` or -`false`. If _Value_ is bound to `true` enable debugging, and if -it is bound to `false` disable debugging. - -+ `debugger_print_options ` - - If bound, set the argument to the `write_term/3` options the -debugger uses to write terms. If unbound, show the current options. - -+ `dialect ` - - Read-only flag that always returns `yap`. - -+ `discontiguous_warnings ` - - If _Value_ is unbound, tell whether warnings for discontiguous -predicates are `on` or -`off`. If _Value_ is bound to `on` enable these warnings, -and if it is bound to `off` disable them. The default for YAP is -`off`, unless we are in `sicstus` or `iso` mode. - -+ `dollar_as_lower_case ` - - If `off` (default) consider the character `$` a control character, if -`on` consider `$` a lower case character. - -+ `double_quotes is iso ` - - If _Value_ is unbound, tell whether a double quoted list of characters -token is converted to a list of atoms, `chars`, to a list of integers, -`codes`, or to a single atom, `atom`. If _Value_ is bound, set to -the corresponding behavior. The default value is `codes`. - -+ `executable ` - - Read-only flag. It unifies with an atom that gives the -original program path. - -+ `fast ` - - If `on` allow fast machine code, if `off` (default) disable it. Only -available in experimental implementations. - -+ `fileerrors` - - If `on` `fileerrors` is `on`, if `off` (default) -`fileerrors` is disabled. - -+ `float_format ` - - C-library `printf()` format specification used by write/1 and -friends to determine how floating point numbers are printed. The -default is `%.15g`. The specified value is passed to `printf()` -without further checking. For example, if you want less digits -printed, `%g` will print all floats using 6 digits instead of the -default 15. - -+ `gc` - - If `on` allow garbage collection (default), if `off` disable it. - -+ `gc_margin ` - - Set or show the minimum free stack before starting garbage -collection. The default depends on total stack size. - -+ `gc_trace ` - - If `off` (default) do not show information on garbage collection -and stack shifts, if `on` inform when a garbage collection or stack -shift happened, if verbose give detailed information on garbage -collection and stack shifts. Last, if `very_verbose` give detailed -information on data-structures found during the garbage collection -process, namely, on choice-points. - -+ `generate_debugging_info ` - - If `true` (default) generate debugging information for -procedures, including source mode. If `false` predicates no -information is generated, although debugging is still possible, and -source mode is disabled. - -+ `host_type ` - - Return `configure` system information, including the machine-id -for which YAP was compiled and Operating System information. - -+ `index ` - - If `on` allow indexing (default), if `off` disable it, if -`single` allow on first argument only. - -+ `index_sub_term_search_depth ` - - Maximum bound on searching sub-terms for indexing, if `0` (default) no bound. - -+ `informational_messages ` - - If `on` allow printing of informational messages, such as the ones -that are printed when consulting. If `off` disable printing -these messages. It is `on` by default except if YAP is booted with -the `-L` flag. - -+ `integer_rounding_function is iso ` - - Read-only flag telling the rounding function used for integers. Takes the value -`toward_zero` for the current version of YAP. - -+ `language ` - - Choose whether YAP is closer to C-Prolog, `cprolog`, iso-prolog, -`iso` or SICStus Prolog, `sicstus`. The current default is -`cprolog`. This flag affects update semantics, leashing mode, -style checking, handling calls to undefined procedures, how directives -are interpreted, when to use dynamic, character escapes, and how files -are consulted. - -+ `max_arity is iso ` - - Read-only flag telling the maximum arity of a functor. Takes the value -`unbounded` for the current version of YAP. - -+ `max_integer is iso ` - - Read-only flag telling the maximum integer in the -implementation. Depends on machine and Operating System -architecture, and on whether YAP uses the `GMP` multi-precision -library. If bounded is false, requests for max_integer -will fail. - -+ `max_tagged_integer ` - - Read-only flag telling the maximum integer we can store as a single -word. Depends on machine and Operating System -architecture. It can be used to find the word size of the current machine. - -+ `min_integer is iso ` - - Read-only flag telling the minimum integer in the -implementation. Depends on machine and Operating System architecture, -and on whether YAP uses the `GMP` multi-precision library. If -bounded is false, requests for min_integer will fail. - -+ `min_tagged_integer ` - - Read-only flag telling the minimum integer we can store as a single -word. Depends on machine and Operating System -architecture. - -+ `n_of_integer_keys_in_bb ` - - Read or set the size of the hash table that is used for looking up the -blackboard when the key is an integer. - -+ `occurs_check ` - - Current read-only and set to `false`. - -+ `n_of_integer_keys_in_db ` - - Read or set the size of the hash table that is used for looking up the -internal data-base when the key is an integer. - -+ `open_expands_filename ` - - If `true` the open/3 builtin performs filename-expansion -before opening a file (SICStus Prolog like). If `false` it does not -(SWI-Prolog like). - -+ `open_shared_object ` - - If true, `open_shared_object/2` and friends are implemented, -providing access to shared libraries (`.so` files) or to dynamic link -libraries (`.DLL` files). - -+ `profiling ` - - If `off` (default) do not compile profiling information for -procedures. If `on` compile predicates so that they will output -profiling information. Profiling data can be read through the -profile_data/3 built-in. - -+ `prompt_alternatives_on(atom, changeable) ` - - SWI-Compatible option, determines prompting for alternatives in the Prolog toplevel. Default is groundness, YAP prompts for alternatives if and only if the query contains variables. The alternative, default in SWI-Prolog is determinism which implies the system prompts for alternatives if the goal succeeded while leaving choicepoints. - -+ `redefine_warnings ` - - If _Value_ is unbound, tell whether warnings for procedures defined -in several different files are `on` or -`off`. If _Value_ is bound to `on` enable these warnings, -and if it is bound to `off` disable them. The default for YAP is -`off`, unless we are in `sicstus` or `iso` mode. - -+ `shared_object_search_path ` - - Name of the environment variable used by the system to search for shared -objects. - -+ `shared_object_extension ` - - Suffix associated with loadable code. - -+ `single_var_warnings ` - - If _Value_ is unbound, tell whether warnings for singleton variables -are `on` or `off`. If _Value_ is bound to `on` enable -these warnings, and if it is bound to `off` disable them. The -default for YAP is `off`, unless we are in `sicstus` or -`iso` mode. - -+ `strict_iso ` - - If _Value_ is unbound, tell whether strict ISO compatibility mode -is `on` or `off`. If _Value_ is bound to `on` set -language mode to `iso` and enable strict mode. If _Value_ is -bound to `off` disable strict mode, and keep the current language -mode. The default for YAP is `off`. -Under strict ISO Prolog mode all calls to non-ISO built-ins generate an -error. Compilation of clauses that would call non-ISO built-ins will -also generate errors. Pre-processing for grammar rules is also -disabled. Module expansion is still performed. -Arguably, ISO Prolog does not provide all the functionality required -from a modern Prolog system. Moreover, because most Prolog -implementations do not fully implement the standard and because the -standard itself gives the implementor latitude in a few important -questions, such as the unification algorithm and maximum size for -numbers there is no guarantee that programs compliant with this mode -will work the same way in every Prolog and in every platform. We thus -believe this mode is mostly useful when investigating how a program -depends on a Prolog's platform specific features. - -+ `stack_dump_on_error ` - - If `on` show a stack dump when YAP finds an error. The default is -`off`. - -+ `syntax_errors` - - Control action to be taken after syntax errors while executing read/1, -`read/2`, or `read_term/3`: - + `dec10` -Report the syntax error and retry reading the term. - + `fail` -Report the syntax error and fail (default). - + `error` -Report the syntax error and generate an error. - + `quiet` -Just fail - -+ `system_options ` - - This read only flag tells which options were used to compile -YAP. Currently it informs whether the system supports `big_numbers`, -`coroutining`, `depth_limit`, `low_level_tracer`, -`or-parallelism`, `rational_trees`, `readline`, `tabling`, -`threads`, or the `wam_profiler`. - -+ `tabling_mode` - - Sets or reads the tabling mode for all tabled predicates. Please - (see Tabling) for the list of options. - -+ `to_chars_mode ` - - Define whether YAP should follow `quintus`-like -semantics for the `atom_chars/1` or `number_chars/1` built-in, -or whether it should follow the ISO standard (`iso` option). - -+ `toplevel_hook ` - - If bound, set the argument to a goal to be executed before entering the -top-level. If unbound show the current goal or `true` if none is -presented. Only the first solution is considered and the goal is not -backtracked into. - -+ `toplevel_print_options ` - - If bound, set the argument to the `write_term/3` options used to write -terms from the top-level. If unbound, show the current options. - -+ `typein_module ` - - If bound, set the current working or type-in module to the argument, -which must be an atom. If unbound, unify the argument with the current -working module. - -+ `unix` - - Read-only Boolean flag that unifies with `true` if YAP is -running on an Unix system. Defined if the C-compiler used to compile -this version of YAP either defines `__unix__` or `unix`. - -+ `unknown is iso` - - Corresponds to calling the unknown/2 built-in. Possible values -are `error`, `fail`, and `warning`. - -+ `update_semantics ` - - Define whether YAP should follow `immediate` update -semantics, as in C-Prolog (default), `logical` update semantics, -as in Quintus Prolog, SICStus Prolog, or in the ISO standard. There is -also an intermediate mode, `logical_assert`, where dynamic -procedures follow logical semantics but the internal data base still -follows immediate semantics. - -+ `user_error ` - - If the second argument is bound to a stream, set user_error to -this stream. If the second argument is unbound, unify the argument with -the current user_error stream. -By default, the user_error stream is set to a stream -corresponding to the Unix `stderr` stream. -The next example shows how to use this flag: - -~~~{.prolog} - ?- open( '/dev/null', append, Error, - [alias(mauri_tripa)] ). - - Error = '$stream'(3) ? ; - - no - ?- set_prolog_flag(user_error, mauri_tripa). - - close(mauri_tripa). - - yes - ?- -~~~ - We execute three commands. First, we open a stream in write mode and -give it an alias, in this case `mauri_tripa`. Next, we set -user_error to the stream via the alias. Note that after we did so -prompts from the system were redirected to the stream -`mauri_tripa`. Last, we close the stream. At this point, YAP -automatically redirects the user_error alias to the original -`stderr`. - -+ `user_flags ` - - Define the behaviour of set_prolog_flag/2 if the flag is not known. Values are `silent`, `warning` and `error`. The first two create the flag on-the-fly, with `warning` printing a message. The value `error` is consistent with ISO: it raises an existence error and does not create the flag. See also `create_prolog_flag/3`. The default is`error`, and developers are encouraged to use `create_prolog_flag/3` to create flags for their library. - -+ `user_input ` - - If the second argument is bound to a stream, set user_input to -this stream. If the second argument is unbound, unify the argument with -the current user_input stream. -By default, the user_input stream is set to a stream -corresponding to the Unix `stdin` stream. - -+ `user_output ` - - If the second argument is bound to a stream, set user_output to -this stream. If the second argument is unbound, unify the argument with -the current user_output stream. -By default, the user_output stream is set to a stream -corresponding to the Unix `stdout` stream. - -+ `verbose ` - - If `normal` allow printing of informational and banner messages, -such as the ones that are printed when consulting. If `silent` -disable printing these messages. It is `normal` by default except if -YAP is booted with the `-q` or `-L` flag. - -+ `verbose_load ` - - If `true` allow printing of informational messages when -consulting files. If `false` disable printing these messages. It -is `normal` by default except if YAP is booted with the `-L` -flag. - -+ `version ` - - Read-only flag that returns an atom with the current version of -YAP. - -+ `version_data ` - - Read-only flag that reads a term of the form -`yap`( _Major_, _Minor_, _Patch_, _Undefined_), where - _Major_ is the major version, _Minor_ is the minor version, -and _Patch_ is the patch number. - -+ `windows ` - - Read-only boolean flag that unifies with tr `true` if YAP is -running on an Windows machine. - -+ `write_strings ` - - Writable flag telling whether the system should write lists of -integers that are writable character codes using the list notation. It -is `on` if enables or `off` if disabled. The default value for -this flag is `off`. - -+ `max_workers ` - - Read-only flag telling the maximum number of parallel processes. - -+ `max_threads ` - - Read-only flag telling the maximum number of Prolog threads that can -be created. - - - -*/ - -/** @pred current_prolog_flag(? _Flag_,- _Value_) is iso - -Obtain the value for a YAP Prolog flag. Equivalent to calling -yap_flag/2 with the second argument unbound, and unifying the -returned second argument with _Value_. - - -*/ - -/** @pred prolog_flag(? _Flag_,- _OldValue_,+ _NewValue_) - - - -Obtain the value for a YAP Prolog flag and then set it to a new -value. Equivalent to first calling current_prolog_flag/2 with the -second argument _OldValue_ unbound and then calling -set_prolog_flag/2 with the third argument _NewValue_. - - -*/ - -/** @pred set_prolog_flag(+ _Flag_,+ _Value_) is iso - - - -Set the value for YAP Prolog flag `Flag`. Equivalent to -calling yap_flag/2 with both arguments bound. - - -*/ - -/** @pred create_prolog_flag(+ _Flag_,+ _Value_,+ _Options_) - - - -Create a new YAP Prolog flag. _Options_ include `type(+Type)` and `access(+Access)` with _Access_ -one of `read_only` or `read_write` and _Type_ one of `boolean`, `integer`, `float`, `atom` -and `term` (that is, no type). - - -*/ - -/** @pred op(+ _P_,+ _T_,+ _A_) is iso - - -Defines the operator _A_ or the list of operators _A_ with type - _T_ (which must be one of `xfx`, `xfy`,`yfx`, -`xf`, `yf`, `fx` or `fy`) and precedence _P_ -(see appendix iv for a list of predefined operators). - -Note that if there is a preexisting operator with the same name and -type, this operator will be discarded. Also, `,` may not be defined -as an operator, and it is not allowed to have the same for an infix and -a postfix operator. - - -*/ - -/** @pred current_op( _P_, _T_, _F_) is iso - - -Defines the relation: _P_ is a currently defined operator of type - _T_ and precedence _P_. - - -*/ - -/** @pred prompt(- _A_,+ _B_) - - -Changes YAP input prompt from _A_ to _B_. - - -*/ - -/** @pred initialization - -Execute the goals defined by initialization/1. Only the first answer is -considered. - - -*/ - -/** @pred prolog_initialization( _G_) - - -Add a goal to be executed on system initialization. This is compatible -with SICStus Prolog's initialization/1. - - -*/ - -/** @pred version - -Write YAP's boot message. - - -*/ - -/** @pred version(- _Message_) - -Add a message to be written when yap boots or after aborting. It is not -possible to remove messages. - - -*/ - -/** @pred prolog_load_context(? _Key_, ? _Value_) - - -Obtain information on what is going on in the compilation process. The -following keys are available: - - - -+ directory - - - -Full name for the directory where YAP is currently consulting the -file. - -+ file - - - -Full name for the file currently being consulted. Notice that included -filed are ignored. - -+ module - - - -Current source module. - -+ `source` (prolog_load_context/2 option) - - Full name for the file currently being read in, which may be consulted, -reconsulted, or included. - -+ `stream` - - Stream currently being read in. - -+ `term_position` - - Stream position at the stream currently being read in. For SWI -compatibility, it is a term of the form -'$stream_position'(0,Line,0,0,0). - - -+ `source_location(? _FileName_, ? _Line_)` - - SWI-compatible predicate. If the last term has been read from a physical file (i.e., not from the file user or a string), unify File with an absolute path to the file and Line with the line-number in the file. Please use prolog_load_context/2. - -+ `source_file(? _File_)` - - SWI-compatible predicate. True if _File_ is a loaded Prolog source file. - -+ `source_file(? _ModuleAndPred_,? _File_)` - - SWI-compatible predicate. True if the predicate specified by _ModuleAndPred_ was loaded from file _File_, where _File_ is an absolute path name (see `absolute_file_name/2`). - - - -@section library Library Predicates - -Library files reside in the library_directory path (set by the -`LIBDIR` variable in the Makefile for YAP). Currently, -most files in the library are from the Edinburgh Prolog library. - - - */ - -/** @defgroup Aggregate Aggregate -@ingroup library -@{ - -This is the SWI-Prolog library based on the Quintus and SICStus 4 -library. @c To be done - Analysing the aggregation template. - - -This library provides aggregating operators over the solutions of a -predicate. The operations are a generalisation of the bagof/3, -setof/3 and findall/3 built-in predicates. The defined -aggregation operations are counting, computing the sum, minimum, -maximum, a bag of solutions and a set of solutions. We first give a -simple example, computing the country with the smallest area: - -~~~~~{.prolog} -smallest_country(Name, Area) :- - aggregate(min(A, N), country(N, A), min(Area, Name)). -~~~~~ - -There are four aggregation predicates, distinguished on two properties. - -+ aggregate vs. aggregate_all -The aggregate predicates use setof/3 (aggregate/4) or bagof/3 -(aggregate/3), dealing with existential qualified variables -( _Var_/\ _Goal_) and providing multiple solutions for the -remaining free variables in _Goal_. The aggregate_all/3 -predicate uses findall/3, implicitly qualifying all free variables -and providing exactly one solution, while aggregate_all/4 uses -sort/2 over solutions and Distinguish (see below) generated using -findall/3. -+ The _Distinguish_ argument -The versions with 4 arguments provide a _Distinguish_ argument -that allow for keeping duplicate bindings of a variable in the -result. For example, if we wish to compute the total population of -all countries we do not want to lose results because two countries -have the same population. Therefore we use: - -~~~~~{.prolog} - aggregate(sum(P), Name, country(Name, P), Total) -~~~~~ - - - -All aggregation predicates support the following operators below in - _Template_. In addition, they allow for an arbitrary named compound -term where each of the arguments is a term from the list below. I.e. the -term `r(min(X), max(X))` computes both the minimum and maximum -binding for _X_. - -+ `count` - - Count number of solutions. Same as `sum(1)`. - -+ `sum( _Expr_)` - - Sum of _Expr_ for all solutions. - -+ `min( _Expr_)` - - Minimum of _Expr_ for all solutions. - -+ `min( _Expr_, _Witness_)` - - A term min( _Min_, _Witness_), where _Min_ is the minimal version of _Expr_ - -over all Solution and _Witness_ is any other template applied to -Solution that produced _Min_. If multiple solutions provide the same -minimum, _Witness_ corresponds to the first solution. - -+ `max( _Expr_)` - - Maximum of _Expr_ for all solutions. - -+ `max( _Expr_, _Witness_)` - - As min( _Expr_, _Witness_), but producing the maximum result. - -+ `set( _X_)` - - An ordered set with all solutions for _X_. - -+ `bag( _X_)` - - A list of all solutions for _X_. - - - -The predicates are: - - - - @pred aggregate(+ _Template_, : _Goal_, - _Result_) is nondet - - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate/3 version performs bagof/3 on _Goal_. - -*/ - -/** @pred [nondet]aggregate(+ _Template_, + _Discriminator_, : _Goal_, - _Result_) - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate/3 version performs setof/3 on _Goal_. - -*/ - -/** @pred aggregate_all(+ _Template_, : _Goal_, - _Result_) is semidet - - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate_all/3 version performs findall/3 on _Goal_. - -*/ - -/** @pred aggregate_all(+ _Template_, + _Discriminator_, : _Goal_, - _Result_) is semidet - -Aggregate bindings in _Goal_ according to _Template_. The -aggregate_all/3 version performs findall/3 followed by sort/2 on - _Goal_. - -*/ - -/** @pred foreach(:Generator, : _Goal_) - - -True if the conjunction of instances of _Goal_ using the -bindings from Generator is true. Unlike forall/2, which runs a -failure-driven loop that proves _Goal_ for each solution of -Generator, foreach creates a conjunction. Each member of the -conjunction is a copy of _Goal_, where the variables it shares -with Generator are filled with the values from the corresponding -solution. - -The implementation executes forall/2 if _Goal_ does not contain -any variables that are not shared with Generator. - -Here is an example: - -~~~~~{.prolog} - ?- foreach( between(1,4,X), dif(X,Y)), Y = 5. - Y = 5 - ?- foreach( between(1,4,X), dif(X,Y)), Y = 3. - No -~~~~~ - -Notice that _Goal_ is copied repeatedly, which may cause -problems if attributed variables are involved. - - -*/ - -/** @pred free_variables(:Generator, + _Template_, +VarList0, -VarList) is det - - -In order to handle variables properly, we have to find all the universally quantified variables in the Generator. All variables as yet unbound are universally quantified, unless - -+ they occur in the template -+ they are bound by X/\P, setof, or bagof - -`free_variables(Generator, Template, OldList, NewList)` finds this set, using OldList as an accumulator. - - -The original author of this code was Richard O'Keefe. Jan Wielemaker -made some SWI-Prolog enhancements, sponsored by SecuritEase, -http://www.securitease.com. The code is public domain (from DEC10 library). - - - */ - -/** @defgroup Apply Apply Macros -@ingroup library -@{ - -This library provides a SWI-compatible set of utilities for applying a -predicate to all elements of a list. The library just forwards -definitions from the `maplist` library. - - - */ - -/** @defgroup Association_Lists Association Lists -@ingroup library -@{ - -The following association list manipulation predicates are available -once included with the `use_module(library(assoc))` command. The -original library used Richard O'Keefe's implementation, on top of -unbalanced binary trees. The current code utilises code from the -red-black trees library and emulates the SICStus Prolog interface. - - -*/ - -/** @pred assoc_to_list(+ _Assoc_,? _List_) - - -Given an association list _Assoc_ unify _List_ with a list of -the form _Key-Val_, where the elements _Key_ are in ascending -order. - - -*/ - -/** @pred del_assoc(+ _Key_, + _Assoc_, ? _Val_, ? _NewAssoc_) - - -Succeeds if _NewAssoc_ is an association list, obtained by removing -the element with _Key_ and _Val_ from the list _Assoc_. - - -*/ - -/** @pred del_max_assoc(+ _Assoc_, ? _Key_, ? _Val_, ? _NewAssoc_) - - -Succeeds if _NewAssoc_ is an association list, obtained by removing -the largest element of the list, with _Key_ and _Val_ from the -list _Assoc_. - - -*/ - -/** @pred del_min_assoc(+ _Assoc_, ? _Key_, ? _Val_, ? _NewAssoc_) - - -Succeeds if _NewAssoc_ is an association list, obtained by removing -the smallest element of the list, with _Key_ and _Val_ -from the list _Assoc_. - - -*/ - -/** @pred empty_assoc(+ _Assoc_) - - -Succeeds if association list _Assoc_ is empty. - - -*/ - -/** @pred gen_assoc(+ _Assoc_,? _Key_,? _Value_) - - -Given the association list _Assoc_, unify _Key_ and _Value_ -with two associated elements. It can be used to enumerate all elements -in the association list. - - -*/ - -/** @pred get_assoc(+ _Key_,+ _Assoc_,? _Value_) - - -If _Key_ is one of the elements in the association list _Assoc_, -return the associated value. - - -*/ - -/** @pred get_assoc(+ _Key_,+ _Assoc_,? _Value_,+ _NAssoc_,? _NValue_) - - -If _Key_ is one of the elements in the association list _Assoc_, -return the associated value _Value_ and a new association list - _NAssoc_ where _Key_ is associated with _NValue_. - - -*/ - -/** @pred get_prev_assoc(+ _Key_,+ _Assoc_,? _Next_,? _Value_) - - -If _Key_ is one of the elements in the association list _Assoc_, -return the previous key, _Next_, and its value, _Value_. - - -*/ - -/** @pred get_next_assoc(+ _Key_,+ _Assoc_,? _Next_,? _Value_) - -If _Key_ is one of the elements in the association list _Assoc_, -return the next key, _Next_, and its value, _Value_. - - -*/ - -/** @pred is_assoc(+ _Assoc_) - - -Succeeds if _Assoc_ is an association list, that is, if it is a -red-black tree. - - -*/ - -/** @pred list_to_assoc(+ _List_,? _Assoc_) - - -Given a list _List_ such that each element of _List_ is of the -form _Key-Val_, and all the _Keys_ are unique, _Assoc_ is -the corresponding association list. - - -*/ - -/** @pred map_assoc(+ _Pred_,+ _Assoc_) - - -Succeeds if the unary predicate name _Pred_( _Val_) holds for every -element in the association list. - - -*/ - -/** @pred map_assoc(+ _Pred_,+ _Assoc_,? _New_) - -Given the binary predicate name _Pred_ and the association list - _Assoc_, _New_ in an association list with keys in _Assoc_, -and such that if _Key-Val_ is in _Assoc_, and _Key-Ans_ is in - _New_, then _Pred_( _Val_, _Ans_) holds. - - -*/ - -/** @pred max_assoc(+ _Assoc_,- _Key_,? _Value_) - - -Given the association list - _Assoc_, _Key_ in the largest key in the list, and _Value_ -the associated value. - - -*/ - -/** @pred min_assoc(+ _Assoc_,- _Key_,? _Value_) - - -Given the association list - _Assoc_, _Key_ in the smallest key in the list, and _Value_ -the associated value. - - -*/ - -/** @pred ord_list_to_assoc(+ _List_,? _Assoc_) - - -Given an ordered list _List_ such that each element of _List_ is -of the form _Key-Val_, and all the _Keys_ are unique, _Assoc_ is -the corresponding association list. - - -*/ - -/** @pred put_assoc(+ _Key_,+ _Assoc_,+ _Val_,+ _New_) - - -The association list _New_ includes and element of association - _key_ with _Val_, and all elements of _Assoc_ that did not -have key _Key_. - - - - - */ - -/** @defgroup AVL_Trees AVL Trees -@ingroup library -@{ - -AVL trees are balanced search binary trees. They are named after their -inventors, Adelson-Velskii and Landis, and they were the first -dynamically balanced trees to be proposed. The YAP AVL tree manipulation -predicates library uses code originally written by Martin van Emdem and -published in the Logic Programming Newsletter, Autumn 1981. A bug in -this code was fixed by Philip Vasey, in the Logic Programming -Newsletter, Summer 1982. The library currently only includes routines to -insert and lookup elements in the tree. Please try red-black trees if -you need deletion. - - -*/ - -/** @pred avl_new(+ _T_) - - -Create a new tree. - - -*/ - -/** @pred avl_insert(+ _Key_,? _Value_,+ _T0_,- _TF_) - - -Add an element with key _Key_ and _Value_ to the AVL tree - _T0_ creating a new AVL tree _TF_. Duplicated elements are -allowed. - - -*/ - -/** @pred avl_lookup(+ _Key_,- _Value_,+ _T_) - - -Lookup an element with key _Key_ in the AVL tree - _T_, returning the value _Value_. - - - - - */ - -/** @defgroup Exo_Intervals Exo Intervals -@ingroup library -@{ - -This package assumes you use exo-compilation, that is, that you loaded -the pedicate using the `exo` option to load_files/2, In this -case, YAP includes a package for improved search on intervals of -integers. - -The package is activated by `udi` declarations that state what is -the argument of interest: - -~~~~~{.prolog} -:- udi(diagnoses(exo_interval,?,?)). - -:- load_files(db, [consult(exo)]). -~~~~~ -It is designed to optimise the following type of queries: - -~~~~~{.prolog} -?- max(X, diagnoses(X, 9, Y), X). - -?- min(X, diagnoses(X, 9, 36211117), X). - -?- X #< Y, min(X, diagnoses(X, 9, 36211117), X ), diagnoses(Y, 9, _). -~~~~~ -The first argument gives the time, the second the patient, and the -third the condition code. The first query should find the last time -the patient 9 had any code reported, the second looks for the first -report of code 36211117, and the last searches for reports after this -one. All queries run in constant or log(n) time. - - - */ - -/** @defgroup Gecode Gecode Interface -@ingroup packages -@{ - - -The gecode library intreface was designed and implemented by Denis -Duchier, with recent work by Vítor Santos Costa to port it to version 4 -of gecode and to have an higher level interface, - - - */ - -/** @defgroup The_Gecode_Interface The Gecode Interface -@ingroup Gecode -@{ - -This text is due to Denys Duchier. The gecode interface requires - -~~~~~{.prolog} -:- use_module(library(gecode)). -~~~~~ -Several example programs are available with the distribution. - -+ CREATING A SPACE - -A space is gecodes data representation for a store of constraints: - -~~~~~{.prolog} - Space := space -~~~~~ - -+ CREATING VARIABLES - -Unlike in Gecode, variable objects are not bound to a specific Space. Each one -actually contains an index with which it is possible to access a Space-bound -Gecode variable. Variables can be created using the following expressions: - -~~~~~{.prolog} - IVar := intvar(Space,SPEC...) - BVar := boolvar(Space) - SVar := setvar(Space,SPEC...) -~~~~~ - -where SPEC... is the same as in Gecode. For creating lists of variables use -the following variants: - -~~~~~{.prolog} - IVars := intvars(Space,N,SPEC...) - BVars := boolvars(Space,N,SPEC...) - SVars := setvars(Space,N,SPEC...) -~~~~~ - -where N is the number of variables to create (just like for XXXVarArray in -Gecode). Sometimes an IntSet is necessary: - -~~~~~{.prolog} - ISet := intset([SPEC...]) -~~~~~ - -where each SPEC is either an integer or a pair (I,J) of integers. An IntSet -describes a set of ints by providing either intervals, or integers (which stand -for an interval of themselves). It might be tempting to simply represent an -IntSet as a list of specs, but this would be ambiguous with IntArgs which, -here, are represented as lists of ints. - -~~~~~{.prolog} - Space += keep(Var) - Space += keep(Vars) -~~~~~ - -Variables can be marked as "kept". In this case, only such variables will be -explicitly copied during search. This could bring substantial benefits in -memory usage. Of course, in a solution, you can then only look at variables -that have been "kept". If no variable is marked as "kept", then they are all -kept. Thus marking variables as "kept" is purely an optimization. - -+ CONSTRAINTS AND BRANCHINGS - -all constraint and branching posting functions are available just like in -Gecode. Wherever a XXXArgs or YYYSharedArray is expected, simply use a list. -At present, there is no support for minimodel-like constraint posting. -Constraints and branchings are added to a space using: - -~~~~~{.prolog} - Space += CONSTRAINT - Space += BRANCHING -~~~~~ - -For example: - -~~~~~{.prolog} - Space += rel(X,'IRT_EQ',Y) -~~~~~ - -arrays of variables are represented by lists of variables, and constants are -represented by atoms with the same name as the Gecode constant -(e.g. 'INT_VAR_SIZE_MIN'). - -+ SEARCHING FOR SOLUTIONS - -~~~~~{.prolog} - SolSpace := search(Space) -~~~~~ - -This is a backtrackable predicate that enumerates all solution spaces -(SolSpace). It may also take options: - -~~~~~{.prolog} - SolSpace := search(Space,Options) -~~~~~ - -Options is a list whose elements maybe: - -+ restart -to select the Restart search engine -+ threads=N -to activate the parallel search engine and control the number of -workers (see Gecode doc) -+ c_d=N -to set the commit distance for recomputation -+ a_d=N -to set the adaptive distance for recomputation - - - -+ EXTRACTING INFO FROM A SOLUTION - -An advantage of non Space-bound variables, is that you can use them both to -post constraints in the original space AND to consult their values in -solutions. Below are methods for looking up information about variables. Each -of these methods can either take a variable as argument, or a list of -variables, and returns resp. either a value, or a list of values: - -~~~~~{.prolog} - Val := assigned(Space,X) - - Val := min(Space,X) - Val := max(Space,X) - Val := med(Space,X) - Val := val(Space,X) - Val := size(Space,X) - Val := width(Space,X) - Val := regret_min(Space,X) - Val := regret_max(Space,X) - - Val := glbSize(Space,V) - Val := lubSize(Space,V) - Val := unknownSize(Space,V) - Val := cardMin(Space,V) - Val := cardMax(Space,V) - Val := lubMin(Space,V) - Val := lubMax(Space,V) - Val := glbMin(Space,V) - Val := glbMax(Space,V) - Val := glb_ranges(Space,V) - Val := lub_ranges(Space,V) - Val := unknown_ranges(Space,V) - Val := glb_values(Space,V) - Val := lub_values(Space,V) - Val := unknown_values(Space,V) -~~~~~ - -+ DISJUNCTORS - -Disjunctors provide support for disjunctions of clauses, where each clause is a -conjunction of constraints: - -~~~~~{.prolog} - C1 or C2 or ... or Cn -~~~~~ - -Each clause is executed "speculatively": this means it does not affect the main -space. When a clause becomes failed, it is discarded. When only one clause -remains, it is committed: this means that it now affects the main space. - -Example: - -Consider the problem where either X=Y=0 or X=Y+(1 or 2) for variable X and Y -that take values in 0..3. - -~~~~~{.prolog} - Space := space, - [X,Y] := intvars(Space,2,0,3), -~~~~~ - -First, we must create a disjunctor as a manager for our 2 clauses: - -~~~~~{.prolog} - Disj := disjunctor(Space), -~~~~~ - -We can now create our first clause: - -~~~~~{.prolog} - C1 := clause(Disj), -~~~~~ - -This clause wants to constrain X and Y to 0. However, since it must be -executed "speculatively", it must operate on new variables X1 and Y1 that -shadow X and Y: - -~~~~~{.prolog} - [X1,Y1] := intvars(C1,2,0,3), - C1 += forward([X,Y],[X1,Y1]), -~~~~~ - -The forward(...) stipulation indicates which global variable is shadowed by -which clause-local variable. Now we can post the speculative clause-local -constraints for X=Y=0: - -~~~~~{.prolog} - C1 += rel(X1,'IRT_EQ',0), - C1 += rel(Y1,'IRT_EQ',0), -~~~~~ - -We now create the second clause which uses X2 and Y2 to shadow X and Y: - -~~~~~{.prolog} - C2 := clause(Disj), - [X2,Y2] := intvars(C2,2,0,3), - C2 += forward([X,Y],[X2,Y2]), -~~~~~ - -However, this clause also needs a clause-local variable Z2 taking values 1 or -2 in order to post the clause-local constraint X2=Y2+Z2: - -~~~~~{.prolog} - Z2 := intvar(C2,1,2), - C2 += linear([-1,1,1],[X2,Y2,Z2],'IRT_EQ',0), -~~~~~ - -Finally, we can branch and search: - -~~~~~{.prolog} - Space += branch([X,Y],'INT_VAR_SIZE_MIN','INT_VAL_MIN'), - SolSpace := search(Space), -~~~~~ - -and lookup values of variables in each solution: - -~~~~~{.prolog} - [X_,Y_] := val(SolSpace,[X,Y]). -~~~~~ - - - - - */ - -/** @defgroup Gecode_and_ClPbBFDbC Programming Finite Domain Constraints in YAP/Gecode -@ingroup Gecode -@{ - -The gecode/clp(fd) interface is designed to use the GECODE functionality -in a more CLP like style. It requires - -~~~~~{.prolog} -:- use_module(library(gecode/clpfd)). -~~~~~ -Several example programs are available with the distribution. - -Integer variables are declared as: - -+ _V_ in _A_.. _B_ -declares an integer variable _V_ with range _A_ to _B_. -+ _Vs_ ins _A_.. _B_ -declares a set of integer variabless _Vs_ with range _A_ to _B_. -+ boolvar( _V_) -declares a boolean variable. -+ boolvars( _Vs_) -declares a set of boolean variable. - - -Constraints supported are: - - -*/ - -/** @pred _X_ #= _Y_ is semidet -equality - -*/ - -/** @pred _X_ #\= _Y_ is semidet -disequality - -*/ - -/** @pred _X_ #> _Y_ is semidet -larger - -*/ - -/** @pred _X_ #>= _Y_ is semidet -larger or equal - -*/ - -/** @pred _X_ #=< _Y_ is semidet -smaller - -*/ - -/** @pred _X_ #< _Y_ is semidet -smaller or equal - -Arguments to this constraint may be an arithmetic expression with +, --, \\*, integer division /, min, max, sum, -count, and -abs. Boolean variables support conjunction (/\), disjunction (\/), -implication (=>), equivalence (<=>), and xor. The sum constraint allows a two argument version using the -`where` conditional, in Zinc style. - -The send more money equation may be written as: - -~~~~~{.prolog} - 1000*S + 100*E + 10*N + D + - 1000*M + 100*O + 10*R + E #= -10000*M + 1000*O + 100*N + 10*E + Y, -~~~~~ - -This example uses `where` to select from -column _I_ the elements that have value under _M_: - -~~~~~{.prolog} -OutFlow[I] #= sum(J in 1..N where D[J,I]count constraint counts the number of elements that match a -certain constant or variable (integer sets are not available). - - -*/ - -/** @pred all_different( _Vs_ ) - -Verifies whether all elements of a list are different. -*/ - -/** @pred all_distinct( _Cs_, _Vs_) - -verifies whether all elements of a list are different. Also tests if -all the sums between a list of constants and a list of variables are -different. - -This is a formulation of the queens problem that uses both versions of `all_different`: - -~~~~~{.prolog} -queens(N, Queens) :- - length(Queens, N), - Queens ins 1..N, - all_distinct(Queens), - foldl(inc, Queens, Inc, 0, _), % [0, 1, 2, .... ] - foldl(dec, Queens, Dec, 0, _), % [0, -1, -2, ... ] - all_distinct(Inc,Queens), - all_distinct(Dec,Queens), - labeling([], Queens). - -inc(_, I0, I0, I) :- - I is I0+1. - -dec(_, I0, I0, I) :- - I is I0-1. -~~~~~ - -The next example uses `all_different/1` and the functionality of the matrix package to verify that all squares in -sudoku have a different value: - -~~~~~{.prolog} - foreach( [I,J] ins 0..2 , - all_different(M[I*3+(0..2),J*3+(0..2)]) ), -~~~~~ - - -*/ - -/** @pred scalar_product(+ _Cs_, + _Vs_, + _Rel_, ? _V_ ) - -The product of constant _Cs_ by _Vs_ must be in relation - _Rel_ with _V_ . - - -*/ - -/** @pred _X_ #= is det -all elements of _X_ must take the same value - -*/ - -/** @pred _X_ #\= is det -not all elements of _X_ take the same value - -*/ - -/** @pred _X_ #> is det -elements of _X_ must be increasing - -*/ - -/** @pred _X_ #>= is det -elements of _X_ must be increasinga or equal - -*/ - -/** @pred _X_ #=< is det -elements of _X_ must be decreasing - -*/ - -/** @pred _X_ #< is det -elements of _X_ must be decreasing or equal - - -*/ - -/** @pred _X_ #<==> _B_ is det -reified equivalence - -*/ - -/** @pred _X_ #==> _B_ is det -Reified implication - -*/ - -/** @pred _X_ #< _B_ is det -reified implication - -As an example. consider finding out the people who wanted to sit -next to a friend and that are are actually sitting together: - -~~~~~{.prolog} -preference_satisfied(X-Y, B) :- - abs(X - Y) #= 1 #<==> B. -~~~~~ -Note that not all constraints may be reifiable. - - -*/ - -/** @pred element( _X_, _Vs_ ) - _X_ is an element of list _Vs_ - - -*/ - -/** @pred clause( _Type_, _Ps_ , _Ns_, _V_ ) -If _Type_ is `and` it is the conjunction of boolean variables - _Ps_ and the negation of boolean variables _Ns_ and must have -result _V_. If _Type_ is `or` it is a disjunction. - -+ DFA -the interface allows creating and manipulation deterministic finite -automata. A DFA has a set of states, represented as integers -and is initialised with an initial state, a set of transitions from the -first to the last argument emitting the middle argument, and a final -state. - -The swedish-drinkers protocol is represented as follows: - -~~~~~{.prolog} - A = [X,Y,Z], - dfa( 0, [t(0,0,0),t(0,1,1),t(1,0,0),t(-1,0,0)], [0], C), - in_dfa( A, C ), -~~~~~ -This code will enumeratae the valid tuples of three emissions. - -+ extensional constraints -Constraints can also be represented as lists of tuples. - -The previous example -would be written as: - -~~~~~{.prolog} - extensional_constraint([[0,0,0],[0,1,0],[1,0,0]], C), - in_relation( A, C ), -~~~~~ - - -*/ - -/** @pred minimum( _X_, _Vs_) - -*/ - -/** @pred min( _X_, _Vs_) -First Argument is the least element of a list. - - -*/ - -/** @pred maximum( _X_, _Vs_) - -*/ - -/** @pred max( _X_, _Vs_) -First Argument is the greatest element of a list. - -+ lex_order( _Vs_) -All elements must be ordered. - - - -The following predicates control search: - - -*/ - -/** @pred labeling( _Opts_, _Xs_) -performs labeling, several variable and value selection options are -available. The defaults are `min` and `min_step`. - -Variable selection options are as follows: - -+ leftmost -choose the first variable -+ min -choose one of the variables with smallest minimum value -+ max -choose one of the variables with greatest maximum value -+ ff -choose one of the most constrained variables, that is, with the smallest -domain. - - -Given that we selected a variable, the values chosen for branching may -be: - -+ min_step -smallest value -+ max_step -largest value -+ bisect -median -+ enum -all value starting from the minimum. - - - -*/ - -/** @pred maximize( _V_) -maximise variable _V_ - - -*/ - -/** @pred minimize(V) -minimise variable _V_ - - - - - */ - -/** @defgroup Heaps Heaps -@ingroup library -@{ - -A heap is a labelled binary tree where the key of each node is less than -or equal to the keys of its sons. The point of a heap is that we can -keep on adding new elements to the heap and we can keep on taking out -the minimum element. If there are N elements total, the total time is -O(NlgN). If you know all the elements in advance, you are better off -doing a merge-sort, but this file is for when you want to do say a -best-first search, and have no idea when you start how many elements -there will be, let alone what they are. - -The following heap manipulation routines are available once included -with the `use_module(library(heaps))` command. - - - - @pred add_to_heap(+ _Heap_,+ _key_,+ _Datum_,- _NewHeap_) - - -Inserts the new _Key-Datum_ pair into the heap. The insertion is not -stable, that is, if you insert several pairs with the same _Key_ it -is not defined which of them will come out first, and it is possible for -any of them to come out first depending on the history of the heap. - - -*/ - -/** @pred empty_heap(? _Heap_) - - -Succeeds if _Heap_ is an empty heap. - - -*/ - -/** @pred get_from_heap(+ _Heap_,- _key_,- _Datum_,- _Heap_) - - -Returns the _Key-Datum_ pair in _OldHeap_ with the smallest - _Key_, and also a _Heap_ which is the _OldHeap_ with that -pair deleted. - - -*/ - -/** @pred heap_size(+ _Heap_, - _Size_) - - -Reports the number of elements currently in the heap. - - -*/ - -/** @pred heap_to_list(+ _Heap_, - _List_) - - -Returns the current set of _Key-Datum_ pairs in the _Heap_ as a - _List_, sorted into ascending order of _Keys_. - - -*/ - -/** @pred list_to_heap(+ _List_, - _Heap_) - - -Takes a list of _Key-Datum_ pairs (such as keysort could be used to sort) -and forms them into a heap. - - -*/ - -/** @pred min_of_heap(+ _Heap_, - _Key_, - _Datum_) - - -Returns the Key-Datum pair at the top of the heap (which is of course -the pair with the smallest Key), but does not remove it from the heap. - - -*/ - -/** @pred min_of_heap(+ _Heap_, - _Key1_, - _Datum1_, -- _Key2_, - _Datum2_) - -Returns the smallest (Key1) and second smallest (Key2) pairs in the -heap, without deleting them. - - - - */ - -/** @defgroup Lists List Manipulation -@ingroup library -@{ - -The following list manipulation routines are available once included -with the `use_module(library(lists))` command. - - - - @pred append(? _Prefix_,? _Suffix_,? _Combined_) - - -True when all three arguments are lists, and the members of - _Combined_ are the members of _Prefix_ followed by the members of _Suffix_. -It may be used to form _Combined_ from a given _Prefix_, _Suffix_ or to take -a given _Combined_ apart. - - -*/ - -/** @pred append(? _Lists_,? _Combined_) - -Holds if the lists of _Lists_ can be concatenated as a - _Combined_ list. - - -*/ - -/** @pred delete(+ _List_, ? _Element_, ? _Residue_) - - -True when _List_ is a list, in which _Element_ may or may not -occur, and _Residue_ is a copy of _List_ with all elements -identical to _Element_ deleted. - - -*/ - -/** @pred flatten(+ _List_, ? _FlattenedList_) - - -Flatten a list of lists _List_ into a single list - _FlattenedList_. - -~~~~~{.prolog} -?- flatten([[1],[2,3],[4,[5,6],7,8]],L). - -L = [1,2,3,4,5,6,7,8] ? ; - -no -~~~~~ - - -*/ - -/** @pred last(+ _List_,? _Last_) - - -True when _List_ is a list and _Last_ is identical to its last element. - - -*/ - -/** @pred list_concat(+ _Lists_,? _List_) - - -True when _Lists_ is a list of lists and _List_ is the -concatenation of _Lists_. - - -*/ - -/** @pred member(? _Element_, ? _Set_) - - -True when _Set_ is a list, and _Element_ occurs in it. It may be used -to test for an element or to enumerate all the elements by backtracking. - - -*/ - -/** @pred memberchk(+ _Element_, + _Set_) - - -As member/2, but may only be used to test whether a known - _Element_ occurs in a known Set. In return for this limited use, it -is more efficient when it is applicable. - - -*/ - -/** @pred nth0(? _N_, ? _List_, ? _Elem_) - - -True when _Elem_ is the Nth member of _List_, -counting the first as element 0. (That is, throw away the first -N elements and unify _Elem_ with the next.) It can only be used to -select a particular element given the list and index. For that -task it is more efficient than member/2 - - -*/ - -/** @pred nth1(? _N_, ? _List_, ? _Elem_) - - -The same as nth0/3, except that it counts from -1, that is `nth(1, [H|_], H)`. - - -*/ - -/** @pred nth(? _N_, ? _List_, ? _Elem_) - - -The same as nth1/3. - - -*/ - -/** @pred nth0(? _N_, ? _List_, ? _Elem_, ? _Rest_) - -Unifies _Elem_ with the Nth element of _List_, -counting from 0, and _Rest_ with the other elements. It can be used -to select the Nth element of _List_ (yielding _Elem_ and _Rest_), or to -insert _Elem_ before the Nth (counting from 1) element of _Rest_, when -it yields _List_, e.g. `nth0(2, List, c, [a,b,d,e])` unifies List with -`[a,b,c,d,e]`. `nth/4` is the same except that it counts from 1. `nth0/4` -can be used to insert _Elem_ after the Nth element of _Rest_. - - -*/ - -/** @pred nth1(? _N_, ? _List_, ? _Elem_, ? _Rest_) - -Unifies _Elem_ with the Nth element of _List_, counting from 1, -and _Rest_ with the other elements. It can be used to select the -Nth element of _List_ (yielding _Elem_ and _Rest_), or to -insert _Elem_ before the Nth (counting from 1) element of - _Rest_, when it yields _List_, e.g. `nth(3, List, c, [a,b,d,e])` unifies List with `[a,b,c,d,e]`. `nth/4` -can be used to insert _Elem_ after the Nth element of _Rest_. - - -*/ - -/** @pred nth(? _N_, ? _List_, ? _Elem_, ? _Rest_) - -Same as `nth1/4`. - - -*/ - -/** @pred permutation(+ _List_,? _Perm_) - - -True when _List_ and _Perm_ are permutations of each other. - - -*/ - -/** @pred remove_duplicates(+ _List_, ? _Pruned_) - - -Removes duplicated elements from _List_. Beware: if the _List_ has -non-ground elements, the result may surprise you. - - -*/ - -/** @pred reverse(+ _List_, ? _Reversed_) - - -True when _List_ and _Reversed_ are lists with the same elements -but in opposite orders. - - -*/ - -/** @pred same_length(? _List1_, ? _List2_) - - -True when _List1_ and _List2_ are both lists and have the same number -of elements. No relation between the values of their elements is -implied. -Modes `same_length(-,+)` and `same_length(+,-)` generate either list given -the other; mode `same_length(-,-)` generates two lists of the same length, -in which case the arguments will be bound to lists of length 0, 1, 2, ... - - -*/ - -/** @pred select(? _Element_, ? _List_, ? _Residue_) - - -True when _Set_ is a list, _Element_ occurs in _List_, and - _Residue_ is everything in _List_ except _Element_ (things -stay in the same order). - - -*/ - -/** @pred selectchk(? _Element_, ? _List_, ? _Residue_) - - -Semi-deterministic selection from a list. Steadfast: defines as - -~~~~~{.prolog} -selectchk(Elem, List, Residue) :- - select(Elem, List, Rest0), !, - Rest = Rest0. -~~~~~ - - -*/ - -/** @pred sublist(? _Sublist_, ? _List_) - - -True when both `append(_,Sublist,S)` and `append(S,_,List)` hold. - - -*/ - -/** @pred suffix(? _Suffix_, ? _List_) - - -Holds when `append(_,Suffix,List)` holds. - - -*/ - -/** @pred sum_list(? _Numbers_, ? _Total_) - - -True when _Numbers_ is a list of numbers, and _Total_ is their sum. - - -*/ - -/** @pred sum_list(? _Numbers_, + _SoFar_, ? _Total_) - -True when _Numbers_ is a list of numbers, and _Total_ is the sum of their total plus _SoFar_. - - -*/ - -/** @pred sumlist(? _Numbers_, ? _Total_) - - -True when _Numbers_ is a list of integers, and _Total_ is their -sum. The same as sum_list/2, please do use sum_list/2 -instead. - - -*/ - -/** @pred max_list(? _Numbers_, ? _Max_) - - -True when _Numbers_ is a list of numbers, and _Max_ is the maximum. - - -*/ - -/** @pred min_list(? _Numbers_, ? _Min_) - - -True when _Numbers_ is a list of numbers, and _Min_ is the minimum. - - -*/ - -/** @pred numlist(+ _Low_, + _High_, + _List_) - - -If _Low_ and _High_ are integers with _Low_ =< - _High_, unify _List_ to a list `[Low, Low+1, ...High]`. See -also between/3. - - -*/ - -/** @pred intersection(+ _Set1_, + _Set2_, + _Set3_) - - -Succeeds if _Set3_ unifies with the intersection of _Set1_ and - _Set2_. _Set1_ and _Set2_ are lists without duplicates. They -need not be ordered. - - -*/ - -/** @pred subtract(+ _Set_, + _Delete_, ? _Result_) - - -Delete all elements from _Set_ that occur in _Delete_ (a set) -and unify the result with _Result_. Deletion is based on -unification using memberchk/2. The complexity is -`|Delete|\*|Set|`. - -See ord_subtract/3. - - - - */ - -/** @defgroup LineUtilities Line Manipulation Utilities -@ingroup library -@{ - -This package provides a set of useful predicates to manipulate -sequences of characters codes, usually first read in as a line. It is -available by loading the library `library(lineutils)`. - - - - @pred search_for(+ _Char_,+ _Line_) - - - -Search for a character _Char_ in the list of codes _Line_. - - -*/ - -/** @pred search_for(+ _Char_,+ _Line_,- _RestOfine_) - - -Search for a character _Char_ in the list of codes _Line_, - _RestOfLine_ has the line to the right. - - -*/ - -/** @pred scan_natural(? _Nat_,+ _Line_,+ _RestOfLine_) - - - -Scan the list of codes _Line_ for a natural number _Nat_, zero -or a positive integer, and unify _RestOfLine_ with the remainder -of the line. - - -*/ - -/** @pred scan_integer(? _Int_,+ _Line_,+ _RestOfLine_) - - - -Scan the list of codes _Line_ for an integer _Nat_, either a -positive, zero, or negative integer, and unify _RestOfLine_ with -the remainder of the line. - - -*/ - -/** @pred split(+ _Line_,+ _Separators_,- _Split_) - - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the character codes in _Separators_ as separators. As an -example, consider: - -~~~~~{.prolog} -?- split("Hello * I am free"," *",S). - -S = ["Hello","I","am","free"] ? - -no -~~~~~ - - -*/ - -/** @pred split(+ _Line_,- _Split_) - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the blank characters as separators. - - -*/ - -/** @pred fields(+ _Line_,+ _Separators_,- _Split_) - - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the character codes in _Separators_ as separators for -fields. If two separators occur in a row, the field is considered -empty. As an example, consider: - -~~~~~{.prolog} -?- fields("Hello I am free"," *",S). - -S = ["Hello","","I","am","","free"] ? -~~~~~ - - -*/ - -/** @pred fields(+ _Line_,- _Split_) - - -Unify _Words_ with a set of strings obtained from _Line_ by -using the blank characters as field separators. - - -*/ - -/** @pred glue(+ _Words_,+ _Separator_,- _Line_) - - - -Unify _Line_ with string obtained by glueing _Words_ with -the character code _Separator_. - - -*/ - -/** @pred copy_line(+ _StreamInput_,+ _StreamOutput_) - - - -Copy a line from _StreamInput_ to _StreamOutput_. - - -*/ - -/** @pred process(+ _StreamInp_, + _Goal_) - - - -For every line _LineIn_ in stream _StreamInp_, call -`call(Goal,LineIn)`. - - -*/ - -/** @pred filter(+ _StreamInp_, + _StreamOut_, + _Goal_) - - - -For every line _LineIn_ in stream _StreamInp_, execute -`call(Goal,LineIn,LineOut)`, and output _LineOut_ to -stream _StreamOut_. - - -*/ - -/** @pred file_filter(+ _FileIn_, + _FileOut_, + _Goal_) - - - -For every line _LineIn_ in file _FileIn_, execute -`call(Goal,LineIn,LineOut)`, and output _LineOut_ to file - _FileOut_. - - -*/ - -/** @pred file_filter_with_initialization(+ _FileIn_, + _FileOut_, + _Goal_, + _FormatCommand_, + _Arguments_) - - -Same as file_filter/3, but before starting the filter execute -`format/3` on the output stream, using _FormatCommand_ and - _Arguments_. - - - - - */ - -/** @defgroup matrix Matrix Library -@ingroup library -@{ - -This package provides a fast implementation of multi-dimensional -matrices of integers and floats. In contrast to dynamic arrays, these -matrices are multi-dimensional and compact. In contrast to static -arrays. these arrays are allocated in the stack. Matrices are available -by loading the library `library(matrix)`. They are multimensional -objects of type: - -+ terms: Prolog terms -+ ints: bounded integers, represented as an opaque term. The -maximum integer depends on hardware, but should be obtained from the -natural size of the machine. -+ floats: floating-poiny numbers, represented as an opaque term. - - -Matrix elements can be accessed through the `matrix_get/2` -predicate or through an R-inspired access notation (that uses the ciao -style extension to `[]`. Examples include: - - -+ Access the second row, third column of matrix X. Indices start from -`0`, -~~~~ - _E_ <== _X_[2,3] -~~~~ - -+ Access all the second row, the output is a list ofe elements. -~~~~ - _L_ <== _X_[2,_] -~~~~ - -+ Access all the second, thrd and fourth rows, the output is a list of elements. -~~~~ - _L_ <== _X_[2..4,_] -~~~~ - -+ Access all the fifth, sixth and eight rows, the output is a list of elements. -~~~~ - _L_ <== _X_[2..4+3,_] -~~~~ - -The matrix library also supports a B-Prolog/ECliPSe inspired `foreach`iterator to iterate over -elements of a matrix: - -+ Copy a vector, element by element. - -~~~~ - foreach(I in 0..N1, X[I] <== Y[I]) -~~~~ - -+ The lower-triangular matrix _Z_ is the difference between the -lower-triangular and upper-triangular parts of _X_. - -~~~~ - foreach([I in 0..N1, J in I..N1], Z[I,J] <== X[I,J] - X[I,J]) -~~~~ - -+ Add all elements of a matrix by using _Sum_ as an accumulator. - -~~~~ - foreach([I in 0..N1, J in 0..N1], plus(X[I,J]), 0, Sum) -~~~~ - - Notice that the library does not support all known matrix operations. Please -contact the YAP maintainers if you require extra functionality. - - - -+ _X_ = array[ _Dim1_,..., _Dimn_] of _Objects_ - The of/2 operator can be used to create a new array of - _Objects_. The objects supported are: - - + `Unbound Variable` - create an array of free variables - + `ints ` - create an array of integers - + `floats ` - create an array of floating-point numbers - + `_I_: _J_` - create an array with integers from _I_ to _J_ - + `[..]` - create an array from the values in a list - -The dimensions can be given as an integer, and the matrix will be -indexed `C`-style from `0..( _Max_-1)`, or can be given -as an interval ` _Base_.. _Limit_`. In the latter case, -matrices of integers and of floating-point numbers should have the same - _Base_ on every dimension. - - -*/ - -/** @pred ?_LHS_ <== ?_RHS_ is semidet - - -General matrix assignment operation. It evaluates the right-hand side -and then acts different according to the -left-hand side and to the matrix: - -+ if _LHS_ is part of an integer or floating-point matrix, -perform non-backtrackable assignment. -+ other unify left-hand side and right-hand size. - - -The right-hand side supports the following operators: - -+ `[]/2` - - written as _M_[ _Offset_]: obtain an element or list of elements -of matrix _M_ at offset _Offset_. - -+ `matrix/1` - - create a vector from a list - -+ `matrix/2` - - create a matrix from a list. Options are: - + dim= -a list of dimensions - + type= -integers, floating-point or terms - + base= -a list of base offsets per dimension (all must be the same for arrays of -integers and floating-points - -+ `matrix/3` - - create matrix giving two options - - + `dim/1` - list with matrix dimensions - - + `nrow/1` - number of rows in bi-dimensional matrix - -+ `ncol/1` - number of columns in bi-dimensional matrix - -+ `length/1` - size of a matrix - -+ `size/1` - size of a matrix - -+ `max/1` - - maximum element of a numeric matrix - -+ `maxarg/1` - - argument of maximum element of a numeric matrix - -+ `min/1` - - minimum element of a numeric matrix - -+ `minarg/1` - - argument of minimum element of a numeric matrix - -+ `list/1` - - represent matrix as a list - -+ `lists/2` - - represent matrix as list of embedded lists - -+ `../2` - - _I_.. _J_ generates a list with all integers from _I_ to - _J_, included. - -+ `+/2` - - add two numbers, add two matrices element-by-element, or add a number to -all elements of a matrix or list. - -+ `-/2 ` - - subtract two numbers, subtract two matrices or lists element-by-element, or subtract a number from -all elements of a matrix or list - -+ `* /2` - - multiply two numbers, multiply two matrices or lists element-by-element, or multiply a number from -all elements of a matrix or list - - + `log/1` - - natural logarithm of a number, matrix or list - -+ `exp/1 ` - - natural exponentiation of a number, matrix or list - -*/ - -/** @pred foreach( _Sequence_, _Goal_) - - -Deterministic iterator. The ranges are given by _Sequence_ that is -either ` _I_ in _M_.. _N_`, or of the form -`[ _I_, _J_] ins _M_.. _N_`, or a list of the above conditions. - -Variables in the goal are assumed to be global, ie, share a single value -in the execution. The exceptions are the iteration indices. Moreover, if -the goal is of the form ` _Locals_^ _G_` all variables -occurring in _Locals_ are marked as local. As an example: - -~~~~~{.prolog} -foreach([I,J] ins 1..N, A^(A <==M[I,J], N[I] <== N[I] + A*A) ) -~~~~~ -the variables _I_, _J_ and _A_ are duplicated for every -call (local), whereas the matrices _M_ and _N_ are shared -throughout the execution (global). - - -*/ - -/** @pred foreach( _Sequence_, _Goal_, _Acc0_, _AccF_) - -Deterministic iterator with accumulator style arguments. - - -*/ - -/** @pred matrix_new(+ _Type_,+ _Dims_,- _Matrix_) - - - -Create a new matrix _Matrix_ of type _Type_, which may be one of -`ints` or `floats`, and with a list of dimensions _Dims_. -The matrix will be initialised to zeros. - -~~~~~ -?- matrix_new(ints,[2,3],Matrix). - -Matrix = {..} -~~~~~ -Notice that currently YAP will always write a matrix of numbers as `{..}`. - - -*/ - -/** @pred matrix_new(+ _Type_,+ _Dims_,+ _List_,- _Matrix_) - - -Create a new matrix _Matrix_ of type _Type_, which may be one of -`ints` or `floats`, with dimensions _Dims_, and -initialised from list _List_. - - -*/ - -/** @pred matrix_new_set(? _Dims_,+ _OldMatrix_,+ _Value_,- _NewMatrix_) - - - -Create a new matrix _NewMatrix_ of type _Type_, with dimensions - _Dims_. The elements of _NewMatrix_ are set to _Value_. - - -*/ - -/** @pred matrix_dims(+ _Matrix_,- _Dims_) - - - -Unify _Dims_ with a list of dimensions for _Matrix_. - - -*/ - -/** @pred matrix_ndims(+ _Matrix_,- _Dims_) - - - -Unify _NDims_ with the number of dimensions for _Matrix_. - - -*/ - -/** @pred matrix_size(+ _Matrix_,- _NElems_) - - - -Unify _NElems_ with the number of elements for _Matrix_. - - -*/ - -/** @pred matrix_type(+ _Matrix_,- _Type_) - - - -Unify _NElems_ with the type of the elements in _Matrix_. - - -*/ - -/** @pred matrix_to_list(+ _Matrix_,- _Elems_) - - - -Unify _Elems_ with the list including all the elements in _Matrix_. - - -*/ - -/** @pred matrix_get(+ _Matrix_,+ _Position_,- _Elem_) - - - -Unify _Elem_ with the element of _Matrix_ at position - _Position_. - - -*/ - -/** @pred matrix_get(+ _Matrix_[+ _Position_],- _Elem_) - - -Unify _Elem_ with the element _Matrix_[ _Position_]. - - -*/ - -/** @pred matrix_set(+ _Matrix_,+ _Position_,+ _Elem_) - - - -Set the element of _Matrix_ at position - _Position_ to _Elem_. - - -*/ - -/** @pred matrix_set(+ _Matrix_[+ _Position_],+ _Elem_) - - -Set the element of _Matrix_[ _Position_] to _Elem_. - - -*/ - -/** @pred matrix_set_all(+ _Matrix_,+ _Elem_) - - - -Set all element of _Matrix_ to _Elem_. - - -*/ - -/** @pred matrix_add(+ _Matrix_,+ _Position_,+ _Operand_) - - - -Add _Operand_ to the element of _Matrix_ at position - _Position_. - - -*/ - -/** @pred matrix_inc(+ _Matrix_,+ _Position_) - - - -Increment the element of _Matrix_ at position _Position_. - - -*/ - -/** @pred matrix_inc(+ _Matrix_,+ _Position_,- _Element_) - - -Increment the element of _Matrix_ at position _Position_ and -unify with _Element_. - - -*/ - -/** @pred matrix_dec(+ _Matrix_,+ _Position_) - - - -Decrement the element of _Matrix_ at position _Position_. - - -*/ - -/** @pred matrix_dec(+ _Matrix_,+ _Position_,- _Element_) - - -Decrement the element of _Matrix_ at position _Position_ and -unify with _Element_. - - -*/ - -/** @pred matrix_arg_to_offset(+ _Matrix_,+ _Position_,- _Offset_) - - - -Given matrix _Matrix_ return what is the numerical _Offset_ of -the element at _Position_. - - -*/ - -/** @pred matrix_offset_to_arg(+ _Matrix_,- _Offset_,+ _Position_) - - - -Given a position _Position _ for matrix _Matrix_ return the -corresponding numerical _Offset_ from the beginning of the matrix. - - -*/ - -/** @pred matrix_max(+ _Matrix_,+ _Max_) - - - -Unify _Max_ with the maximum in matrix _Matrix_. - - -*/ - -/** @pred matrix_maxarg(+ _Matrix_,+ _Maxarg_) - - - -Unify _Max_ with the position of the maximum in matrix _Matrix_. - - -*/ - -/** @pred matrix_min(+ _Matrix_,+ _Min_) - - - -Unify _Min_ with the minimum in matrix _Matrix_. - - -*/ - -/** @pred matrix_minarg(+ _Matrix_,+ _Minarg_) - - - -Unify _Min_ with the position of the minimum in matrix _Matrix_. - - -*/ - -/** @pred matrix_sum(+ _Matrix_,+ _Sum_) - - - -Unify _Sum_ with the sum of all elements in matrix _Matrix_. - - -*/ - -/** @pred matrix_agg_lines(+ _Matrix_,+Operator,+ _Aggregate_) - - - -If _Matrix_ is a n-dimensional matrix, unify _Aggregate_ with -the n-1 dimensional matrix where each element is obtained by adding all -_Matrix_ elements with same last n-1 index. Currently, only addition is supported. - - -*/ - -/** @pred matrix_agg_cols(+ _Matrix_,+Operator,+ _Aggregate_) - - - -If _Matrix_ is a n-dimensional matrix, unify _Aggregate_ with -the one dimensional matrix where each element is obtained by adding all -Matrix elements with same first index. Currently, only addition is supported. - - -*/ - -/** @pred matrix_op(+ _Matrix1_,+ _Matrix2_,+ _Op_,- _Result_) - - - - _Result_ is the result of applying _Op_ to matrix _Matrix1_ -and _Matrix2_. Currently, only addition (`+`) is supported. - - -*/ - -/** @pred matrix_op_to_all(+ _Matrix1_,+ _Op_,+ _Operand_,- _Result_) - - - - _Result_ is the result of applying _Op_ to all elements of - _Matrix1_, with _Operand_ as the second argument. Currently, -only addition (`+`), multiplication (`\*`), and division -(`/`) are supported. - - -*/ - -/** @pred matrix_op_to_lines(+ _Matrix1_,+ _Lines_,+ _Op_,- _Result_) - - - - _Result_ is the result of applying _Op_ to all elements of - _Matrix1_, with the corresponding element in _Lines_ as the -second argument. Currently, only division (`/`) is supported. - - -*/ - -/** @pred matrix_op_to_cols(+ _Matrix1_,+ _Cols_,+ _Op_,- _Result_) - - - - _Result_ is the result of applying _Op_ to all elements of - _Matrix1_, with the corresponding element in _Cols_ as the -second argument. Currently, only addition (`+`) is -supported. Notice that _Cols_ will have n-1 dimensions. - - -*/ - -/** @pred matrix_shuffle(+ _Matrix_,+ _NewOrder_,- _Shuffle_) - - - -Shuffle the dimensions of matrix _Matrix_ according to - _NewOrder_. The list _NewOrder_ must have all the dimensions of - _Matrix_, starting from 0. - - -*/ - -/** @pred matrix_transpose(+ _Matrix_,- _Transpose_) - - - -Transpose matrix _Matrix_ to _Transpose_. Equivalent to: - -~~~~~ -matrix_transpose(Matrix,Transpose) :- - matrix_shuffle(Matrix,[1,0],Transpose). -~~~~~ - - -*/ - -/** @pred matrix_expand(+ _Matrix_,+ _NewDimensions_,- _New_) - - - -Expand _Matrix_ to occupy new dimensions. The elements in - _NewDimensions_ are either 0, for an existing dimension, or a -positive integer with the size of the new dimension. - - -*/ - -/** @pred matrix_select(+ _Matrix_,+ _Dimension_,+ _Index_,- _New_) - - - -Select from _Matrix_ the elements who have _Index_ at - _Dimension_. - - -*/ - -/** @pred matrix_column(+ _Matrix_,+ _Column_,- _NewMatrix_) - - - -Select from _Matrix_ the column matching _Column_ as new matrix _NewMatrix_. _Column_ must have one less dimension than the original matrix. - - - - */ - -/** @defgroup MATLAB MATLAB Package Interface -@ingroup library -@{ - -The MathWorks MATLAB is a widely used package for array -processing. YAP now includes a straightforward interface to MATLAB. To -actually use it, you need to install YAP calling `configure` with -the `--with-matlab=DIR` option, and you need to call -`use_module(library(lists))` command. - -Accessing the matlab dynamic libraries can be complicated. In Linux -machines, to use this interface, you may have to set the environment -variable LD_LIBRARY_PATH. Next, follows an example using bash in a -64-bit Linux PC: - -~~~~~ -export LD_LIBRARY_PATH=''$MATLAB_HOME"/sys/os/glnxa64:''$MATLAB_HOME"/bin/glnxa64:''$LD_LIBRARY_PATH" -~~~~~ -where `MATLAB_HOME` is the directory where matlab is installed -at. Please replace `ax64` for `x86` on a 32-bit PC. - - - - @pred start_matlab(+ _Options_) - - -Start a matlab session. The argument _Options_ may either be the -empty string/atom or the command to call matlab. The command may fail. - - -*/ - -/** @pred close_matlab - - -Stop the current matlab session. - - -*/ - -/** @pred matlab_on - - -Holds if a matlab session is on. - - -*/ - -/** @pred matlab_eval_string(+ _Command_) - - -Holds if matlab evaluated successfully the command _Command_. - - -*/ - -/** @pred matlab_eval_string(+ _Command_, - _Answer_) - -MATLAB will evaluate the command _Command_ and unify _Answer_ -with a string reporting the result. - - -*/ - -/** @pred matlab_cells(+ _Size_, ? _Array_) - - -MATLAB will create an empty vector of cells of size _Size_, and if - _Array_ is bound to an atom, store the array in the matlab -variable with name _Array_. Corresponds to the MATLAB command `cells`. - - -*/ - -/** @pred matlab_cells(+ _SizeX_, + _SizeY_, ? _Array_) - -MATLAB will create an empty array of cells of size _SizeX_ and - _SizeY_, and if _Array_ is bound to an atom, store the array -in the matlab variable with name _Array_. Corresponds to the -MATLAB command `cells`. - - -*/ - -/** @pred matlab_initialized_cells(+ _SizeX_, + _SizeY_, + _List_, ? _Array_) - - -MATLAB will create an array of cells of size _SizeX_ and - _SizeY_, initialized from the list _List_, and if _Array_ -is bound to an atom, store the array in the matlab variable with name - _Array_. - - -*/ - -/** @pred matlab_matrix(+ _SizeX_, + _SizeY_, + _List_, ? _Array_) - - -MATLAB will create an array of floats of size _SizeX_ and _SizeY_, -initialized from the list _List_, and if _Array_ is bound to -an atom, store the array in the matlab variable with name _Array_. - - -*/ - -/** @pred matlab_set(+ _MatVar_, + _X_, + _Y_, + _Value_) - - -Call MATLAB to set element _MatVar_( _X_, _Y_) to - _Value_. Notice that this command uses the MATLAB array access -convention. - - -*/ - -/** @pred matlab_get_variable(+ _MatVar_, - _List_) - - -Unify MATLAB variable _MatVar_ with the List _List_. - - -*/ - -/** @pred matlab_item(+ _MatVar_, + _X_, ? _Val_) - - -Read or set MATLAB _MatVar_( _X_) from/to _Val_. Use -`C` notation for matrix access (ie, starting from 0). - - -*/ - -/** @pred matlab_item(+ _MatVar_, + _X_, + _Y_, ? _Val_) - -Read or set MATLAB _MatVar_( _X_, _Y_) from/to _Val_. Use -`C` notation for matrix access (ie, starting from 0). - - -*/ - -/** @pred matlab_item1(+ _MatVar_, + _X_, ? _Val_) - - -Read or set MATLAB _MatVar_( _X_) from/to _Val_. Use -MATLAB notation for matrix access (ie, starting from 1). - - -*/ - -/** @pred matlab_item1(+ _MatVar_, + _X_, + _Y_, ? _Val_) - -Read or set MATLAB _MatVar_( _X_, _Y_) from/to _Val_. Use -MATLAB notation for matrix access (ie, starting from 1). - - -*/ - -/** @pred matlab_sequence(+ _Min_, + _Max_, ? _Array_) - - -MATLAB will create a sequence going from _Min_ to _Max_, and -if _Array_ is bound to an atom, store the sequence in the matlab -variable with name _Array_. - - -*/ - -/** @pred matlab_vector(+ _Size_, + _List_, ? _Array_) - - -MATLAB will create a vector of floats of size _Size_, initialized -from the list _List_, and if _Array_ is bound to an atom, -store the array in the matlab variable with name _Array_. - - -*/ - -/** @pred matlab_zeros(+ _Size_, ? _Array_) - - -MATLAB will create a vector of zeros of size _Size_, and if - _Array_ is bound to an atom, store the array in the matlab -variable with name _Array_. Corresponds to the MATLAB command -`zeros`. - - -*/ - -/** @pred matlab_zeros(+ _SizeX_, + _SizeY_, ? _Array_) - -MATLAB will create an array of zeros of size _SizeX_ and - _SizeY_, and if _Array_ is bound to an atom, store the array -in the matlab variable with name _Array_. Corresponds to the -MATLAB command `zeros`. - - -*/ - -/** @pred matlab_zeros(+ _SizeX_, + _SizeY_, + _SizeZ_, ? _Array_) - -MATLAB will create an array of zeros of size _SizeX_, _SizeY_, -and _SizeZ_. If _Array_ is bound to an atom, store the array -in the matlab variable with name _Array_. Corresponds to the -MATLAB command `zeros`. - - - - - */ - -/** @defgroup NonhYBacktrackable_Data_Structures Non-Backtrackable Data Structures -@ingroup library -@{ - -The following routines implement well-known data-structures using global -non-backtrackable variables (implemented on the Prolog stack). The -data-structures currently supported are Queues, Heaps, and Beam for Beam -search. They are allowed through `library(nb)`. - - -*/ - -/** @pred nb_queue(- _Queue_) - - -Create a _Queue_. - - -*/ - -/** @pred nb_queue_close(+ _Queue_, - _Head_, ? _Tail_) - - -Unify the queue _Queue_ with a difference list - _Head_- _Tail_. The queue will now be empty and no further -elements can be added. - - -*/ - -/** @pred nb_queue_enqueue(+ _Queue_, + _Element_) - - -Add _Element_ to the front of the queue _Queue_. - - -*/ - -/** @pred nb_queue_dequeue(+ _Queue_, - _Element_) - - -Remove _Element_ from the front of the queue _Queue_. Fail if -the queue is empty. - - -*/ - -/** @pred nb_queue_peek(+ _Queue_, - _Element_) - - - _Element_ is the front of the queue _Queue_. Fail if -the queue is empty. - - -*/ - -/** @pred nb_queue_size(+ _Queue_, - _Size_) - - -Unify _Size_ with the number of elements in the queue _Queue_. - - -*/ - -/** @pred nb_queue_empty(+ _Queue_) - - -Succeeds if _Queue_ is empty. - - -*/ - -/** @pred nb_heap(+ _DefaultSize_,- _Heap_) - - -Create a _Heap_ with default size _DefaultSize_. Note that size -will expand as needed. - - -*/ - -/** @pred nb_heap_close(+ _Heap_) - - -Close the heap _Heap_: no further elements can be added. - - -*/ - -/** @pred nb_heap_add(+ _Heap_, + _Key_, + _Value_) - - -Add _Key_- _Value_ to the heap _Heap_. The key is sorted on - _Key_ only. - - -*/ - -/** @pred nb_heap_del(+ _Heap_, - _Key_, - _Value_) - - -Remove element _Key_- _Value_ with smallest _Value_ in heap - _Heap_. Fail if the heap is empty. - - -*/ - -/** @pred nb_heap_peek(+ _Heap_, - _Key_, - _Value_)) - - - _Key_- _Value_ is the element with smallest _Key_ in the heap - _Heap_. Fail if the heap is empty. - - -*/ - -/** @pred nb_heap_size(+ _Heap_, - _Size_) - - -Unify _Size_ with the number of elements in the heap _Heap_. - - -*/ - -/** @pred nb_heap_empty(+ _Heap_) - - -Succeeds if _Heap_ is empty. - - -*/ - -/** @pred nb_beam(+ _DefaultSize_,- _Beam_) - - -Create a _Beam_ with default size _DefaultSize_. Note that size -is fixed throughout. - - -*/ - -/** @pred nb_beam_close(+ _Beam_) - - -Close the beam _Beam_: no further elements can be added. - - -*/ - -/** @pred nb_beam_add(+ _Beam_, + _Key_, + _Value_) - - -Add _Key_- _Value_ to the beam _Beam_. The key is sorted on - _Key_ only. - - -*/ - -/** @pred nb_beam_del(+ _Beam_, - _Key_, - _Value_) - - -Remove element _Key_- _Value_ with smallest _Value_ in beam - _Beam_. Fail if the beam is empty. - - -*/ - -/** @pred nb_beam_peek(+ _Beam_, - _Key_, - _Value_)) - - - _Key_- _Value_ is the element with smallest _Key_ in the beam - _Beam_. Fail if the beam is empty. - - -*/ - -/** @pred nb_beam_size(+ _Beam_, - _Size_) - - -Unify _Size_ with the number of elements in the beam _Beam_. - - -*/ - -/** @pred nb_beam_empty(+ _Beam_) - - -Succeeds if _Beam_ is empty. - - - - - */ - -/** @defgroup Ordered_Sets Ordered Sets -@ingroup library -@{ - -The following ordered set manipulation routines are available once -included with the `use_module(library(ordsets))` command. An -ordered set is represented by a list having unique and ordered -elements. Output arguments are guaranteed to be ordered sets, if the -relevant inputs are. This is a slightly patched version of Richard -O'Keefe's original library. - - -*/ - -/** @pred list_to_ord_set(+ _List_, ? _Set_) - - -Holds when _Set_ is the ordered representation of the set -represented by the unordered representation _List_. - - -*/ - -/** @pred merge(+ _List1_, + _List2_, - _Merged_) - - -Holds when _Merged_ is the stable merge of the two given lists. - -Notice that merge/3 will not remove duplicates, so merging -ordered sets will not necessarily result in an ordered set. Use -`ord_union/3` instead. - - -*/ - -/** @pred ord_add_element(+ _Set1_, + _Element_, ? _Set2_) - - -Inserting _Element_ in _Set1_ returns _Set2_. It should give -exactly the same result as `merge(Set1, [Element], Set2)`, but a -bit faster, and certainly more clearly. The same as ord_insert/3. - - -*/ - -/** @pred ord_del_element(+ _Set1_, + _Element_, ? _Set2_) - - -Removing _Element_ from _Set1_ returns _Set2_. - - -*/ - -/** @pred ord_disjoint(+ _Set1_, + _Set2_) - - -Holds when the two ordered sets have no element in common. - - -*/ - -/** @pred ord_member(+ _Element_, + _Set_) - - -Holds when _Element_ is a member of _Set_. - - -*/ - -/** @pred ord_insert(+ _Set1_, + _Element_, ? _Set2_) - - -Inserting _Element_ in _Set1_ returns _Set2_. It should give -exactly the same result as `merge(Set1, [Element], Set2)`, but a -bit faster, and certainly more clearly. The same as ord_add_element/3. - - -*/ - -/** @pred ord_intersect(+ _Set1_, + _Set2_) - - -Holds when the two ordered sets have at least one element in common. - - -*/ - -/** @pred ord_intersection(+ _Set1_, + _Set2_, ? _Intersection_) - -Holds when Intersection is the ordered representation of _Set1_ -and _Set2_. - - -*/ - -/** @pred ord_intersection(+ _Set1_, + _Set2_, ? _Intersection_, ? _Diff_) - -Holds when Intersection is the ordered representation of _Set1_ -and _Set2_. _Diff_ is the difference between _Set2_ and _Set1_. - - -*/ - -/** @pred ord_seteq(+ _Set1_, + _Set2_) - - -Holds when the two arguments represent the same set. - - -*/ - -/** @pred ord_setproduct(+ _Set1_, + _Set2_, - _Set_) - - -If Set1 and Set2 are ordered sets, Product will be an ordered -set of x1-x2 pairs. - - -*/ - -/** @pred ord_subset(+ _Set1_, + _Set2_) - - -Holds when every element of the ordered set _Set1_ appears in the -ordered set _Set2_. - - -*/ - -/** @pred ord_subtract(+ _Set1_, + _Set2_, ? _Difference_) - - -Holds when _Difference_ contains all and only the elements of _Set1_ -which are not also in _Set2_. - - -*/ - -/** @pred ord_symdiff(+ _Set1_, + _Set2_, ? _Difference_) - - -Holds when _Difference_ is the symmetric difference of _Set1_ -and _Set2_. - - -*/ - -/** @pred ord_union(+ _Sets_, ? _Union_) - - -Holds when _Union_ is the union of the lists _Sets_. - - -*/ - -/** @pred ord_union(+ _Set1_, + _Set2_, ? _Union_) - -Holds when _Union_ is the union of _Set1_ and _Set2_. - - -*/ - -/** @pred ord_union(+ _Set1_, + _Set2_, ? _Union_, ? _Diff_) - -Holds when _Union_ is the union of _Set1_ and _Set2_ and - _Diff_ is the difference. - - - - - */ - -/** @defgroup Pseudo_Random Pseudo Random Number Integer Generator -@ingroup library -@{ - -The following routines produce random non-negative integers in the range -0 .. 2^(w-1) -1, where w is the word size available for integers, e.g. -32 for Intel machines and 64 for Alpha machines. Note that the numbers -generated by this random number generator are repeatable. This generator -was originally written by Allen Van Gelder and is based on Knuth Vol 2. - - -*/ - -/** @pred rannum(- _I_) - - -Produces a random non-negative integer _I_ whose low bits are not -all that random, so it should be scaled to a smaller range in general. -The integer _I_ is in the range 0 .. 2^(w-1) - 1. You can use: - -~~~~~ -rannum(X) :- yap_flag(max_integer,MI), rannum(R), X is R/MI. -~~~~~ -to obtain a floating point number uniformly distributed between 0 and 1. - - -*/ - -/** @pred ranstart - - -Initialize the random number generator using a built-in seed. The -ranstart/0 built-in is always called by the system when loading -the package. - - -*/ - -/** @pred ranstart(+ _Seed_) - -Initialize the random number generator with user-defined _Seed_. The -same _Seed_ always produces the same sequence of numbers. - - -*/ - -/** @pred ranunif(+ _Range_,- _I_) - - -ranunif/2 produces a uniformly distributed non-negative random -integer _I_ over a caller-specified range _R_. If range is _R_, -the result is in 0 .. _R_-1. - - - - - */ - -/** @defgroup Queues Queues -@ingroup library -@{ - -The following queue manipulation routines are available once -included with the `use_module(library(queues))` command. Queues are -implemented with difference lists. - - - - @pred make_queue(+ _Queue_) - - -Creates a new empty queue. It should only be used to create a new queue. - - -*/ - -/** @pred join_queue(+ _Element_, + _OldQueue_, - _NewQueue_) - - -Adds the new element at the end of the queue. - - -*/ - -/** @pred list_join_queue(+ _List_, + _OldQueue_, - _NewQueue_) - - -Ads the new elements at the end of the queue. - - -*/ - -/** @pred jump_queue(+ _Element_, + _OldQueue_, - _NewQueue_) - - -Adds the new element at the front of the list. - - -*/ - -/** @pred list_jump_queue(+ _List_, + _OldQueue_, + _NewQueue_) - - -Adds all the elements of _List_ at the front of the queue. - - -*/ - -/** @pred head_queue(+ _Queue_, ? _Head_) - - -Unifies Head with the first element of the queue. - - -*/ - -/** @pred serve_queue(+ _OldQueue_, + _Head_, - _NewQueue_) - - -Removes the first element of the queue for service. - - -*/ - -/** @pred empty_queue(+ _Queue_) - - -Tests whether the queue is empty. - - -*/ - -/** @pred length_queue(+ _Queue_, - _Length_) - - -Counts the number of elements currently in the queue. - - -*/ - -/** @pred list_to_queue(+ _List_, - _Queue_) - - -Creates a new queue with the same elements as _List._ - - -*/ - -/** @pred queue_to_list(+ _Queue_, - _List_) - - -Creates a new list with the same elements as _Queue_. - - - - - */ - -/** @defgroup Random Random Number Generator -@ingroup library -@{ - -The following random number operations are included with the -`use_module(library(random))` command. Since YAP-4.3.19 YAP uses -the O'Keefe public-domain algorithm, based on the "Applied Statistics" -algorithm AS183. - - - - @pred getrand(- _Key_) - - -Unify _Key_ with a term of the form `rand(X,Y,Z)` describing the -current state of the random number generator. - - -*/ - -/** @pred random(- _Number_) - - -Unify _Number_ with a floating-point number in the range `[0...1)`. - - -*/ - -/** @pred random(+ _LOW_, + _HIGH_, - _NUMBER_) - -Unify _Number_ with a number in the range -`[LOW...HIGH)`. If both _LOW_ and _HIGH_ are -integers then _NUMBER_ will also be an integer, otherwise - _NUMBER_ will be a floating-point number. - - -*/ - -/** @pred randseq(+ _LENGTH_, + _MAX_, - _Numbers_) - - -Unify _Numbers_ with a list of _LENGTH_ unique random integers -in the range `[1... _MAX_)`. - - -*/ - -/** @pred randset(+ _LENGTH_, + _MAX_, - _Numbers_) - - -Unify _Numbers_ with an ordered list of _LENGTH_ unique random -integers in the range `[1... _MAX_)`. - - -*/ - -/** @pred setrand(+ _Key_) - - -Use a term of the form `rand(X,Y,Z)` to set a new state for the -random number generator. The integer `X` must be in the range -`[1...30269)`, the integer `Y` must be in the range -`[1...30307)`, and the integer `Z` must be in the range -`[1...30323)`. - - - - - */ - -/** @defgroup Read_Utilities Read Utilities -@ingroup library -@{ - -The `readutil` library contains primitives to read lines, files, -multiple terms, etc. - - -*/ - -/** @pred read_line_to_codes(+ _Stream_, - _Codes_) - - - -Read the next line of input from _Stream_ and unify the result with - _Codes_ after the line has been read. A line is ended by a -newline character or end-of-file. Unlike `read_line_to_codes/3`, -this predicate removes trailing newline character. - -On end-of-file the atom `end_of_file` is returned. See also -`at_end_of_stream/[0,1]`. - - -*/ - -/** @pred read_line_to_codes(+ _Stream_, - _Codes_, ? _Tail_) - -Difference-list version to read an input line to a list of character -codes. Reading stops at the newline or end-of-file character, but -unlike read_line_to_codes/2, the newline is retained in the -output. This predicate is especially useful for reading a block of -lines upto some delimiter. The following example reads an HTTP header -ended by a blank line: - -~~~~~ -read_header_data(Stream, Header) :- - read_line_to_codes(Stream, Header, Tail), - read_header_data(Header, Stream, Tail). - -read_header_data("\r\n", _, _) :- !. -read_header_data("\n", _, _) :- !. -read_header_data("", _, _) :- !. -read_header_data(_, Stream, Tail) :- - read_line_to_codes(Stream, Tail, NewTail), - read_header_data(Tail, Stream, NewTail). -~~~~~ - - -*/ - -/** @pred read_stream_to_codes(+ _Stream_, - _Codes_) - - -Read all input until end-of-file and unify the result to _Codes_. - - -*/ - -/** @pred read_stream_to_codes(+ _Stream_, - _Codes_, ? _Tail_) - -Difference-list version of read_stream_to_codes/2. - - -*/ - -/** @pred read_file_to_codes(+ _Spec_, - _Codes_, + _Options_) - - -Read a file to a list of character codes. Currently ignores - _Options_. - - -*/ - -/** @pred read_file_to_terms(+ _Spec_, - _Terms_, + _Options_) - - -Read a file to a list of Prolog terms (see read/1). @c _Spec_ is a - - - - - - - - - - */ - -/** @defgroup RedhYBlack_Trees Red-Black Trees -@ingroup library -@{ - -Red-Black trees are balanced search binary trees. They are named because -nodes can be classified as either red or black. The code we include is -based on "Introduction to Algorithms", second edition, by Cormen, -Leiserson, Rivest and Stein. The library includes routines to insert, -lookup and delete elements in the tree. - - -*/ - -/** @pred rb_new(? _T_) - - -Create a new tree. - - -*/ - -/** @pred rb_empty(? _T_) - - -Succeeds if tree _T_ is empty. - - -*/ - -/** @pred is_rbtree(+ _T_) - - -Check whether _T_ is a valid red-black tree. - - -*/ - -/** @pred rb_insert(+ _T0_,+ _Key_,? _Value_,+ _TF_) - - -Add an element with key _Key_ and _Value_ to the tree - _T0_ creating a new red-black tree _TF_. Duplicated elements are not -allowed. - -Add a new element with key _Key_ and _Value_ to the tree - _T0_ creating a new red-black tree _TF_. Fails is an element -with _Key_ exists in the tree. - - -*/ - -/** @pred rb_lookup(+ _Key_,- _Value_,+ _T_) - - -Backtrack through all elements with key _Key_ in the red-black tree - _T_, returning for each the value _Value_. - - -*/ - -/** @pred rb_lookupall(+ _Key_,- _Value_,+ _T_) - - -Lookup all elements with key _Key_ in the red-black tree - _T_, returning the value _Value_. - - -*/ - -/** @pred rb_delete(+ _T_,+ _Key_,- _TN_) - - -Delete element with key _Key_ from the tree _T_, returning a new -tree _TN_. - - -*/ - -/** @pred rb_delete(+ _T_,+ _Key_,- _Val_,- _TN_) - -Delete element with key _Key_ from the tree _T_, returning the -value _Val_ associated with the key and a new tree _TN_. - - -*/ - -/** @pred rb_del_min(+ _T_,- _Key_,- _Val_,- _TN_) - - -Delete the least element from the tree _T_, returning the key - _Key_, the value _Val_ associated with the key and a new tree - _TN_. - - -*/ - -/** @pred rb_del_max(+ _T_,- _Key_,- _Val_,- _TN_) - - -Delete the largest element from the tree _T_, returning the key - _Key_, the value _Val_ associated with the key and a new tree - _TN_. - - -*/ - -/** @pred rb_update(+ _T_,+ _Key_,+ _NewVal_,- _TN_) - - -Tree _TN_ is tree _T_, but with value for _Key_ associated -with _NewVal_. Fails if it cannot find _Key_ in _T_. - - -*/ - -/** @pred rb_apply(+ _T_,+ _Key_,+ _G_,- _TN_) - - -If the value associated with key _Key_ is _Val0_ in _T_, and -if `call(G,Val0,ValF)` holds, then _TN_ differs from - _T_ only in that _Key_ is associated with value _ValF_ in -tree _TN_. Fails if it cannot find _Key_ in _T_, or if -`call(G,Val0,ValF)` is not satisfiable. - - -*/ - -/** @pred rb_visit(+ _T_,- _Pairs_) - - - _Pairs_ is an infix visit of tree _T_, where each element of - _Pairs_ is of the form _K_- _Val_. - - -*/ - -/** @pred rb_size(+ _T_,- _Size_) - - - _Size_ is the number of elements in _T_. - - -*/ - -/** @pred rb_keys(+ _T_,+ _Keys_) - - - _Keys_ is an infix visit with all keys in tree _T_. Keys will be -sorted, but may be duplicate. - - -*/ - -/** @pred rb_map(+ _T_,+ _G_,- _TN_) - - -For all nodes _Key_ in the tree _T_, if the value associated with -key _Key_ is _Val0_ in tree _T_, and if -`call(G,Val0,ValF)` holds, then the value associated with _Key_ -in _TN_ is _ValF_. Fails if or if `call(G,Val0,ValF)` is not -satisfiable for all _Var0_. - - -*/ - -/** @pred rb_partial_map(+ _T_,+ _Keys_,+ _G_,- _TN_) - - -For all nodes _Key_ in _Keys_, if the value associated with key - _Key_ is _Val0_ in tree _T_, and if `call(G,Val0,ValF)` -holds, then the value associated with _Key_ in _TN_ is - _ValF_. Fails if or if `call(G,Val0,ValF)` is not satisfiable -for all _Var0_. Assumes keys are not repeated. - - -*/ - -/** @pred rb_fold(+ _T_,+ _G_,+ _Acc0_, - _AccF_) - - -For all nodes _Key_ in the tree _T_, if the value -associated with key _Key_ is _V_ in tree _T_, if -`call(G,V,Acc1,Acc2)` holds, then if _VL_ is value of the -previous node in inorder, `call(G,VL,_,Acc0)` must hold, and if - _VR_ is the value of the next node in inorder, -`call(G,VR,Acc1,_)` must hold. - - -*/ - -/** @pred rb_key_fold(+ _T_,+ _G_,+ _Acc0_, - _AccF_) - - -For all nodes _Key_ in the tree _T_, if the value -associated with key _Key_ is _V_ in tree _T_, if -`call(G,Key,V,Acc1,Acc2)` holds, then if _VL_ is value of the -previous node in inorder, `call(G,KeyL,VL,_,Acc0)` must hold, and if - _VR_ is the value of the next node in inorder, -`call(G,KeyR,VR,Acc1,_)` must hold. - - -*/ - -/** @pred rb_clone(+ _T_,+ _NT_,+ _Nodes_) - - -=Clone= the red-back tree into a new tree with the same keys as the -original but with all values set to unbound values. _Nodes_ is a list -containing all new nodes as pairs _K-V_. - - -*/ - -/** @pred rb_min(+ _T_,- _Key_,- _Value_) - - - _Key_ is the minimum key in _T_, and is associated with _Val_. - - -*/ - -/** @pred rb_max(+ _T_,- _Key_,- _Value_) - - - _Key_ is the maximal key in _T_, and is associated with _Val_. - - -*/ - -/** @pred rb_next(+ _T_, + _Key_,- _Next_,- _Value_) - - - _Next_ is the next element after _Key_ in _T_, and is -associated with _Val_. - - -*/ - -/** @pred rb_previous(+ _T_, + _Key_,- _Previous_,- _Value_) - - - _Previous_ is the previous element after _Key_ in _T_, and is -associated with _Val_. - - -*/ - -/** @pred ord_list_to_rbtree(+ _L_, - _T_) - - - _T_ is the red-black tree corresponding to the mapping in ordered -list _L_. - - - - */ - -/** @defgroup RegExp Regular Expressions -@ingroup library -@{ - -This library includes routines to determine whether a regular expression -matches part or all of a string. The routines can also return which -parts parts of the string matched the expression or subexpressions of -it. This library relies on Henry Spencer's `C`-package and is only -available in operating systems that support dynamic loading. The -`C`-code has been obtained from the sources of FreeBSD-4.0 and is -protected by copyright from Henry Spencer and from the Regents of the -University of California (see the file library/regex/COPYRIGHT for -further details). - -Much of the description of regular expressions below is copied verbatim -from Henry Spencer's manual page. - -A regular expression is zero or more branches, separated by ``|`. It -matches anything that matches one of the branches. - -A branch is zero or more pieces, concatenated. It matches a match for -the first, followed by a match for the second, etc. - -A piece is an atom possibly followed by `\*`, `+`, or `?`. An atom -followed by `\*` matches a sequence of 0 or more matches of the atom. -An atom followed by `+` matches a sequence of 1 or more matches of the -atom. An atom followed by `?` matches a match of the atom, or the -null string. - -An atom is a regular expression in parentheses (matching a match for the -regular expression), a range (see below), `.` (matching any single -character), `^` (matching the null string at the beginning of the -input string), `$` (matching the null string at the end of the input -string), a `\` followed by a single character (matching that -character), or a single character with no other significance (matching -that character). - -A range is a sequence of characters enclosed in `[]`. It normally -matches any single character from the sequence. If the sequence begins -with `^`, it matches any single character not from the rest of the -sequence. If two characters in the sequence are separated by `-`, -this is shorthand for the full list of ASCII characters between them -(e.g. `[0-9]` matches any decimal digit). To include a literal `]` -in the sequence, make it the first character (following a possible -`^`). To include a literal `-`, make it the first or last -character. - - - - @pred regexp(+ _RegExp_,+ _String_,+ _Opts_) - - - -Match regular expression _RegExp_ to input string _String_ -according to options _Opts_. The options may be: - -+ `nocase`: Causes upper-case characters in _String_ to -be treated as lower case during the matching process. - - - -*/ - -/** @pred regexp(+ _RegExp_,+ _String_,+ _Opts_,? _SubMatchVars_) - - -Match regular expression _RegExp_ to input string _String_ -according to options _Opts_. The variable _SubMatchVars_ should -be originally unbound or a list of unbound variables all will contain a -sequence of matches, that is, the head of _SubMatchVars_ will -contain the characters in _String_ that matched the leftmost -parenthesized subexpression within _RegExp_, the next head of list -will contain the characters that matched the next parenthesized -subexpression to the right in _RegExp_, and so on. - -The options may be: - -+ `nocase`: Causes upper-case characters in _String_ to -be treated as lower case during the matching process. -+ `indices`: Changes what is stored in - _SubMatchVars_. Instead of storing the matching characters from - _String_, each variable will contain a term of the form _IO-IF_ -giving the indices in _String_ of the first and last characters in -the matching range of characters. - - - -In general there may be more than one way to match a regular expression -to an input string. For example, consider the command - -~~~~~ - regexp("(a*)b*","aabaaabb", [], [X,Y]) -~~~~~ -Considering only the rules given so far, _X_ and _Y_ could end up -with the values `"aabb"` and `"aa"`, `"aaab"` and -`"aaa"`, `"ab"` and `"a"`, or any of several other -combinations. To resolve this potential ambiguity `regexp` chooses among -alternatives using the rule `first then longest`. In other words, it -considers the possible matches in order working from left to right -across the input string and the pattern, and it attempts to match longer -pieces of the input string before shorter ones. More specifically, the -following rules apply in decreasing order of priority: - -+ If a regular expression could match two different parts of an -input string then it will match the one that begins earliest. - -+ If a regular expression contains "|" operators then the leftmost matching sub-expression is chosen. - -+ In \*, +, and ? constructs, longer matches are chosen in preference to shorter ones. - -+ In sequences of expression components the components are considered from left to right. - -In the example above, `"(a\*)b\*"` matches `"aab"`: the -`"(a\*)"` portion of the pattern is matched first and it consumes -the leading `"aa"`; then the `"b\*"` portion of the pattern -consumes the next `"b"`. Or, consider the following example: - -~~~~~ - regexp("(ab|a)(b*)c", "abc", [], [X,Y,Z]) -~~~~~ - -After this command _X_ will be `"abc"`, _Y_ will be -`"ab"`, and _Z_ will be an empty string. Rule 4 specifies that -`"(ab|a)"` gets first shot at the input string and Rule 2 specifies -that the `"ab"` sub-expression is checked before the `"a"` -sub-expression. Thus the `"b"` has already been claimed before the -`"(b\*)"` component is checked and `(b\*)` must match an empty string. - - - - - */ - -/** @defgroup shlib SWI-Prolog's shlib library -@ingroup library -@{ - -This section discusses the functionality of the (autoload) -`library(shlib)`, providing an interface to manage shared -libraries. - -One of the files provides a global function `install_mylib()` that -initialises the module using calls to `PL_register_foreign()`. Here is a -simple example file `mylib.c`, which creates a Windows MessageBox: - -~~~~~{.c} -#include -#include - -static foreign_t -pl_say_hello(term_t to) -{ char *a; - - if ( PL_get_atom_chars(to, &a) ) - { MessageBox(NULL, a, "DLL test", MB_OK|MB_TASKMODAL); - - PL_succeed; - } - - PL_fail; -} - -install_t -install_mylib() -{ PL_register_foreign("say_hello", 1, pl_say_hello, 0); -} -~~~~~ - -Now write a file mylib.pl: - -~~~~~ -:- module(mylib, [ say_hello/1 ]). -:- use_foreign_library(foreign(mylib)). -~~~~~ - -The file mylib.pl can be loaded as a normal Prolog file and provides the predicate defined in C. - - -*/ - -/** @pred load_foreign_library(: _FileSpec_) is det - - - -*/ - -/** @pred load_foreign_library(: _FileSpec_, + _Entry_:atom) is det - -Load a shared object or DLL. After loading the _Entry_ function is -called without arguments. The default entry function is composed -from `install_`, followed by the file base-name. E.g., the -load-call below calls the function `install_mylib()`. If the platform -prefixes extern functions with `_`, this prefix is added before -calling. - -~~~~~ - ... - load_foreign_library(foreign(mylib)), - ... -~~~~~ - - _FileSpec_ is a specification for -absolute_file_name/3. If searching the file fails, the plain -name is passed to the OS to try the default method of the OS for -locating foreign objects. The default definition of -file_search_path/2 searches /lib/Yap. - -See also -`use_foreign_library/1,2` are intended for use in -directives. - - -*/ - -/** @pred use_foreign_library(+ _FileSpec_) is det - use_foreign_library(+ _FileSpec_, + _Entry_:atom) is det - - - -Load and install a foreign library as load_foreign_library/1 -and `load_foreign_library/2` and -register the installation using `initialization/2` with the option -now. This is similar to using: - -~~~~~ - :- initialization(load_foreign_library(foreign(mylib))). -~~~~~ - -but using the initialization/1 wrapper causes the library to -be loaded after loading of the file in which it appears is -completed, while use_foreign_library/1 loads the library -immediately. I.e. the difference is only relevant if the remainder -of the file uses functionality of the `C`-library. - - -*/ - -/** @pred unload_foreign_library(+ _FileSpec_) is det - -*/ - -/** @pred unload_foreign_library(+ _FileSpec_, + _Exit_:atom) is det - - - - -Unload a shared -object or DLL. After calling the _Exit_ function, the shared object is -removed from the process. The default exit function is composed from -`uninstall_`, followed by the file base-name. - - -*/ - -/** @pred current_foreign_library(? _File_, ? _Public_) - - - -Query currently -loaded shared libraries. - - - - - */ - -/** @defgroup Splay_Trees Splay Trees -@ingroup library -@{ - -Splay trees are explained in the paper "Self-adjusting Binary Search -Trees", by D.D. Sleator and R.E. Tarjan, JACM, vol. 32, No.3, July 1985, -p. 668. They are designed to support fast insertions, deletions and -removals in binary search trees without the complexity of traditional -balanced trees. The key idea is to allow the tree to become -unbalanced. To make up for this, whenever we find a node, we move it up -to the top. We use code by Vijay Saraswat originally posted to the Prolog -mailing-list. - - - - @pred splay_access(- _Return_,+ _Key_,? _Val_,+ _Tree_,- _NewTree_) - - -If item _Key_ is in tree _Tree_, return its _Val_ and -unify _Return_ with `true`. Otherwise unify _Return_ with -`null`. The variable _NewTree_ unifies with the new tree. - - -*/ - -/** @pred splay_del(+ _Item_,+ _Tree_,- _NewTree_) - - -Delete item _Key_ from tree _Tree_, assuming that it is present -already. The variable _Val_ unifies with a value for key _Key_, -and the variable _NewTree_ unifies with the new tree. The predicate -will fail if _Key_ is not present. - - -*/ - -/** @pred splay_init(- _NewTree_) - - -Initialize a new splay tree. - - -*/ - -/** @pred splay_insert(+ _Key_,? _Val_,+ _Tree_,- _NewTree_) - - -Insert item _Key_ in tree _Tree_, assuming that it is not -there already. The variable _Val_ unifies with a value for key - _Key_, and the variable _NewTree_ unifies with the new -tree. In our implementation, _Key_ is not inserted if it is -already there: rather it is unified with the item already in the tree. - - -*/ - -/** @pred splay_join(+ _LeftTree_,+ _RighTree_,- _NewTree_) - - -Combine trees _LeftTree_ and _RighTree_ into a single -tree _NewTree_ containing all items from both trees. This operation -assumes that all items in _LeftTree_ are less than all those in - _RighTree_ and destroys both _LeftTree_ and _RighTree_. - - -*/ - -/** @pred splay_split(+ _Key_,? _Val_,+ _Tree_,- _LeftTree_,- _RightTree_) - - -Construct and return two trees _LeftTree_ and _RightTree_, -where _LeftTree_ contains all items in _Tree_ less than - _Key_, and _RightTree_ contains all items in _Tree_ -greater than _Key_. This operations destroys _Tree_. - - - - - */ - -/** @defgroup String_InputOutput Reading From and Writing To Strings -@ingroup library -@{ - -From Version 4.3.2 onwards YAP implements SICStus Prolog compatible -String Input/Output. The library allows users to read from and write to a memory -buffer as if it was a file. The memory buffer is built from or converted -to a string of character codes by the routines in library. Therefore, if -one wants to read from a string the string must be fully instantiated -before the library built-in opens the string for reading. These commands -are available through the `use_module(library(charsio))` command. - - -*/ - -/** @pred format_to_chars(+ _Form_, + _Args_, - _Result_) - - - -Execute the built-in procedure format/2 with form _Form_ and -arguments _Args_ outputting the result to the string of character -codes _Result_. - - -*/ - -/** @pred format_to_chars(+ _Form_, + _Args_, - _Result_, - _Result0_) - - -Execute the built-in procedure format/2 with form _Form_ and -arguments _Args_ outputting the result to the difference list of -character codes _Result-Result0_. - - -*/ - -/** @pred write_to_chars(+ _Term_, - _Result_) - - - -Execute the built-in procedure write/1 with argument _Term_ -outputting the result to the string of character codes _Result_. - - -*/ - -/** @pred write_to_chars(+ _Term_, - _Result0_, - _Result_) - - -Execute the built-in procedure write/1 with argument _Term_ -outputting the result to the difference list of character codes - _Result-Result0_. - - -*/ - -/** @pred atom_to_chars(+ _Atom_, - _Result_) - - - -Convert the atom _Atom_ to the string of character codes - _Result_. - - -*/ - -/** @pred atom_to_chars(+ _Atom_, - _Result0_, - _Result_) - - -Convert the atom _Atom_ to the difference list of character codes - _Result-Result0_. - - -*/ - -/** @pred number_to_chars(+ _Number_, - _Result_) - - - -Convert the number _Number_ to the string of character codes - _Result_. - - -*/ - -/** @pred number_to_chars(+ _Number_, - _Result0_, - _Result_) - - -Convert the atom _Number_ to the difference list of character codes - _Result-Result0_. - - -*/ - -/** @pred atom_to_term(+ _Atom_, - _Term_, - _Bindings_) - - -Use _Atom_ as input to read_term/2 using the option `variable_names` and return the read term in _Term_ and the variable bindings in _Bindings_. _Bindings_ is a list of `Name = Var` couples, thus providing access to the actual variable names. See also read_term/2. If Atom has no valid syntax, a syntax_error exception is raised. - - -*/ - -/** @pred term_to_atom(? _Term_, ? _Atom_) - - -True if _Atom_ describes a term that unifies with _Term_. When - _Atom_ is instantiated _Atom_ is converted and then unified with - _Term_. If _Atom_ has no valid syntax, a syntax_error exception -is raised. Otherwise _Term_ is `written` on _Atom_ using -write_term/2 with the option quoted(true). - - -*/ - -/** @pred read_from_chars(+ _Chars_, - _Term_) - - - -Parse the list of character codes _Chars_ and return the result in -the term _Term_. The character codes to be read must terminate with -a dot character such that either (i) the dot character is followed by -blank characters; or (ii) the dot character is the last character in the -string. - - -*/ - -/** @pred open_chars_stream(+ _Chars_, - _Stream_) - - - -Open the list of character codes _Chars_ as a stream _Stream_. - - -*/ - -/** @pred with_output_to_chars(? _Goal_, - _Chars_) - - - -Execute goal _Goal_ such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the list of character codes _Chars_. - - -*/ - -/** @pred with_output_to_chars(? _Goal_, ? _Chars0_, - _Chars_) - - -Execute goal _Goal_ such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the difference list of character codes - _Chars-Chars0_. - - -*/ - -/** @pred with_output_to_chars(? _Goal_, - _Stream_, ? _Chars0_, - _Chars_) - - -Execute goal _Goal_ such that its standard output will be sent to a -memory buffer. After successful execution the contents of the memory -buffer will be converted to the difference list of character codes - _Chars-Chars0_ and _Stream_ receives the stream corresponding to -the memory buffer. - - */ - -/** @defgroup System Calling The Operating System from YAP -@ingroup library -@{ - -YAP now provides a library of system utilities compatible with the -SICStus Prolog system library. This library extends and to some point -replaces the functionality of Operating System access routines. The -library includes Unix/Linux and Win32 `C` code. They -are available through the `use_module(library(system))` command. - - - - @pred datime(datime(- _Year_, - _Month_, - _DayOfTheMonth_, - _Hour_, - _Minute_, - _Second_) - -The datime/1 procedure returns the current date and time, with -information on _Year_, _Month_, _DayOfTheMonth_, - _Hour_, _Minute_, and _Second_. The _Hour_ is returned -on local time. This function uses the WIN32 -`GetLocalTime` function or the Unix `localtime` function. - -~~~~~ - ?- datime(X). - -X = datime(2001,5,28,15,29,46) ? -~~~~~ - - -*/ - -/** @pred mktime(+_Datime_, - _Seconds_) - -The `mktime/2` procedure receives a term of the form _datime(+ _Year_, -+ _Month_, + _DayOfTheMonth_, + _Hour_, + _Minute_, + _Second_)_ and -returns the number of _Seconds_ elapsed since 00:00:00 on January 1, -1970, Coordinated Universal Time (UTC). The user provides information -on _Year_, _Month_, _DayOfTheMonth_, _Hour_, _Minute_, and -_Second_. The _Hour_ is given on local time. This function uses the -WIN32 `GetLocalTime` function or the Unix `mktime` function. - -~~~~~ - ?- mktime(datime(2001,5,28,15,29,46),X). - -X = 991081786 ? ; -~~~~~ - - -*/ - -/** @pred delete_file(+ _File_) - - -The delete_file/1 procedure removes file _File_. If - _File_ is a directory, remove the directory and all its subdirectories. - -~~~~~ - ?- delete_file(x). -~~~~~ - - -*/ - -/** @pred delete_file(+ _File_,+ _Opts_) - -The `delete_file/2` procedure removes file _File_ according to -options _Opts_. These options are `directory` if one should -remove directories, `recursive` if one should remove directories -recursively, and `ignore` if errors are not to be reported. - -This example is equivalent to using the delete_file/1 predicate: - -~~~~~ - ?- delete_file(x, [recursive]). -~~~~~ - - -*/ - -/** @pred directory_files(+ _Dir_,+ _List_) - - -Given a directory _Dir_, directory_files/2 procedures a -listing of all files and directories in the directory: - -~~~~~ - ?- directory_files('.',L), writeq(L). -['Makefile.~1~','sys.so','Makefile','sys.o',x,..,'.'] -~~~~~ -The predicates uses the `dirent` family of routines in Unix -environments, and `findfirst` in WIN32. - - -*/ - -/** @pred file_exists(+ _File_) - - -The atom _File_ corresponds to an existing file. - - -*/ - -/** @pred file_exists(+ _File_,+ _Permissions_) - -The atom _File_ corresponds to an existing file with permissions -compatible with _Permissions_. YAP currently only accepts for -permissions to be described as a number. The actual meaning of this -number is Operating System dependent. - - -*/ - -/** @pred file_property(+ _File_,? _Property_) - - -The atom _File_ corresponds to an existing file, and _Property_ -will be unified with a property of this file. The properties are of the -form `type( _Type_)`, which gives whether the file is a regular -file, a directory, a fifo file, or of unknown type; -`size( _Size_)`, with gives the size for a file, and -`mod_time( _Time_)`, which gives the last time a file was -modified according to some Operating System dependent -timestamp; `mode( _mode_)`, gives the permission flags for the -file, and `linkto( _FileName_)`, gives the file pointed to by a -symbolic link. Properties can be obtained through backtracking: - -~~~~~ - ?- file_property('Makefile',P). - -P = type(regular) ? ; - -P = size(2375) ? ; - -P = mod_time(990826911) ? ; - -no -~~~~~ - - -*/ - -/** @pred make_directory(+ _Dir_) - - -Create a directory _Dir_. The name of the directory must be an atom. - - -*/ - -/** @pred rename_file(+ _OldFile_,+ _NewFile_) - - -Create file _OldFile_ to _NewFile_. This predicate uses the -`C` built-in function `rename`. - - -*/ - -/** @pred environ(? _EnvVar_,+ _EnvValue_) - - -Unify environment variable _EnvVar_ with its value _EnvValue_, -if there is one. This predicate is backtrackable in Unix systems, but -not currently in Win32 configurations. - -~~~~~ - ?- environ('HOME',X). - -X = 'C:\\cygwin\\home\\administrator' ? -~~~~~ - - -*/ - -/** @pred host_id(- _Id_) - - - -Unify _Id_ with an identifier of the current host. YAP uses the -`hostid` function when available, - - -*/ - -/** @pred host_name(- _Name_) - - - -Unify _Name_ with a name for the current host. YAP uses the -`hostname` function in Unix systems when available, and the -`GetComputerName` function in WIN32 systems. - - -*/ - -/** @pred kill( _Id_,+ _SIGNAL_) - - - -Send signal _SIGNAL_ to process _Id_. In Unix this predicate is -a direct interface to `kill` so one can send signals to groups of -processes. In WIN32 the predicate is an interface to -`TerminateProcess`, so it kills _Id_ independently of _SIGNAL_. - - -*/ - -/** @pred mktemp( _Spec_,- _File_) - - - -Direct interface to `mktemp`: given a _Spec_, that is a file -name with six _X_ to it, create a file name _File_. Use -tmpnam/1 instead. - - -*/ - -/** @pred pid(- _Id_) - - - -Unify _Id_ with the process identifier for the current -process. An interface to the getpid function. - - -*/ - -/** @pred tmpnam(- _File_) - - - -Interface with _tmpnam_: obtain a new, unique file name _File_. - - -*/ - -/** @pred tmp_file(+_Base_, - _File_) - -Create a name for a temporary file. _Base_ is an user provided -identifier for the category of file. The _TmpName_ is guaranteed to -be unique. If the system halts, it will automatically remove all created -temporary files. - - -*/ - -/** @pred exec(+ _Command_, _StandardStreams_,- _PID_) - - -Execute command _Command_ with its standard streams connected to -the list [_InputStream_, _OutputStream_, _ErrorStream_]. The -process that executes the command is returned as _PID_. The -command is executed by the default shell `bin/sh -c` in Unix. - -The following example demonstrates the use of exec/3 to send a -command and process its output: - -~~~~~ -exec(ls,[std,pipe(S),null],P),repeat, get0(S,C), (C = -1, close(S) ! ; put(C)). -~~~~~ - -The streams may be one of standard stream, `std`, null stream, -`null`, or `pipe(S)`, where _S_ is a pipe stream. Note -that it is up to the user to close the pipe. - - -*/ - -/** @pred popen(+ _Command_, + _TYPE_, - _Stream_) - - -Interface to the popen function. It opens a process by creating a -pipe, forking and invoking _Command_ on the current shell. Since a -pipe is by definition unidirectional the _Type_ argument may be -`read` or `write`, not both. The stream should be closed -using close/1, there is no need for a special `pclose` -command. - -The following example demonstrates the use of popen/3 to process -the output of a command, as exec/3 would do: - -~~~~~{.prolog} - ?- popen(ls,read,X),repeat, get0(X,C), (C = -1, ! ; put(C)). - -X = 'C:\\cygwin\\home\\administrator' ? -~~~~~ - -The WIN32 implementation of popen/3 relies on exec/3. - - -*/ - -/** @pred shell - - -Start a new shell and leave YAP in background until the shell -completes. YAP uses the shell given by the environment variable -`SHELL`. In WIN32 environment YAP will use `COMSPEC` if -`SHELL` is undefined. - - -*/ - -/** @pred shell(+ _Command_) - -Execute command _Command_ under a new shell. YAP will be in -background until the command completes. In Unix environments YAP uses -the shell given by the environment variable `SHELL` with the option -`" -c "`. In WIN32 environment YAP will use `COMSPEC` if -`SHELL` is undefined, in this case with the option `" /c "`. - - -*/ - -/** @pred shell(+ _Command_,- _Status_) - -Execute command _Command_ under a new shell and unify _Status_ -with the exit for the command. YAP will be in background until the -command completes. In Unix environments YAP uses the shell given by the -environment variable `SHELL` with the option `" -c "`. In -WIN32 environment YAP will use `COMSPEC` if `SHELL` is -undefined, in this case with the option `" /c "`. - - -*/ - -/** @pred sleep(+ _Time_) - - -Block the current thread for _Time_ seconds. When YAP is compiled -without multi-threading support, this predicate blocks the YAP process. -The number of seconds must be a positive number, and it may an integer -or a float. The Unix implementation uses `usleep` if the number of -seconds is below one, and `sleep` if it is over a second. The WIN32 -implementation uses `Sleep` for both cases. - - -*/ - -/** @pred system - -Start a new default shell and leave YAP in background until the shell -completes. YAP uses `/bin/sh` in Unix systems and `COMSPEC` in -WIN32. - - -*/ - -/** @pred system(+ _Command_,- _Res_) - -Interface to `system`: execute command _Command_ and unify - _Res_ with the result. - - -*/ - -/** @pred wait(+ _PID_,- _Status_) - - -Wait until process _PID_ terminates, and return its exits _Status_. - - - - - */ - -/** @defgroup Terms Utilities On Terms -@ingroup library -@{ - -The next routines provide a set of commonly used utilities to manipulate -terms. Most of these utilities have been implemented in `C` for -efficiency. They are available through the -`use_module(library(terms))` command. - - - - @pred cyclic_term(? _Term_) - - -Succeed if the argument _Term_ is not a cyclic term. - - -*/ - -/** @pred term_hash(+ _Term_, ? _Hash_) - - - -If _Term_ is ground unify _Hash_ with a positive integer -calculated from the structure of the term. Otherwise the argument - _Hash_ is left unbound. The range of the positive integer is from -`0` to, but not including, `33554432`. - - -*/ - -/** @pred term_hash(+ _Term_, + _Depth_, + _Range_, ? _Hash_) - - -Unify _Hash_ with a positive integer calculated from the structure -of the term. The range of the positive integer is from `0` to, but -not including, _Range_. If _Depth_ is `-1` the whole term -is considered. Otherwise, the term is considered only up to depth -`1`, where the constants and the principal functor have depth -`1`, and an argument of a term with depth _I_ has depth _I+1_. - - -*/ - -/** @pred variables_within_term(+ _Variables_,? _Term_, - _OutputVariables_) - - - -Unify _OutputVariables_ with the subset of the variables _Variables_ that occurs in _Term_. - - -*/ - -/** @pred new_variables_in_term(+ _Variables_,? _Term_, - _OutputVariables_) - - - -Unify _OutputVariables_ with all variables occurring in _Term_ that are not in the list _Variables_. - - -*/ - -/** @pred variant(? _Term1_, ? _Term2_) - - - -Succeed if _Term1_ and _Term2_ are variant terms. - - -*/ - -/** @pred subsumes(? _Term1_, ? _Term2_) - - - -Succeed if _Term1_ subsumes _Term2_. Variables in term - _Term1_ are bound so that the two terms become equal. - - -*/ - -/** @pred subsumes_chk(? _Term1_, ? _Term2_) - - - -Succeed if _Term1_ subsumes _Term2_ but does not bind any -variable in _Term1_. - - -*/ - -/** @pred variable_in_term(? _Term_,? _Var_) - - -Succeed if the second argument _Var_ is a variable and occurs in -term _Term_. - - -*/ - -/** @pred unifiable(? _Term1_, ? _Term2_, - _Bindings_) - - - -Succeed if _Term1_ and _Term2_ are unifiable with substitution - _Bindings_. - - - - - */ - -/** @defgroup Tries Trie DataStructure -@ingroup library -@{ - -The next routines provide a set of utilities to create and manipulate -prefix trees of Prolog terms. Tries were originally proposed to -implement tabling in Logic Programming, but can be used for other -purposes. The tries will be stored in the Prolog database and can seen -as alternative to `assert` and `record` family of -primitives. Most of these utilities have been implemented in `C` -for efficiency. They are available through the -`use_module(library(tries))` command. - - -*/ - -/** @pred trie_open(- _Id_) - - - -Open a new trie with identifier _Id_. - - -*/ - -/** @pred trie_close(+ _Id_) - - - -Close trie with identifier _Id_. - - -*/ - -/** @pred trie_close_all - - - -Close all available tries. - - -*/ - -/** @pred trie_mode(? _Mode_) - - - -Unify _Mode_ with trie operation mode. Allowed values are either -`std` (default) or `rev`. - - -*/ - -/** @pred trie_put_entry(+ _Trie_,+ _Term_,- _Ref_) - - - -Add term _Term_ to trie _Trie_. The handle _Ref_ gives -a reference to the term. - - -*/ - -/** @pred trie_check_entry(+ _Trie_,+ _Term_,- _Ref_) - - - -Succeeds if a variant of term _Term_ is in trie _Trie_. An handle - _Ref_ gives a reference to the term. - - -*/ - -/** @pred trie_get_entry(+ _Ref_,- _Term_) - - -Unify _Term_ with the entry for handle _Ref_. - - -*/ - -/** @pred trie_remove_entry(+ _Ref_) - - - -Remove entry for handle _Ref_. - - -*/ - -/** @pred trie_remove_subtree(+ _Ref_) - - - -Remove subtree rooted at handle _Ref_. - - -*/ - -/** @pred trie_save(+ _Trie_,+ _FileName_) - - -Dump trie _Trie_ into file _FileName_. - - -*/ - -/** @pred trie_load(+ _Trie_,+ _FileName_) - - -Load trie _Trie_ from the contents of file _FileName_. - - -*/ - -/** @pred trie_stats(- _Memory_,- _Tries_,- _Entries_,- _Nodes_) - - -Give generic statistics on tries, including the amount of memory, - _Memory_, the number of tries, _Tries_, the number of entries, - _Entries_, and the total number of nodes, _Nodes_. - - -*/ - -/** @pred trie_max_stats(- _Memory_,- _Tries_,- _Entries_,- _Nodes_) - - -Give maximal statistics on tries, including the amount of memory, - _Memory_, the number of tries, _Tries_, the number of entries, - _Entries_, and the total number of nodes, _Nodes_. - - -*/ - -/** @pred trie_usage(+ _Trie_,- _Entries_,- _Nodes_,- _VirtualNodes_) - - -Give statistics on trie _Trie_, the number of entries, - _Entries_, and the total number of nodes, _Nodes_, and the -number of _VirtualNodes_. - - -*/ - -/** @pred trie_print(+ _Trie_) - - -Print trie _Trie_ on standard output. - - - - - */ - -/** @defgroup Cleanup Call Cleanup -@ingroup library -@{ - -call_cleanup/1 and call_cleanup/2 allow predicates to register -code for execution after the call is finished. Predicates can be -declared to be fragile to ensure that call_cleanup is called -for any Goal which needs it. This library is loaded with the -`use_module(library(cleanup))` command. - - -*/ - -/** @pred :- fragile _P_,....,_Pn_ is directive - - -Declares the predicate _P_=[module:]name/arity as a fragile -predicate, module is optional, default is the current -typein_module. Whenever such a fragile predicate is used in a query -it will be called through call_cleanup/1. - -~~~~~{.prolog} -:- fragile foo/1,bar:baz/2. -~~~~~ - - -*/ - -/** @pred call_cleanup(: _Goal_) - - -Execute goal _Goal_ within a cleanup-context. Called predicates -might register cleanup Goals which are called right after the end of -the call to _Goal_. Cuts and exceptions inside Goal do not prevent the -execution of the cleanup calls. call_cleanup might be nested. - - -*/ - -/** @pred call_cleanup(: _Goal_, : _CleanUpGoal_) - -This is similar to call_cleanup/1 with an additional - _CleanUpGoal_ which gets called after _Goal_ is finished. - - -*/ - -/** @pred setup_call_cleanup(: _Setup_,: _Goal_, : _CleanUpGoal_) - - -Calls `(Setup, Goal)`. For each sucessful execution of _Setup_, calling _Goal_, the -cleanup handler _Cleanup_ is guaranteed to be called exactly once. -This will happen after _Goal_ completes, either through failure, -deterministic success, commit, or an exception. _Setup_ will -contain the goals that need to be protected from asynchronous interrupts -such as the ones received from `call_with_time_limit/2` or thread_signal/2. In -most uses, _Setup_ will perform temporary side-effects required by - _Goal_ that are finally undone by _Cleanup_. - -Success or failure of _Cleanup_ is ignored and choice-points it -created are destroyed (as once/1). If _Cleanup_ throws an exception, -this is executed as normal. - -Typically, this predicate is used to cleanup permanent data storage -required to execute _Goal_, close file-descriptors, etc. The example -below provides a non-deterministic search for a term in a file, closing -the stream as needed. - -~~~~~{.prolog} -term_in_file(Term, File) :- - setup_call_cleanup(open(File, read, In), - term_in_stream(Term, In), - close(In) ). - -term_in_stream(Term, In) :- - repeat, - read(In, T), - ( T == end_of_file - -> !, fail - ; T = Term - ). -~~~~~ - -Note that it is impossible to implement this predicate in Prolog other than -by reading all terms into a list, close the file and call member/2. -Without setup_call_cleanup/3 there is no way to gain control if the -choice-point left by `repeat` is removed by a cut or an exception. - -`setup_call_cleanup/2` can also be used to test determinism of a goal: - -~~~~~ -?- setup_call_cleanup(true,(X=1;X=2), Det=yes). - -X = 1 ; - -X = 2, -Det = yes ; -~~~~~ - -This predicate is under consideration for inclusion into the ISO standard. -For compatibility with other Prolog implementations see `call_cleanup/2`. - - -*/ - -/** @pred setup_call_catcher_cleanup(: _Setup_,: _Goal_, + _Catcher_,: _CleanUpGoal_) - - -Similar to `setup_call_cleanup( _Setup_, _Goal_, _Cleanup_)` with -additional information on the reason of calling _Cleanup_. Prior -to calling _Cleanup_, _Catcher_ unifies with the termination -code. If this unification fails, _Cleanup_ is - *not* called. - - -*/ - -/** @pred on_cleanup(+ _CleanUpGoal_) - - -Any Predicate might registers a _CleanUpGoal_. The - _CleanUpGoal_ is put onto the current cleanup context. All such -CleanUpGoals are executed in reverse order of their registration when -the surrounding cleanup-context ends. This call will throw an exception -if a predicate tries to register a _CleanUpGoal_ outside of any -cleanup-context. - - -*/ - -/** @pred cleanup_all - - -Calls all pending CleanUpGoals and resets the cleanup-system to an -initial state. Should only be used as one of the last calls in the -main program. - - - -There are some private predicates which could be used in special -cases, such as manually setting up cleanup-contexts and registering -CleanUpGoals for other than the current cleanup-context. -Read the Source Luke. - - - */ - -/** @defgroup Timeout Calls With Timeout -@ingroup library -@{ - -The time_out/3 command relies on the alarm/3 built-in to -implement a call with a maximum time of execution. The command is -available with the `use_module(library(timeout))` command. - - - - @pred time_out(+ _Goal_, + _Timeout_, - _Result_) - - -Execute goal _Goal_ with time limited _Timeout_, where - _Timeout_ is measured in milliseconds. If the goal succeeds, unify - _Result_ with success. If the timer expires before the goal -terminates, unify _Result_ with time_out. - -This command is implemented by activating an alarm at procedure -entry. If the timer expires before the goal completes, the alarm will -throw an exception _timeout_. - -One should note that time_out/3 is not reentrant, that is, a goal -called from `time_out` should never itself call -time_out/3. Moreover, time_out/3 will deactivate any previous -alarms set by alarm/3 and vice-versa, hence only one of these -calls should be used in a program. - -Last, even though the timer is set in milliseconds, the current -implementation relies on alarm/3, and therefore can only offer -precision on the scale of seconds. - - - - - */ - -/** @defgroup Trees Updatable Binary Trees -@ingroup library -@{ - -The following queue manipulation routines are available once -included with the `use_module(library(trees))` command. - - - - @pred get_label(+ _Index_, + _Tree_, ? _Label_) - - -Treats the tree as an array of _N_ elements and returns the - _Index_-th. - - -*/ - -/** @pred list_to_tree(+ _List_, - _Tree_) - - -Takes a given _List_ of _N_ elements and constructs a binary - _Tree_. - - -*/ - -/** @pred map_tree(+ _Pred_, + _OldTree_, - _NewTree_) - - -Holds when _OldTree_ and _NewTree_ are binary trees of the same shape -and `Pred(Old,New)` is true for corresponding elements of the two trees. - - -*/ - -/** @pred put_label(+ _Index_, + _OldTree_, + _Label_, - _NewTree_) - - -constructs a new tree the same shape as the old which moreover has the -same elements except that the _Index_-th one is _Label_. - - -*/ - -/** @pred tree_size(+ _Tree_, - _Size_) - - -Calculates the number of elements in the _Tree_. - - -*/ - -/** @pred tree_to_list(+ _Tree_, - _List_) - - -Is the converse operation to list_to_tree. - - - - - */ - -/** @defgroup UGraphs Unweighted Graphs -@ingroup library -@{ - -The following graph manipulation routines are based in code originally -written by Richard O'Keefe. The code was then extended to be compatible -with the SICStus Prolog ugraphs library. The routines assume directed -graphs, undirected graphs may be implemented by using two edges. Graphs -are represented in one of two ways: - -+ The P-representation of a graph is a list of (from-to) vertex -pairs, where the pairs can be in any old order. This form is -convenient for input/output. - -The S-representation of a graph is a list of (vertex-neighbors) -pairs, where the pairs are in standard order (as produced by keysort) -and the neighbors of each vertex are also in standard order (as -produced by sort). This form is convenient for many calculations. - - -These built-ins are available once included with the -`use_module(library(ugraphs))` command. - -*/ - -/** @pred vertices_edges_to_ugraph(+ _Vertices_, + _Edges_, - _Graph_) - - -Given a graph with a set of vertices _Vertices_ and a set of edges - _Edges_, _Graph_ must unify with the corresponding -s-representation. Note that the vertices without edges will appear in - _Vertices_ but not in _Edges_. Moreover, it is sufficient for a -vertex to appear in _Edges_. - -~~~~~{.prolog} -?- vertices_edges_to_ugraph([],[1-3,2-4,4-5,1-5],L). - -L = [1-[3,5],2-[4],3-[],4-[5],5-[]] ? - -~~~~~ -In this case all edges are defined implicitly. The next example shows -three unconnected edges: - -~~~~~{.prolog} -?- vertices_edges_to_ugraph([6,7,8],[1-3,2-4,4-5,1-5],L). - -L = [1-[3,5],2-[4],3-[],4-[5],5-[],6-[],7-[],8-[]] ? - -~~~~~ - - -*/ - -/** @pred vertices(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with all vertices appearing in graph - _Graph_. In the next example: - -~~~~~{.prolog} -?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). - -L = [1,2,3,4,5] -~~~~~ - - -*/ - -/** @pred edges(+ _Graph_, - _Edges_) - - -Unify _Edges_ with all edges appearing in graph - _Graph_. In the next example: - -~~~~~{.prolog} -?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], V). - -L = [1,2,3,4,5] -~~~~~ - - -*/ - -/** @pred add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -vertices _Vertices_ to the graph _Graph_. In the next example: - -~~~~~{.prolog} -?- add_vertices([1-[3,5],2-[4],3-[],4-[5], - 5-[],6-[],7-[],8-[]], - [0,2,9,10,11], - NG). - -NG = [0-[],1-[3,5],2-[4],3-[],4-[5],5-[], - 6-[],7-[],8-[],9-[],10-[],11-[]] -~~~~~ - - -*/ - -/** @pred del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting the list of -vertices _Vertices_ and all the edges that start from or go to a -vertex in _Vertices_ to the graph _Graph_. In the next example: - -~~~~~{.prolog} -?- del_vertices([2,1],[1-[3,5],2-[4],3-[], - 4-[5],5-[],6-[],7-[2,6],8-[]],NL). - -NL = [3-[],4-[5],5-[],6-[],7-[6],8-[]] -~~~~~ - - -*/ - -/** @pred add_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -edges _Edges_ to the graph _Graph_. In the next example: - -~~~~~{.prolog} -?- add_edges([1-[3,5],2-[4],3-[],4-[5],5-[],6-[], - 7-[],8-[]],[1-6,2-3,3-2,5-7,3-2,4-5],NL). - -NL = [1-[3,5,6],2-[3,4],3-[2],4-[5],5-[7],6-[],7-[],8-[]] -~~~~~ - - -*/ - -/** @pred del_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by removing the list of -edges _Edges_ from the graph _Graph_. Notice that no vertices -are deleted. In the next example: - -~~~~~{.prolog} -?- del_edges([1-[3,5],2-[4],3-[],4-[5],5-[], - 6-[],7-[],8-[]], - [1-6,2-3,3-2,5-7,3-2,4-5,1-3],NL). - -NL = [1-[5],2-[4],3-[],4-[],5-[],6-[],7-[],8-[]] -~~~~~ - - -*/ - -/** @pred transpose(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained from _Graph_ by -replacing all edges of the form _V1-V2_ by edges of the form - _V2-V1_. The cost is `O(|V|^2)`. In the next example: - -~~~~~{.prolog} -?- transpose([1-[3,5],2-[4],3-[], - 4-[5],5-[],6-[],7-[],8-[]], NL). - -NL = [1-[],2-[],3-[1],4-[2],5-[1,4],6-[],7-[],8-[]] -~~~~~ -Notice that an undirected graph is its own transpose. - - -*/ - -/** @pred neighbors(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbors of vertex _Vertex_ -in _Graph_. If the vertice is not in the graph fail. In the next -example: - -~~~~~{.prolog} -?- neighbors(4,[1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], - NL). - -NL = [1,2,7,5] -~~~~~ - - -*/ - -/** @pred neighbours(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbours of vertex _Vertex_ -in _Graph_. In the next example: - -~~~~~{.prolog} -?- neighbours(4,[1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). - -NL = [1,2,7,5] -~~~~~ - - -*/ - -/** @pred complement(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with the graph complementary to _Graph_. -In the next example: - -~~~~~{.prolog} -?- complement([1-[3,5],2-[4],3-[], - 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). - -NL = [1-[2,4,6,7,8],2-[1,3,5,6,7,8],3-[1,2,4,5,6,7,8], - 4-[3,5,6,8],5-[1,2,3,4,6,7,8],6-[1,2,3,4,5,7,8], - 7-[1,2,3,4,5,6,8],8-[1,2,3,4,5,6,7]] -~~~~~ - - -*/ - -/** @pred compose(+ _LeftGraph_, + _RightGraph_, - _NewGraph_) - - -Compose the graphs _LeftGraph_ and _RightGraph_ to form _NewGraph_. -In the next example: - -~~~~~{.prolog} -?- compose([1-[2],2-[3]],[2-[4],3-[1,2,4]],L). - -L = [1-[4],2-[1,2,4],3-[]] -~~~~~ - - -*/ - -/** @pred top_sort(+ _Graph_, - _Sort_) - - -Generate the set of nodes _Sort_ as a topological sorting of graph - _Graph_, if one is possible. -In the next example we show how topological sorting works for a linear graph: - -~~~~~{.prolog} -?- top_sort([_138-[_219],_219-[_139], _139-[]],L). - -L = [_138,_219,_139] -~~~~~ - - -*/ - -/** @pred top_sort(+ _Graph_, - _Sort0_, - _Sort_) - -Generate the difference list _Sort_- _Sort0_ as a topological -sorting of graph _Graph_, if one is possible. - - -*/ - -/** @pred transitive_closure(+ _Graph_, + _Closure_) - - -Generate the graph _Closure_ as the transitive closure of graph - _Graph_. -In the next example: - -~~~~~{.prolog} -?- transitive_closure([1-[2,3],2-[4,5],4-[6]],L). - -L = [1-[2,3,4,5,6],2-[4,5,6],4-[6]] -~~~~~ - - -*/ - -/** @pred reachable(+ _Node_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the set of all vertices in graph - _Graph_ that are reachable from _Node_. In the next example: - -~~~~~{.prolog} -?- reachable(1,[1-[3,5],2-[4],3-[],4-[5],5-[]],V). - -V = [1,3,5] -~~~~~ - - - - - */ - -/** @defgroup DGraphs Directed Graphs -@ingroup library -@{ - -The following graph manipulation routines use the red-black tree library -to try to avoid linear-time scans of the graph for all graph -operations. Graphs are represented as a red-black tree, where the key is -the vertex, and the associated value is a list of vertices reachable -from that vertex through an edge (ie, a list of edges). - - - - @pred dgraph_new(+ _Graph_) - - -Create a new directed graph. This operation must be performed before -trying to use the graph. - - -*/ - -/** @pred dgraph_vertices(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with all vertices appearing in graph - _Graph_. - - -*/ - -/** @pred dgraph_edge(+ _N1_, + _N2_, + _Graph_) - - -Edge _N1_- _N2_ is an edge in directed graph _Graph_. - - -*/ - -/** @pred dgraph_edges(+ _Graph_, - _Edges_) - - -Unify _Edges_ with all edges appearing in graph - _Graph_. - - -*/ - -/** @pred dgraph_add_vertices(+ _Graph_, + _Vertex_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding -vertex _Vertex_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -vertices _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_del_vertex(+ _Graph_, + _Vertex_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting vertex - _Vertex_ and all the edges that start from or go to _Vertex_ to -the graph _Graph_. - - -*/ - -/** @pred dgraph_del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting the list of -vertices _Vertices_ and all the edges that start from or go to a -vertex in _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_add_edge(+ _Graph_, + _N1_, + _N2_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the edge - _N1_- _N2_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_add_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -edges _Edges_ to the graph _Graph_. - - -*/ - -/** @pred dgraph_del_edge(+ _Graph_, + _N1_, + _N2_, - _NewGraph_) - - -Succeeds if _NewGraph_ unifies with a new graph obtained by -removing the edge _N1_- _N2_ from the graph _Graph_. Notice -that no vertices are deleted. - - -*/ - -/** @pred dgraph_del_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by removing the list of -edges _Edges_ from the graph _Graph_. Notice that no vertices -are deleted. - - -*/ - -/** @pred dgraph_to_ugraph(+ _Graph_, - _UGraph_) - - -Unify _UGraph_ with the representation used by the _ugraphs_ -unweighted graphs library, that is, a list of the form - _V-Neighbors_, where _V_ is a node and _Neighbors_ the nodes -children. - - -*/ - -/** @pred ugraph_to_dgraph( + _UGraph_, - _Graph_) - - -Unify _Graph_ with the directed graph obtain from _UGraph_, -represented in the form used in the _ugraphs_ unweighted graphs -library. - - -*/ - -/** @pred dgraph_neighbors(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbors of vertex _Vertex_ -in _Graph_. If the vertice is not in the graph fail. - - -*/ - -/** @pred dgraph_neighbours(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbours of vertex _Vertex_ -in _Graph_. - - -*/ - -/** @pred dgraph_complement(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with the graph complementary to _Graph_. - - -*/ - -/** @pred dgraph_transpose(+ _Graph_, - _Transpose_) - - -Unify _NewGraph_ with a new graph obtained from _Graph_ by -replacing all edges of the form _V1-V2_ by edges of the form - _V2-V1_. - - -*/ - -/** @pred dgraph_compose(+ _Graph1_, + _Graph2_, - _ComposedGraph_) - - -Unify _ComposedGraph_ with a new graph obtained by composing - _Graph1_ and _Graph2_, ie, _ComposedGraph_ has an edge - _V1-V2_ iff there is a _V_ such that _V1-V_ in _Graph1_ -and _V-V2_ in _Graph2_. - - -*/ - -/** @pred dgraph_transitive_closure(+ _Graph_, - _Closure_) - - -Unify _Closure_ with the transitive closure of graph _Graph_. - - -*/ - -/** @pred dgraph_symmetric_closure(+ _Graph_, - _Closure_) - - -Unify _Closure_ with the symmetric closure of graph _Graph_, -that is, if _Closure_ contains an edge _U-V_ it must also -contain the edge _V-U_. - - -*/ - -/** @pred dgraph_top_sort(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with the topological sort of graph _Graph_. - - -*/ - -/** @pred dgraph_top_sort(+ _Graph_, - _Vertices_, ? _Vertices0_) - -Unify the difference list _Vertices_- _Vertices0_ with the -topological sort of graph _Graph_. - - -*/ - -/** @pred dgraph_min_path(+ _V1_, + _V1_, + _Graph_, - _Path_, ? _Costt_) - - -Unify the list _Path_ with the minimal cost path between nodes - _N1_ and _N2_ in graph _Graph_. Path _Path_ has cost - _Cost_. - - -*/ - -/** @pred dgraph_max_path(+ _V1_, + _V1_, + _Graph_, - _Path_, ? _Costt_) - - -Unify the list _Path_ with the maximal cost path between nodes - _N1_ and _N2_ in graph _Graph_. Path _Path_ has cost - _Cost_. - - -*/ - -/** @pred dgraph_min_paths(+ _V1_, + _Graph_, - _Paths_) - - -Unify the list _Paths_ with the minimal cost paths from node - _N1_ to the nodes in graph _Graph_. - - -*/ - -/** @pred dgraph_isomorphic(+ _Vs_, + _NewVs_, + _G0_, - _GF_) - - -Unify the list _GF_ with the graph isomorphic to _G0_ where -vertices in _Vs_ map to vertices in _NewVs_. - - -*/ - -/** @pred dgraph_path(+ _Vertex_, + _Graph_, ? _Path_) - - -The path _Path_ is a path starting at vertex _Vertex_ in graph - _Graph_. - - -*/ - -/** @pred dgraph_path(+ _Vertex_, + _Vertex1_, + _Graph_, ? _Path_) - -The path _Path_ is a path starting at vertex _Vertex_ in graph - _Graph_ and ending at path _Vertex2_. - - -*/ - -/** @pred dgraph_reachable(+ _Vertex_, + _Graph_, ? _Edges_) - - -The path _Path_ is a path starting at vertex _Vertex_ in graph - _Graph_. - - -*/ - -/** @pred dgraph_leaves(+ _Graph_, ? _Vertices_) - - -The vertices _Vertices_ have no outgoing edge in graph - _Graph_. - - - - - */ - -/** @defgroup UnDGraphs Undirected Graphs -@ingroup library -@{ - -The following graph manipulation routines use the red-black tree graph -library to implement undirected graphs. Mostly, this is done by having -two directed edges per undirected edge. - - - - @pred undgraph_new(+ _Graph_) - - -Create a new directed graph. This operation must be performed before -trying to use the graph. - - -*/ - -/** @pred undgraph_vertices(+ _Graph_, - _Vertices_) - - -Unify _Vertices_ with all vertices appearing in graph - _Graph_. - - -*/ - -/** @pred undgraph_edge(+ _N1_, + _N2_, + _Graph_) - - -Edge _N1_- _N2_ is an edge in undirected graph _Graph_. - - -*/ - -/** @pred undgraph_edges(+ _Graph_, - _Edges_) - - -Unify _Edges_ with all edges appearing in graph - _Graph_. - - -*/ - -/** @pred undgraph_add_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -vertices _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred undgraph_del_vertices(+ _Graph_, + _Vertices_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by deleting the list of -vertices _Vertices_ and all the edges that start from or go to a -vertex in _Vertices_ to the graph _Graph_. - - -*/ - -/** @pred undgraph_add_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by adding the list of -edges _Edges_ to the graph _Graph_. - - -*/ - -/** @pred undgraph_del_edges(+ _Graph_, + _Edges_, - _NewGraph_) - - -Unify _NewGraph_ with a new graph obtained by removing the list of -edges _Edges_ from the graph _Graph_. Notice that no vertices -are deleted. - - -*/ - -/** @pred undgraph_neighbors(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbors of vertex _Vertex_ -in _Graph_. If the vertice is not in the graph fail. - - -*/ - -/** @pred undgraph_neighbours(+ _Vertex_, + _Graph_, - _Vertices_) - - -Unify _Vertices_ with the list of neighbours of vertex _Vertex_ -in _Graph_. - - -*/ - -/** @pred undgraph_complement(+ _Graph_, - _NewGraph_) - - -Unify _NewGraph_ with the graph complementary to _Graph_. - - -*/ - -/** @pred dgraph_to_undgraph( + _DGraph_, - _UndGraph_) - - -Unify _UndGraph_ with the undirected graph obtained from the -directed graph _DGraph_. - - - - - */ - -/** @defgroup DBUsage Memory Usage in Prolog Data-Base -@ingroup library -@{ - -This library provides a set of utilities for studying memory usage in YAP. -The following routines are available once included with the -`use_module(library(dbusage))` command. - - -*/ - -/** @pred db_usage - - -Give general overview of data-base usage in the system. - - -*/ - -/** @pred db_static - - -List memory usage for every static predicate. - - -*/ - -/** @pred db_static(+ _Threshold_) - -List memory usage for every static predicate. Predicate must use more -than _Threshold_ bytes. - - -*/ - -/** @pred db_dynamic - - -List memory usage for every dynamic predicate. - - -*/ - -/** @pred db_dynamic(+ _Threshold_) - -List memory usage for every dynamic predicate. Predicate must use more -than _Threshold_ bytes. - - - - - */ - -/** @defgroup Lambda Lambda Expressions -@ingroup library -@{ - -This library, designed and implemented by Ulrich Neumerkel, provides -lambda expressions to simplify higher order programming based on `call/N`. - -Lambda expressions are represented by ordinary Prolog terms. There are -two kinds of lambda expressions: - -~~~~~{.prolog} - Free+\X1^X2^ ..^XN^Goal - - \X1^X2^ ..^XN^Goal -~~~~~ - -The second is a shorthand for` t+\X1^X2^..^XN^Goal`, where `Xi` are the parameters. - - _Goal_ is a goal or continuation (Syntax note: _Operators_ within _Goal_ -require parentheses due to the low precedence of the `^` operator). - -Free contains variables that are valid outside the scope of the lambda -expression. They are thus free variables within. - -All other variables of _Goal_ are considered local variables. They must -not appear outside the lambda expression. This restriction is -currently not checked. Violations may lead to unexpected bindings. - -In the following example the parentheses around `X>3` are necessary. - -~~~~~{.prolog} -?- use_module(library(lambda)). -?- use_module(library(apply)). - -?- maplist(\X^(X>3),[4,5,9]). -true. -~~~~~ - -In the following _X_ is a variable that is shared by both instances -of the lambda expression. The second query illustrates the cooperation -of continuations and lambdas. The lambda expression is in this case a -continuation expecting a further argument. - -~~~~~{.prolog} -?- Xs = [A,B], maplist(X+\Y^dif(X,Y), Xs). -Xs = [A, B], -dif(X, A), -dif(X, B). - -?- Xs = [A,B], maplist(X+\dif(X), Xs). -Xs = [A, B], -dif(X, A), -dif(X, B). - -~~~~~ - -The following queries are all equivalent. To see this, use -the fact `f(x,y)`. - -~~~~~{.prolog} -?- call(f,A1,A2). -?- call(\X^f(X),A1,A2). -?- call(\X^Y^f(X,Y), A1,A2). -?- call(\X^(X+\Y^f(X,Y)), A1,A2). -?- call(call(f, A1),A2). -?- call(f(A1),A2). -?- f(A1,A2). -A1 = x, -A2 = y. -~~~~~ - -Further discussions -at Ulrich Neumerker's page in . - - - */ - -/** @defgroup LAM LAM -@ingroup packages -@{ - -This library provides a set of utilities for interfacing with LAM MPI. -The following routines are available once included with the -`use_module(library(lam_mpi))` command. The yap should be -invoked using the LAM mpiexec or mpirun commands (see LAM manual for -more details). - - -*/ - -/** @pred mpi_init - - -Sets up the mpi environment. This predicate should be called before any other MPI predicate. - - -*/ - -/** @pred mpi_finalize - - -Terminates the MPI execution environment. Every process must call this predicate before exiting. - - -*/ - -/** @pred mpi_comm_size(- _Size_) - - -Unifies _Size_ with the number of processes in the MPI environment. - - -*/ - -/** @pred mpi_comm_rank(- _Rank_) - - -Unifies _Rank_ with the rank of the current process in the MPI environment. - - -*/ - -/** @pred mpi_version(- _Major_,- _Minor_) - - -Unifies _Major_ and _Minor_ with, respectively, the major and minor version of the MPI. - - -*/ - -/** @pred mpi_send(+ _Data_,+ _Dest_,+ _Tag_) - - - -Blocking communication predicate. The message in _Data_, with tag - _Tag_, is sent immediately to the processor with rank _Dest_. -The predicate succeeds after the message being sent. - - -*/ - -/** @pred mpi_isend(+ _Data_,+ _Dest_,+ _Tag_,- _Handle_) - - - -Non blocking communication predicate. The message in _Data_, with -tag _Tag_, is sent whenever possible to the processor with rank - _Dest_. An _Handle_ to the message is returned to be used to -check for the status of the message, using the `mpi_wait` or -`mpi_test` predicates. Until `mpi_wait` is called, the -memory allocated for the buffer containing the message is not -released. - - -*/ - -/** @pred mpi_recv(? _Source_,? _Tag_,- _Data_) - - - -Blocking communication predicate. The predicate blocks until a message -is received from processor with rank _Source_ and tag _Tag_. -The message is placed in _Data_. - - -*/ - -/** @pred mpi_irecv(? _Source_,? _Tag_,- _Handle_) - - - -Non-blocking communication predicate. The predicate returns an - _Handle_ for a message that will be received from processor with -rank _Source_ and tag _Tag_. Note that the predicate succeeds -immediately, even if no message has been received. The predicate -`mpi_wait_recv` should be used to obtain the data associated to -the handle. - - -*/ - -/** @pred mpi_wait_recv(? _Handle_,- _Status_,- _Data_) - - - -Completes a non-blocking receive operation. The predicate blocks until -a message associated with handle _Hanlde_ is buffered. The -predicate succeeds unifying _Status_ with the status of the -message and _Data_ with the message itself. - - -*/ - -/** @pred mpi_test_recv(? _Handle_,- _Status_,- _Data_) - - - -Provides information regarding a handle. If the message associated -with handle _Hanlde_ is buffered then the predicate succeeds -unifying _Status_ with the status of the message and _Data_ -with the message itself. Otherwise, the predicate fails. - - -*/ - -/** @pred mpi_wait(? _Handle_,- _Status_) - - - -Completes a non-blocking operation. If the operation was a -`mpi_send`, the predicate blocks until the message is buffered -or sent by the runtime system. At this point the send buffer is -released. If the operation was a `mpi_recv`, it waits until the -message is copied to the receive buffer. _Status_ is unified with -the status of the message. - - -*/ - -/** @pred mpi_test(? _Handle_,- _Status_) - - - -Provides information regarding the handle _Handle_, ie., if a -communication operation has been completed. If the operation -associate with _Hanlde_ has been completed the predicate succeeds -with the completion status in _Status_, otherwise it fails. - - -*/ - -/** @pred mpi_barrier - - -Collective communication predicate. Performs a barrier -synchronization among all processes. Note that a collective -communication means that all processes call the same predicate. To be -able to use a regular `mpi_recv` to receive the messages, one -should use `mpi_bcast2`. - - -*/ - -/** @pred mpi_bcast2(+ _Root_, ? _Data_) - - - -Broadcasts the message _Data_ from the process with rank _Root_ -to all other processes. - - -*/ - -/** @pred mpi_bcast3(+ _Root_, + _Data_, + _Tag_) - - -Broadcasts the message _Data_ with tag _Tag_ from the process with rank _Root_ -to all other processes. - - -*/ - -/** @pred mpi_ibcast(+ _Root_, + _Data_, + _Tag_) - - - -Non-blocking operation. Broadcasts the message _Data_ with tag _Tag_ -from the process with rank _Root_ to all other processes. - - -*/ - -/** @pred mpi_default_buffer_size(- _OldBufferSize_, ? _NewBufferSize_) - - - -The _OldBufferSize_ argument unifies with the current size of the -MPI communication buffer size and sets the communication buffer size - _NewBufferSize_. The buffer is used for assynchronous waiting and -for broadcast receivers. Notice that buffer is local at each MPI -process. - - -*/ - -/** @pred mpi_msg_size( _Msg_, - _MsgSize_) - - -Unify _MsgSize_ with the number of bytes YAP would need to send the -message _Msg_. - - -*/ - -/** @pred mpi_gc - - - -Attempts to perform garbage collection with all the open handles -associated with send and non-blocking broadcasts. For each handle it -tests it and the message has been delivered the handle and the buffer -are released. - - - - - */ - -/** @defgroup BDDs Binary Decision Diagrams and Friends -@ingroup packages -@{ - -This library provides an interface to the BDD package CUDD. It requires -CUDD compiled as a dynamic library. In Linux this is available out of -box in Fedora, but can easily be ported to other Linux -distributions. CUDD is available in the ports OSX package, and in -cygwin. To use it, call `:-use_module(library(bdd))`. - -The following predicates construct a BDD: - - -*/ - -/** @pred bdd_new(? _Exp_, - _BddHandle_) - -create a new BDD from the logical expression _Exp_. The expression -may include: - -+ Logical Variables: -a leaf-node can be a logical variable. -+ Constants 0 and 1 -a leaf-node can also be one of these two constants. -+ or( _X_, _Y_), _X_ \/ _Y_, _X_ + _Y_ -disjunction -+ and( _X_, _Y_), _X_ /\ _Y_, _X_ \* _Y_ -conjunction -+ nand( _X_, _Y_) -negated conjunction@ -+ nor( _X_, _Y_) -negated disjunction -+ xor( _X_, _Y_) -exclusive or -+ not( _X_), - _X_ -negation - - - -*/ - -/** @pred bdd_from_list(? _List_, ?_Vars_, - _BddHandle_) - -Convert a _List_ of logical expressions of the form above, that -includes the set of free variables _Vars_, into a BDD accessible -through _BddHandle_. - - -*/ - -/** @pred mtbdd_new(? _Exp_, - _BddHandle_) - -create a new algebraic decision diagram (ADD) from the logical -expression _Exp_. The expression may include: - -+ Logical Variables: -a leaf-node can be a logical variable, or parameter. -+ Number -a leaf-node can also be any number -+ _X_ \* _Y_ -product -+ _X_ + _Y_ -sum -+ _X_ - _Y_ -subtraction -+ or( _X_, _Y_), _X_ \/ _Y_ -logical or - - - -*/ - -/** @pred bdd_tree(+ _BDDHandle_, _Term_) - -Convert the BDD or ADD represented by _BDDHandle_ to a Prolog term -of the form `bdd( _Dir_, _Nodes_, _Vars_)` or `mtbdd( _Nodes_, _Vars_)`, respectively. The arguments are: - -+ - _Dir_ direction of the BDD, usually 1 -+ - _Nodes_ list of nodes in the BDD or ADD. - -In a BDD nodes may be pp (both terminals are positive) or pn -(right-hand-side is negative), and have four arguments: a logical -variable that will be bound to the value of the node, the logical -variable corresponding to the node, a logical variable, a 0 or a 1 with -the value of the left-hand side, and a logical variable, a 0 or a 1 -with the right-hand side. - -+ - _Vars_ are the free variables in the original BDD, or the parameters of the BDD/ADD. - -As an example, the BDD for the expression `X+(Y+X)\*(-Z)` becomes: - -~~~~~ -bdd(1,[pn(N2,X,1,N1),pp(N1,Y,N0,1),pn(N0,Z,1,1)],vs(X,Y,Z)) -~~~~~ - - -*/ - -/** @pred bdd_eval(+ _BDDHandle_, _Val_) - -Unify _Val_ with the value of the logical expression compiled in - _BDDHandle_ given an assignment to its variables. - -~~~~~ -bdd_new(X+(Y+X)*(-Z), BDD), -[X,Y,Z] = [0,0,0], -bdd_eval(BDD, V), -writeln(V). -~~~~~ -would write 0 in the standard output stream. - -The Prolog code equivalent to bdd_eval/2 is: - -~~~~~ - Tree = bdd(1, T, _Vs), - reverse(T, RT), - foldl(eval_bdd, RT, _, V). - -eval_bdd(pp(P,X,L,R), _, P) :- - P is ( X/\L ) \/ ( (1-X) /\ R ). -eval_bdd(pn(P,X,L,R), _, P) :- - P is ( X/\L ) \/ ( (1-X) /\ (1-R) ). -~~~~~ -First, the nodes are reversed to implement bottom-up evaluation. Then, -we use the `foldl` list manipulation predicate to walk every node, -computing the disjunction of the two cases and binding the output -variable. The top node gives the full expression value. Notice that -`(1- _X_)` implements negation. - - -*/ - -/** @pred bdd_size(+ _BDDHandle_, - _Size_) - -Unify _Size_ with the number of nodes in _BDDHandle_. - - -*/ - -/** @pred bdd_print(+ _BDDHandle_, + _File_) - -Output bdd _BDDHandle_ as a dot file to _File_. - - -*/ - -/** @pred bdd_to_probability_sum_product(+ _BDDHandle_, - _Prob_) - -Each node in a BDD is given a probability _Pi_. The total -probability of a corresponding sum-product network is _Prob_. - - -*/ - -/** @pred bdd_to_probability_sum_product(+ _BDDHandle_, - _Probs_, - _Prob_) -Each node in a BDD is given a probability _Pi_. The total -probability of a corresponding sum-product network is _Prob_, and -the probabilities of the inner nodes are _Probs_. - -In Prolog, this predicate would correspond to computing the value of a -BDD. The input variables will be bound to probabilities, eg -`[ _X_, _Y_, _Z_] = [0.3.0.7,0.1]`, and the previous -`eval_bdd` would operate over real numbers: - -~~~~~ - Tree = bdd(1, T, _Vs), - reverse(T, RT), - foldl(eval_prob, RT, _, V). - -eval_prob(pp(P,X,L,R), _, P) :- - P is X * L + (1-X) * R. -eval_prob(pn(P,X,L,R), _, P) :- - P is X * L + (1-X) * (1-R). -~~~~~ - -*/ - -/** @pred bdd_close( _BDDHandle_) - -close the BDD and release any resources it holds. - - - - - */ - -/** @defgroup Block_Diagram Block Diagram -@ingroup library -@{ - -This library provides a way of visualizing a prolog program using -modules with blocks. To use it use: -`:-use_module(library(block_diagram))`. - - -*/ - -/** @pred make_diagram(+inputfilename, +ouputfilename) - - - -This will crawl the files following the use_module, ensure_loaded directives withing the inputfilename. -The result will be a file in dot format. -You can make a pdf at the shell by asking `dot -Tpdf filename > output.pdf`. - - -*/ - -/** @pred make_diagram(+inputfilename, +ouputfilename, +predicate, +depth, +extension) - - -The same as make_diagram/2 but you can define how many of the imported/exporeted predicates will be shown with predicate, and how deep the crawler is allowed to go with depth. The extension is used if the file use module directives do not include a file extension. - - - -*/ - -/** @page SWIhYProlog_Emulation SWI-Prolog Emulation - -This library provides a number of SWI-Prolog builtins that are not by -default in YAP. This support is loaded with the -`expects_dialect(swi)` command. - - -*/ - -/** @pred append(? _List1_,? _List2_,? _List3_) - - -Succeeds when _List3_ unifies with the concatenation of _List1_ -and _List2_. The predicate can be used with any instantiation -pattern (even three variables). - - -*/ - -/** @pred between(+ _Low_,+ _High_,? _Value_) - - - - _Low_ and _High_ are integers, _High_ less or equal than - _Low_. If _Value_ is an integer, _Low_ less or equal than - _Value_ less or equal than _High_. When _Value_ is a -variable it is successively bound to all integers between _Low_ and - _High_. If _High_ is `inf`, between/3 is true iff - _Value_ less or equal than _Low_, a feature that is particularly -interesting for generating integers from a certain value. - - -*/ - -/** @pred chdir(+ _Dir_) - - - -Compatibility predicate. New code should use working_directory/2. - - -*/ - -/** @pred concat_atom(+ _List_,- _Atom_) - - - - _List_ is a list of atoms, integers or floating point numbers. Succeeds -if _Atom_ can be unified with the concatenated elements of _List_. If - _List_ has exactly 2 elements it is equivalent to `atom_concat/3`, -allowing for variables in the list. - - -*/ - -/** @pred concat_atom(? _List_,+ _Separator_,? _Atom_) - - -Creates an atom just like concat_atom/2, but inserts _Separator_ -between each pair of atoms. For example: - -~~~~~ -?- concat_atom([gnu, gnat], ', ', A). - -A = 'gnu, gnat' -~~~~~ - -(Unimplemented) This predicate can also be used to split atoms by -instantiating _Separator_ and _Atom_: - -~~~~~ -?- concat_atom(L, -, 'gnu-gnat'). - -L = [gnu, gnat] -~~~~~ - - -*/ - -/** @pred nth1(+ _Index_,? _List_,? _Elem_) - - -Succeeds when the _Index_-th element of _List_ unifies with - _Elem_. Counting starts at 1. - -Set environment variable. _Name_ and _Value_ should be -instantiated to atoms or integers. The environment variable will be -passed to `shell/[0-2]` and can be requested using `getenv/2`. -They also influence expand_file_name/2. - - -*/ - -/** @pred setenv(+ _Name_,+ _Value_) - - -Set environment variable. _Name_ and _Value_ should be -instantiated to atoms or integers. The environment variable will be -passed to `shell/[0-2]` and can be requested using `getenv/2`. -They also influence expand_file_name/2. - - -*/ - -/** @pred term_to_atom(? _Term_,? _Atom_) - - -Succeeds if _Atom_ describes a term that unifies with _Term_. When - _Atom_ is instantiated _Atom_ is converted and then unified with - _Term_. If _Atom_ has no valid syntax, a `syntax_error` -exception is raised. Otherwise _Term_ is `written` on _Atom_ -using write/1. - - -*/ - -/** @pred working_directory(- _Old_,+ _New_) - - - -Unify _Old_ with an absolute path to the current working directory -and change working directory to _New_. Use the pattern -`working_directory(CWD, CWD)` to get the current directory. See -also `absolute_file_name/2` and chdir/1. - - -*/ - -/** @pred _Term1_ =@= _Term2_ is semidet - - - -True iff _Term1_ and _Term2_ are structurally equivalent. I.e. if _Term1_ and _Term2_ are variants of each other. - - - - - */ - -/** @defgroup Invoking_Predicates_on_all_Members_of_a_List Invoking Predicates on all Members of a List -@ingroup library -@{ - - -All the predicates in this section call a predicate on all members of a -list or until the predicate called fails. The predicate is called via -`call/[2..]`, which implies common arguments can be put in -front of the arguments obtained from the list(s). For example: - -~~~~~ -?- maplist(plus(1), [0, 1, 2], X). - -X = [1, 2, 3] -~~~~~ - -we will phrase this as ` _Predicate_ is applied on ...` - - - - @pred maplist(+ _Pred_,+ _List_) - - - _Pred_ is applied successively on each element of _List_ until -the end of the list or _Pred_ fails. In the latter case -`maplist/2` fails. - - -*/ - -/** @pred maplist(+ _Pred_,+ _List1_,+ _List2_) - -Apply _Pred_ on all successive pairs of elements from - _List1_ and - _List2_. Fails if _Pred_ can not be applied to a -pair. See the example above. - - -*/ - -/** @pred maplist(+ _Pred_,+ _List1_,+ _List2_,+ _List4_) - -Apply _Pred_ on all successive triples of elements from _List1_, - _List2_ and _List3_. Fails if _Pred_ can not be applied to a -triple. See the example above. - - - - - */ - -/** @defgroup Forall Forall -@ingroup packages -@{ - - - -*/ - -/** @pred forall(+ _Cond_,+ _Action_) - - - - -For all alternative bindings of _Cond_ _Action_ can be proven. -The next example verifies that all arithmetic statements in the list - _L_ are correct. It does not say which is wrong if one proves wrong. - -~~~~~ -?- forall(member(Result = Formula, [2 = 1 + 1, 4 = 2 * 2]), - Result =:= Formula). -~~~~~ - - - -*/ - -/** @page SWIhYProlog_Global_Variables SWI Global variables - - -SWI-Prolog global variables are associations between names (atoms) and -terms. They differ in various ways from storing information using -assert/1 or recorda/3. - -+ The value lives on the Prolog (global) stack. This implies -that lookup time is independent from the size of the term. -This is particulary interesting for large data structures -such as parsed XML documents or the CHR global constraint -store. - -They support both global assignment using nb_setval/2 and -backtrackable assignment using b_setval/2. - -+ Only one value (which can be an arbitrary complex Prolog -term) can be associated to a variable at a time. - -+ Their value cannot be shared among threads. Each thread -has its own namespace and values for global variables. - -+ Currently global variables are scoped globally. We may -consider module scoping in future versions. - - -Both b_setval/2 and nb_setval/2 implicitly create a variable if the -referenced name does not already refer to a variable. - -Global variables may be initialised from directives to make them -available during the program lifetime, but some considerations are -necessary for saved-states and threads. Saved-states to not store global -variables, which implies they have to be declared with initialization/1 -to recreate them after loading the saved state. Each thread has -its own set of global variables, starting with an empty set. Using -`thread_inititialization/1` to define a global variable it will be -defined, restored after reloading a saved state and created in all -threads that are created after the registration. - - -*/ - -/** @pred b_setval(+ _Name_,+ _Value_) - - -Associate the term _Value_ with the atom _Name_ or replaces -the currently associated value with _Value_. If _Name_ does -not refer to an existing global variable a variable with initial value -`[]` is created (the empty list). On backtracking the -assignment is reversed. - - -*/ - -/** @pred b_getval(+ _Name_,- _Value_) - - -Get the value associated with the global variable _Name_ and unify -it with _Value_. Note that this unification may further instantiate -the value of the global variable. If this is undesirable the normal -precautions (double negation or copy_term/2) must be taken. The -b_getval/2 predicate generates errors if _Name_ is not an atom or -the requested variable does not exist. - - -*/ - -/** @pred nb_setval(+ _Name_,+ _Value_) - - -Associates a copy of _Value_ created with duplicate_term/2 -with the atom _Name_. Note that this can be used to set an -initial value other than `[]` prior to backtrackable assignment. - - -*/ - -/** @pred nb_getval(+ _Name_,- _Value_) - - -The nb_getval/2 predicate is a synonym for b_getval/2, introduced for -compatibility and symmetry. As most scenarios will use a particular -global variable either using non-backtrackable or backtrackable -assignment, using nb_getval/2 can be used to document that the -variable is used non-backtrackable. - - -*/ - -/** @pred nb_current(? _Name_,? _Value_) - - -Enumerate all defined variables with their value. The order of -enumeration is undefined. - - -*/ - -/** @pred nb_delete(? _Name_) - -Delete the named global variable. - - - - */ - -/** @defgroup Compatibility_of_Global_Variables Compatibility of Global Variables -@ingroup packages -@{ - -Global variables have been introduced by various Prolog -implementations recently. YAP follows their implementation in SWI-Prolog, itself -based on hProlog by Bart Demoen. Jan and Bart -decided that the semantics if hProlog nb_setval/2, which is -equivalent to nb_linkval/2 is not acceptable for normal Prolog -users as the behaviour is influenced by how builtin predicates -constructing terms (read/1, =../2, etc.) are implemented. - -GNU-Prolog provides a rich set of global variables, including arrays. -Arrays can be implemented easily in SWI-Prolog using functor/3 and -`setarg/3` due to the unrestricted arity of compound terms. - -*/ - -/** @page Extensions Extensions to Prolog - -YAP includes a number of extensions over the original Prolog -language. Next, we discuss support to the most important ones. - - - */ - -/** @defgroup Rational_Trees Rational Trees -@ingroup packages -@{ - -Prolog unification is not a complete implementation. For efficiency -considerations, Prolog systems do not perform occur checks while -unifying terms. As an example, `X = a(X)` will not fail but instead -will create an infinite term of the form `a(a(a(a(a(...)))))`, or -rational tree. - -Rational trees are now supported by default in YAP. In previous -versions, this was not the default and these terms could easily lead -to infinite computation. For example, `X = a(X), X = X` would -enter an infinite loop. - -The `RATIONAL_TREES` flag improves support for these -terms. Internal primitives are now aware that these terms can exist, and -will not enter infinite loops. Hence, the previous unification will -succeed. Another example, `X = a(X), ground(X)` will succeed -instead of looping. Other affected built-ins include the term comparison -primitives, numbervars/3, copy_term/2, and the internal -data base routines. The support does not extend to Input/Output routines -or to assert/1 YAP does not allow directly reading -rational trees, and you need to use `write_depth/2` to avoid -entering an infinite cycle when trying to write an infinite term. - - - */ - -/** @defgroup CohYroutining Co-routining -@ingroup packages -@{ - -Prolog uses a simple left-to-right flow of control. It is sometimes -convenient to change this control so that goals will only be executed -when conditions are fulfilled. This may result in a more "data-driven" -execution, or may be necessary to correctly implement extensions such as -negation by default. - -The `COROUTINING` flag enables this option. Note that the support for -coroutining will in general slow down execution. - -The following declaration is supported: - -+ block/1 -The argument to `block/1` is a condition on a goal or a conjunction -of conditions, with each element separated by commas. Each condition is -of the form `predname( _C1_,..., _CN_)`, where _N_ is the -arity of the goal, and each _CI_ is of the form `-`, if the -argument must suspend until the first such variable is bound, or -`?`, otherwise. - -+ wait/1 -The argument to `wait/1` is a predicate descriptor or a conjunction -of these predicates. These predicates will suspend until their first -argument is bound. - - -The following primitives are supported: - - -*/ - -/** @pred dif( _X_, _Y_) - - -Succeed if the two arguments do not unify. A call to dif/2 will -suspend if unification may still succeed or fail, and will fail if they -always unify. - - -*/ - -/** @pred freeze(? _X_,: _G_) - - -Delay execution of goal _G_ until the variable _X_ is bound. - - -*/ - -/** @pred frozen( _X_, _G_) - - -Unify _G_ with a conjunction of goals suspended on variable _X_, -or `true` if no goal has suspended. - - -*/ - -/** @pred when(+ _C_,: _G_) - - -Delay execution of goal _G_ until the conditions _C_ are -satisfied. The conditions are of the following form: - -+ _C1_, _C2_ -Delay until both conditions _C1_ and _C2_ are satisfied. -+ _C1_; _C2_ -Delay until either condition _C1_ or condition _C2_ is satisfied. -+ ?=( _V1_, _C2_) -Delay until terms _V1_ and _V1_ have been unified. -+ nonvar( _V_) -Delay until variable _V_ is bound. -+ ground( _V_) -Delay until variable _V_ is ground. - - -Note that when/2 will fail if the conditions fail. - - -*/ - -/** @pred call_residue(: _G_, _L_) - - - -Call goal _G_. If subgoals of _G_ are still blocked, return -a list containing these goals and the variables they are blocked in. The -goals are then considered as unblocked. The next example shows a case -where dif/2 suspends twice, once outside call_residue/2, -and the other inside: - -~~~~~ -?- dif(X,Y), - call_residue((dif(X,Y),(X = f(Z) ; Y = f(Z))), L). - -X = f(Z), -L = [[Y]-dif(f(Z),Y)], -dif(f(Z),Y) ? ; - -Y = f(Z), -L = [[X]-dif(X,f(Z))], -dif(X,f(Z)) ? ; - -no -~~~~~ -The system only reports one invocation of dif/2 as having -suspended. - - -*/ - -/** @pred call_residue_vars(: _G_, _L_) - - - -Call goal _G_ and unify _L_ with a list of all constrained variables created during execution of _G_: - -~~~~~ - ?- dif(X,Z), call_residue_vars(dif(X,Y),L). -dif(X,Z), call_residue_vars(dif(X,Y),L). -L = [Y], -dif(X,Z), -dif(X,Y) ? ; - -no -~~~~~ - - - - - */ - -/** @defgroup Attributed_Variables Attributed Variables -@ingroup packages -@{ - -YAP supports attributed variables, originally developed at OFAI by -Christian Holzbaur. Attributes are a means of declaring that an -arbitrary term is a property for a variable. These properties can be -updated during forward execution. Moreover, the unification algorithm is -aware of attributed variables and will call user defined handlers when -trying to unify these variables. - -Attributed variables provide an elegant abstraction over which one can -extend Prolog systems. Their main application so far has been in -implementing constraint handlers, such as Holzbaur's CLPQR, Fruewirth -and Holzbaur's CHR, and CLP(BN). - -Different Prolog systems implement attributed variables in different -ways. Traditionally, YAP has used the interface designed by SICStus -Prolog. This interface is still -available in the atts library, but from YAP-6.0.3 we recommend using -the hProlog, SWI style interface. The main reason to do so is that -most packages included in YAP that use attributed variables, such as CHR, CLP(FD), and CLP(QR), -rely on the SWI-Prolog interface. - - - */ - -/** @defgroup New_Style_Attribute_Declarations hProlog and SWI-Prolog style Attribute Declarations -@ingroup packages -@{ - -The following documentation is taken from the SWI-Prolog manual. - -Binding an attributed variable schedules a goal to be executed at the -first possible opportunity. In the current implementation the hooks are -executed immediately after a successful unification of the clause-head -or successful completion of a foreign language (built-in) predicate. Each -attribute is associated to a module and the hook attr_unify_hook/2 is -executed in this module. The example below realises a very simple and -incomplete finite domain reasoner. - -~~~~~ -:- module(domain, - [ domain/2 % Var, ?Domain - ]). -:- use_module(library(ordsets)). - -domain(X, Dom) :- - var(Dom), !, - get_attr(X, domain, Dom). -domain(X, List) :- - list_to_ord_set(List, Domain), - put_attr(Y, domain, Domain), - X = Y. - -% An attributed variable with attribute value Domain has been -% assigned the value Y - -attr_unify_hook(Domain, Y) :- - ( get_attr(Y, domain, Dom2) - -> ord_intersection(Domain, Dom2, NewDomain), - ( NewDomain == [] - -> fail - ; NewDomain = [Value] - -> Y = Value - ; put_attr(Y, domain, NewDomain) - ) - ; var(Y) - -> put_attr( Y, domain, Domain ) - ; ord_memberchk(Y, Domain) - ). - -% Translate attributes from this module to residual goals - -attribute_goals(X) --> - { get_attr(X, domain, List) }, - [domain(X, List)]. -~~~~~ - -Before explaining the code we give some example queries: - -The predicate `domain/2` fetches (first clause) or assigns -(second clause) the variable a domain, a set of values it can -be unified with. In the second clause first associates the domain -with a fresh variable and then unifies X to this variable to deal -with the possibility that X already has a domain. The -predicate attr_unify_hook/2 is a hook called after a variable with -a domain is assigned a value. In the simple case where the variable -is bound to a concrete value we simply check whether this value is in -the domain. Otherwise we take the intersection of the domains and either -fail if the intersection is empty (first example), simply assign the -value if there is only one value in the intersection (second example) or -assign the intersection as the new domain of the variable (third -example). The nonterminal `attribute_goals/3` is used to translate -remaining attributes to user-readable goals that, when executed, reinstate -these attributes. - - - - @pred put_attr(+ _Var_,+ _Module_,+ _Value_) - - - -If _Var_ is a variable or attributed variable, set the value for the -attribute named _Module_ to _Value_. If an attribute with this -name is already associated with _Var_, the old value is replaced. -Backtracking will restore the old value (i.e., an attribute is a mutable -term. See also `setarg/3`). This predicate raises a representation error if - _Var_ is not a variable and a type error if _Module_ is not an atom. - - -*/ - -/** @pred get_attr(+ _Var_,+ _Module_,- _Value_) - - - -Request the current _value_ for the attribute named _Module_. If - _Var_ is not an attributed variable or the named attribute is not -associated to _Var_ this predicate fails silently. If _Module_ -is not an atom, a type error is raised. - - -*/ - -/** @pred del_attr(+ _Var_,+ _Module_) - - - -Delete the named attribute. If _Var_ loses its last attribute it -is transformed back into a traditional Prolog variable. If _Module_ -is not an atom, a type error is raised. In all other cases this -predicate succeeds regardless whether or not the named attribute is -present. - - -*/ - -/** @pred attr_unify_hook(+ _AttValue_,+ _VarValue_) - - - -Hook that must be defined in the module an attributed variable refers -to. Is is called after the attributed variable has been -unified with a non-var term, possibly another attributed variable. - _AttValue_ is the attribute that was associated to the variable -in this module and _VarValue_ is the new value of the variable. -Normally this predicate fails to veto binding the variable to - _VarValue_, forcing backtracking to undo the binding. If - _VarValue_ is another attributed variable the hook often combines -the two attribute and associates the combined attribute with - _VarValue_ using put_attr/3. - - -*/ - -/** @pred attr_portray_hook(+ _AttValue_,+ _Var_) - - - -Called by write_term/2 and friends for each attribute if the option -`attributes(portray)` is in effect. If the hook succeeds the -attribute is considered printed. Otherwise `Module = ...` is -printed to indicate the existence of a variable. - - -*/ - -/** @pred attribute_goals(+ _Var_,- _Gs_,+ _GsRest_) - - - -This nonterminal, if it is defined in a module, is used by _copy_term/3_ -to project attributes of that module to residual goals. It is also -used by the toplevel to obtain residual goals after executing a query. - - -Normal user code should deal with put_attr/3, get_attr/3 and del_attr/2. -The routines in this section fetch or set the entire attribute list of a -variables. Use of these predicates is anticipated to be restricted to -printing and other special purpose operations. - - - - @pred get_attrs(+ _Var_,- _Attributes_) - - - -Get all attributes of _Var_. _Attributes_ is a term of the form -`att( _Module_, _Value_, _MoreAttributes_)`, where _MoreAttributes_ is -`[]` for the last attribute. - - -*/ - -/** @pred put_attrs(+ _Var_,+ _Attributes_) - - -Set all attributes of _Var_. See get_attrs/2 for a description of - _Attributes_. - - -*/ - -/** @pred del_attrs(+ _Var_) - - -If _Var_ is an attributed variable, delete all its -attributes. In all other cases, this predicate succeeds without -side-effects. - - -*/ - -/** @pred term_attvars(+ _Term_,- _AttVars_) - - - _AttVars_ is a list of all attributed variables in _Term_ and -its attributes. I.e., term_attvars/2 works recursively through -attributes. This predicate is Cycle-safe. - - -*/ - -/** @pred copy_term(? _TI_,- _TF_,- _Goals_) - -Term _TF_ is a variant of the original term _TI_, such that for -each variable _V_ in the term _TI_ there is a new variable _V'_ -in term _TF_ without any attributes attached. Attributed -variables are thus converted to standard variables. _Goals_ is -unified with a list that represents the attributes. The goal -`maplist(call, _Goals_)` can be called to recreate the -attributes. - -Before the actual copying, `copy_term/3` calls -`attribute_goals/1` in the module where the attribute is -defined. - - -*/ - -/** @pred copy_term_nat(? _TI_,- _TF_) - - -As copy_term/2. Attributes however, are not copied but replaced -by fresh variables. - - - - - */ - -/** @defgroup Old_Style_Attribute_Declarations SICStus Prolog style Attribute Declarations -@ingroup library -@{ - -Old style attribute declarations are activated through loading the library atts . The command - -~~~~~ -| ?- use_module(library(atts)). -~~~~~ -enables this form of use of attributed variables. The package provides the -following functionality: - -+ Each attribute must be declared first. Attributes are described by a functor -and are declared per module. Each Prolog module declares its own sets of -attributes. Different modules may have different functors with the same -module. -+ The built-in put_atts/2 adds or deletes attributes to a -variable. The variable may be unbound or may be an attributed -variable. In the latter case, YAP discards previous values for the -attributes. -+ The built-in get_atts/2 can be used to check the values of -an attribute associated with a variable. -+ The unification algorithm calls the user-defined predicate -verify_attributes/3 before trying to bind an attributed -variable. Unification will resume after this call. -+ The user-defined predicate -attribute_goal/2 converts from an attribute to a goal. -+ The user-defined predicate -project_attributes/2 is used from a set of variables into a set of -constraints or goals. One application of project_attributes/2 is in -the top-level, where it is used to output the set of -floundered constraints at the end of a query. - - - - */ - -/** @defgroup Attribute_Declarations Attribute Declarations -@ingroup Old_Style_Attribute_Declarations -@{ - -Attributes are compound terms associated with a variable. Each attribute -has a name which is private to the module in which the -attribute was defined. Variables may have at most one attribute with a -name. Attribute names are defined with the following declaration: - -~~~~~ -:- attribute AttributeSpec, ..., AttributeSpec. -~~~~~ - -where each _AttributeSpec_ has the form ( _Name_/ _Arity_). -One single such declaration is allowed per module _Module_. - -Although the YAP module system is predicate based, attributes are local -to modules. This is implemented by rewriting all calls to the -built-ins that manipulate attributes so that attribute names are -preprocessed depending on the module. The `user:goal_expansion/3` -mechanism is used for this purpose. - - - */ - -/** @defgroup Attribute_Manipulation Attribute Manipulation -@ingroup Old_Style_Attribute_Declarations -@{ - -The attribute manipulation predicates always work as follows: - -+ The first argument is the unbound variable associated with -attributes, -+ The second argument is a list of attributes. Each attribute will -be a Prolog term or a constant, prefixed with the + and - unary -operators. The prefix + may be dropped for convenience. - -The following three procedures are available to the user. Notice that -these built-ins are rewritten by the system into internal built-ins, and -that the rewriting process depends on the module on which the -built-ins have been invoked. - - -*/ - -/** @pred _Module_:get_atts( _-Var_, _?ListOfAttributes_) - - -Unify the list _?ListOfAttributes_ with the attributes for the unbound -variable _Var_. Each member of the list must be a bound term of the -form `+( _Attribute_)`, `-( _Attribute_)` (the kbd -prefix may be dropped). The meaning of + and - is: -+ +( _Attribute_) -Unifies _Attribute_ with a corresponding attribute associated with - _Var_, fails otherwise. - -+ -( _Attribute_) -Succeeds if a corresponding attribute is not associated with - _Var_. The arguments of _Attribute_ are ignored. - - -*/ - -/** @pred _Module_:put_atts( _-Var_, _?ListOfAttributes_) - - -Associate with or remove attributes from a variable _Var_. The -attributes are given in _?ListOfAttributes_, and the action depends -on how they are prefixed: -+ +( _Attribute_) -Associate _Var_ with _Attribute_. A previous value for the -attribute is simply replace (like with `set_mutable/2`). - -+ -( _Attribute_) -Remove the attribute with the same name. If no such attribute existed, -simply succeed. - - - - */ - -/** @defgroup Attributed_Unification Attributed Unification -@ingroup Old_Style_Attribute_Declarations -@{ - -The user-predicate predicate verify_attributes/3 is called when -attempting to unify an attributed variable which might have attributes -in some _Module_. - - -*/ - -/** @pred _Module_:verify_attributes( _-Var_, _+Value_, _-Goals_) - - - -The predicate is called when trying to unify the attributed variable - _Var_ with the Prolog term _Value_. Note that _Value_ may be -itself an attributed variable, or may contain attributed variables. The -goal verify_attributes/3 is actually called before _Var_ is -unified with _Value_. - -It is up to the user to define which actions may be performed by -verify_attributes/3 but the procedure is expected to return in - _Goals_ a list of goals to be called after _Var_ is -unified with _Value_. If verify_attributes/3 fails, the -unification will fail. - -Notice that the verify_attributes/3 may be called even if _Var_< -has no attributes in module Module. In this case the routine should -simply succeed with _Goals_ unified with the empty list. - - -*/ - -/** @pred attvar( _-Var_) - - -Succeed if _Var_ is an attributed variable. - - - - */ - -/** @defgroup Displaying_Attributes Displaying Attributes -@ingroup Old_Style_Attribute_Declarations -@{ - -Attributes are usually presented as goals. The following routines are -used by built-in predicates such as call_residue/2 and by the -Prolog top-level to display attributes: - - -*/ - -/** @pred _Module_:attribute_goal( _-Var_, _-Goal_) -User-defined procedure, called to convert the attributes in _Var_ to -a _Goal_. Should fail when no interpretation is available. - - - - - */ - -/** @defgroup Projecting_Attributes Projecting Attributes -@ingroup Old_Style_Attribute_Declarations -@{ - -Constraint solvers must be able to project a set of constraints to a set -of variables. This is useful when displaying the solution to a goal, but -may also be used to manipulate computations. The user-defined -project_attributes/2 is responsible for implementing this -projection. - - -*/ - -/** @pred _Module_:project_attributes( _+QueryVars_, _+AttrVars_) - - -Given a list of variables _QueryVars_ and list of attributed -variables _AttrVars_, project all attributes in _AttrVars_ to - _QueryVars_. Although projection is constraint system dependent, -typically this will involve expressing all constraints in terms of - _QueryVars_ and considering all remaining variables as existentially -quantified. - - -Projection interacts with attribute_goal/2 at the Prolog top -level. When the query succeeds, the system first calls -project_attributes/2. The system then calls -attribute_goal/2 to get a user-level representation of the -constraints. Typically, attribute_goal/2 will convert from the -original constraints into a set of new constraints on the projection, -and these constraints are the ones that will have an -attribute_goal/2 handler. - - - */ - -/** @defgroup Attribute_Examples Attribute Examples -@ingroup Old_Style_Attribute_Declarations -@{ - -The following two examples example is taken from the SICStus Prolog manual. It -sketches the implementation of a simple finite domain `solver`. Note -that an industrial strength solver would have to provide a wider range -of functionality and that it quite likely would utilize a more efficient -representation for the domains proper. The module exports a single -predicate `domain( _-Var_, _?Domain_)` which associates - _Domain_ (a list of terms) with _Var_. A variable can be -queried for its domain by leaving _Domain_ unbound. - -We do not present here a definition for project_attributes/2. -Projecting finite domain constraints happens to be difficult. - -~~~~~ -:- module(domain, [domain/2]). - -:- use_module(library(atts)). -:- use_module(library(ordsets), [ - ord_intersection/3, - ord_intersect/2, - list_to_ord_set/2 - ]). - -:- attribute dom/1. - -verify_attributes(Var, Other, Goals) :- - get_atts(Var, dom(Da)), !, % are we involved? - ( var(Other) -> % must be attributed then - ( get_atts(Other, dom(Db)) -> % has a domain? - ord_intersection(Da, Db, Dc), - Dc = [El|Els], % at least one element - ( Els = [] -> % exactly one element - Goals = [Other=El] % implied binding - ; Goals = [], - put_atts(Other, dom(Dc))% rescue intersection - ) - ; Goals = [], - put_atts(Other, dom(Da)) % rescue the domain - ) - ; Goals = [], - ord_intersect([Other], Da) % value in domain? - ). -verify_attributes(_, _, []). % unification triggered - % because of attributes - % in other modules - -attribute_goal(Var, domain(Var,Dom)) :- % interpretation as goal - get_atts(Var, dom(Dom)). - -domain(X, Dom) :- - var(Dom), !, - get_atts(X, dom(Dom)). -domain(X, List) :- - list_to_ord_set(List, Set), - Set = [El|Els], % at least one element - ( Els = [] -> % exactly one element - X = El % implied binding - ; put_atts(Fresh, dom(Set)), - X = Fresh % may call - % verify_attributes/3 - ). -~~~~~ - -Note that the _implied binding_ `Other=El` was deferred until after -the completion of `verify_attribute/3`. Otherwise, there might be a -danger of recursively invoking `verify_attribute/3`, which might bind -`Var`, which is not allowed inside the scope of `verify_attribute/3`. -Deferring unifications into the third argument of `verify_attribute/3` -effectively serializes the calls to `verify_attribute/3`. - -Assuming that the code resides in the file domain.yap, we -can use it via: - -~~~~~ -| ?- use_module(domain). -~~~~~ - -Let's test it: - -~~~~~ -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]). - -domain(X,[1,5,6,7]), -domain(Y,[3,4,5,6]), -domain(Z,[1,6,7,8]) ? - -yes -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), - X=Y. - -Y = X, -domain(X,[5,6]), -domain(Z,[1,6,7,8]) ? - -yes -| ?- domain(X,[5,6,7,1]), domain(Y,[3,4,5,6]), domain(Z,[1,6,7,8]), - X=Y, Y=Z. - -X = 6, -Y = 6, -Z = 6 -~~~~~ - -To demonstrate the use of the _Goals_ argument of -verify_attributes/3, we give an implementation of -freeze/2. We have to name it `myfreeze/2` in order to -avoid a name clash with the built-in predicate of the same name. - -~~~~~ -:- module(myfreeze, [myfreeze/2]). - -:- use_module(library(atts)). - -:- attribute frozen/1. - -verify_attributes(Var, Other, Goals) :- - get_atts(Var, frozen(Fa)), !, % are we involved? - ( var(Other) -> % must be attributed then - ( get_atts(Other, frozen(Fb)) % has a pending goal? - -> put_atts(Other, frozen((Fa,Fb))) % rescue conjunction - ; put_atts(Other, frozen(Fa)) % rescue the pending goal - ), - Goals = [] - ; Goals = [Fa] - ). -verify_attributes(_, _, []). - -attribute_goal(Var, Goal) :- % interpretation as goal - get_atts(Var, frozen(Goal)). - -myfreeze(X, Goal) :- - put_atts(Fresh, frozen(Goal)), - Fresh = X. -~~~~~ - -Assuming that this code lives in file myfreeze.yap, -we would use it via: - -~~~~~ -| ?- use_module(myfreeze). -| ?- myfreeze(X,print(bound(x,X))), X=2. - -bound(x,2) % side effect -X = 2 % bindings -~~~~~ - -The two solvers even work together: - -~~~~~ -| ?- myfreeze(X,print(bound(x,X))), domain(X,[1,2,3]), - domain(Y,[2,10]), X=Y. - -bound(x,2) % side effect -X = 2, % bindings -Y = 2 -~~~~~ - -The two example solvers interact via bindings to shared attributed -variables only. More complicated interactions are likely to be found -in more sophisticated solvers. The corresponding -verify_attributes/3 predicates would typically refer to the -attributes from other known solvers/modules via the module prefix in -` _Module_:get_atts/2`. - - - */ - -/** @defgroup CLPR Constraint Logic Programming over Reals -@ingroup packages -@{ - -YAP now uses the CLP(R) package developed by Leslie De Koninck, -K.U. Leuven as part of a thesis with supervisor Bart Demoen and daily -advisor Tom Schrijvers, and distributed with SWI-Prolog. - -This CLP(R) system is a port of the CLP(Q,R) system of Sicstus Prolog -and YAP by Christian Holzbaur: Holzbaur C.: OFAI clp(q,r) Manual, -Edition 1.3.3, Austrian Research Institute for Artificial -Intelligence, Vienna, TR-95-09, 1995, - This -port only contains the part concerning real arithmetics. This manual -is roughly based on the manual of the above mentioned *CLP(QR)* -implementation. - -Please note that the clpr library is not an -`autoload` library and therefore this library must be loaded -explicitely before using it: - -~~~~~ -:- use_module(library(clpr)). -~~~~~ - - - */ - -/** @defgroup CLPR_Solver_Predicates Solver Predicates -@ingroup CLPR -@{ - - -The following predicates are provided to work with constraints: - - -*/ - -/** @pred {+ _Constraints_} is det -Adds the constraints given by _Constraints_ to the constraint store. - - -*/ - -/** @pred entailed(+ _Constraint_) -Succeeds if _Constraint_ is necessarily true within the current -constraint store. This means that adding the negation of the constraint -to the store results in failure. - - -*/ - -/** @pred inf(+ _Expression_,- _Inf_) -Computes the infimum of _Expression_ within the current state of the -constraint store and returns that infimum in _Inf_. This predicate -does not change the constraint store. - - -*/ - -/** @pred inf(+ _Expression_,- _Sup_) -Computes the supremum of _Expression_ within the current state of -the constraint store and returns that supremum in _Sup_. This -predicate does not change the constraint store. - - -*/ - -/** @pred min(+ _Expression_) -Minimizes _Expression_ within the current constraint store. This is -the same as computing the infimum and equation the expression to that -infimum. - - -*/ - -/** @pred max(+ _Expression_) -Maximizes _Expression_ within the current constraint store. This is -the same as computing the supremum and equating the expression to that -supremum. - - -*/ - -/** @pred bb_inf(+ _Ints_,+ _Expression_,- _Inf_,- _Vertext_,+ _Eps_) -Computes the infimum of _Expression_ within the current constraint -store, with the additional constraint that in that infimum, all -variables in _Ints_ have integral values. _Vertex_ will contain -the values of _Ints_ in the infimum. _Eps_ denotes how much a -value may differ from an integer to be considered an integer. E.g. when - _Eps_ = 0.001, then X = 4.999 will be considered as an integer (5 in -this case). _Eps_ should be between 0 and 0.5. - - -*/ - -/** @pred bb_inf(+ _Ints_,+ _Expression_,- _Inf_) -The same as bb_inf/5 but without returning the values of the integers -and with an eps of 0.001. - - -*/ - -/** @pred dump(+ _Target_,+ _Newvars_,- _CodedAnswer_) -Returns the constraints on _Target_ in the list _CodedAnswer_ -where all variables of _Target_ have veen replaced by _NewVars_. -This operation does not change the constraint store. E.g. in - -~~~~~ -dump([X,Y,Z],[x,y,z],Cons) -~~~~~ - - _Cons_ will contain the constraints on _X_, _Y_ and - _Z_ where these variables have been replaced by atoms `x`, `y` and `z`. - - - - - */ - -/** @defgroup CLPR_Syntax Syntax of the predicate arguments -@ingroup packages -@{ - - -The arguments of the predicates defined in the subsection above are -defined in the following table. Failing to meet the syntax rules will -result in an exception. - -~~~~~ - ---> \ single constraint \ - | , \ conjunction \ - | ; \ disjunction \ - - ---> {<} \ less than \ - | {>} \ greater than \ - | {=<} \ less or equal \ - | {<=}(, ) \ less or equal \ - | {>=} \ greater or equal \ - | {=\=} \ not equal \ - | =:= \ equal \ - | = \ equal \ - - ---> \ Prolog variable \ - | \ Prolog number (float, integer) \ - | + \ unary plus \ - | - \ unary minus \ - | + \ addition \ - | - \ substraction \ - | * \ multiplication \ - | / \ division \ - | abs() \ absolute value \ - | sin() \ sine \ - | cos() \ cosine \ - | tan() \ tangent \ - | exp() \ exponent \ - | pow() \ exponent \ - | {^} \ exponent \ - | min(, ) \ minimum \ - | max(, ) \ maximum \ -~~~~~ - - - */ - -/** @defgroup CLPR_Unification Use of unification -@ingroup CLPR -@{ - -Instead of using the `{}/1` predicate, you can also use the standard -unification mechanism to store constraints. The following code samples -are equivalent: - -+ Unification with a variable - -~~~~~ -{X =:= Y} -{X = Y} -X = Y -~~~~~ - -+ Unification with a number - -~~~~~ -{X =:= 5.0} -{X = 5.0} -X = 5.0 -~~~~~ - - - - - */ - -/** @defgroup CLPR_NonhYlinear_Constraints Non-Linear Constraints -@ingroup CLPR -@{ - - -In this version, non-linear constraints do not get solved until certain -conditions are satisfied. We call these conditions the isolation axioms. -They are given in the following table. - -~~~~~ -A = B * C when B or C is ground or // A = 5 * C or A = B * 4 \\ - A and (B or C) are ground // 20 = 5 * C or 20 = B * 4 \\ - -A = B / C when C is ground or // A = B / 3 - A and B are ground // 4 = 12 / C - -X = min(Y,Z) when Y and Z are ground or // X = min(4,3) -X = max(Y,Z) Y and Z are ground // X = max(4,3) -X = abs(Y) Y is ground // X = abs(-7) - -X = pow(Y,Z) when X and Y are ground or // 8 = 2 ^ Z -X = exp(Y,Z) X and Z are ground // 8 = Y ^ 3 -X = Y ^ Z Y and Z are ground // X = 2 ^ 3 - -X = sin(Y) when X is ground or // 1 = sin(Y) -X = cos(Y) Y is ground // X = sin(1.5707) -X = tan(Y) -~~~~~ - -@section CHR CHR: Constraint Handling Rules -@ingroup packages - -This chapter is written by Tom Schrijvers, K.U. Leuven for the hProlog -system. Adjusted by Jan Wielemaker to fit the SWI-Prolog documentation -infrastructure and remove hProlog specific references. - -The CHR system of SWI-Prolog is the K.U.Leuven CHR system. The runtime -environment is written by Christian Holzbaur and Tom Schrijvers while the -compiler is written by Tom Schrijvers. Both are integrated with SWI-Prolog -and licenced under compatible conditions with permission from the authors. - -The main reference for SWI-Prolog's CHR system is: - -+ T. Schrijvers, and B. Demoen, The K.U.Leuven CHR System: Implementation and Application, First Workshop on Constraint Handling Rules: Selected -Contributions (Fruwirth, T. and Meister, M., eds.), pp. 1--5, 2004. - - - - */ - -/** @defgroup CHR_Introduction Introduction -@ingroup CHR -@{ - - -Constraint Handling Rules (CHR) is a committed-choice bottom-up language -embedded in Prolog. It is designed for writing constraint solvers and is -particularily useful for providing application-specific constraints. -It has been used in many kinds of applications, like scheduling, -model checking, abduction, type checking among many others. - -CHR has previously been implemented in other Prolog systems (SICStus, -Eclipse, Yap), Haskell and Java. This CHR system is based on the -compilation scheme and runtime environment of CHR in SICStus. - -In this documentation we restrict ourselves to giving a short overview -of CHR in general and mainly focus on elements specific to this -implementation. For a more thorough review of CHR we refer the reader to -[Freuhwirth:98]. More background on CHR can be found at the CHR web site. - - - */ - -/** @defgroup CHR_Syntax_and_Semantics Syntax and Semantics -@ingroup packages -@{ - - - - - */ - -/** @defgroup CHR_Syntax CHR Syntax -Wingroup CHR -@{ - -The syntax of CHR rules in hProlog is the following: - -~~~~~ -rules --> rule, rules. -rules --> []. - -rule --> name, actual_rule, pragma, [atom(`.`)]. - -name --> atom, [atom(`@`)]. -name --> []. - -actual_rule --> simplification_rule. -actual_rule --> propagation_rule. -actual_rule --> simpagation_rule. - -simplification_rule --> constraints, [atom(`<=>`)], guard, body. -propagation_rule --> constraints, [atom(`==>`)], guard, body. -simpagation_rule --> constraints, [atom(`\`)], constraints, [atom(`<=>`)], - guard, body. - -constraints --> constraint, constraint_id. -constraints --> constraint, [atom(`,`)], constraints. - -constraint --> compound_term. - -constraint_id --> []. -constraint_id --> [atom(`#`)], variable. - -guard --> []. -guard --> goal, [atom(`|`)]. - -body --> goal. - -pragma --> []. -pragma --> [atom(`pragma`)], actual_pragmas. - -actual_pragmas --> actual_pragma. -actual_pragmas --> actual_pragma, [atom(`,`)], actual_pragmas. - -actual_pragma --> [atom(`passive(`)], variable, [atom(`)`)]. - -~~~~~ - -Additional syntax-related terminology: - -+ *head:* the constraints in an `actual_rule` before -the arrow (either `<=>` or `==>`) - - - - */ - -/** @defgroup Semantics Semantics -@ingroup CHR -@{ - - -In this subsection the operational semantics of CHR in Prolog are presented -informally. They do not differ essentially from other CHR systems. - -When a constraint is called, it is considered an active constraint and -the system will try to apply the rules to it. Rules are tried and executed -sequentially in the order they are written. - -A rule is conceptually tried for an active constraint in the following -way. The active constraint is matched with a constraint in the head of -the rule. If more constraints appear in the head they are looked for -among the suspended constraints, which are called passive constraints in -this context. If the necessary passive constraints can be found and all -match with the head of the rule and the guard of the rule succeeds, then -the rule is committed and the body of the rule executed. If not all the -necessary passive constraint can be found, the matching fails or the -guard fails, then the body is not executed and the process of trying and -executing simply continues with the following rules. If for a rule, -there are multiple constraints in the head, the active constraint will -try the rule sequentially multiple times, each time trying to match with -another constraint. - -This process ends either when the active constraint disappears, i.e. it -is removed by some rule, or after the last rule has been processed. In -the latter case the active constraint becomes suspended. - -A suspended constraint is eligible as a passive constraint for an active -constraint. The other way it may interact again with the rules, is when -a variable appearing in the constraint becomes bound to either a nonvariable -or another variable involved in one or more constraints. In that case the -constraint is triggered, i.e. it becomes an active constraint and all -the rules are tried. - - - */ - -/** @defgroup Rule_Types -@ingroup CHR -@{ - -There are three different kinds of rules, each with their specific semantics: - -+ simplification -The simplification rule removes the constraints in its head and calls its body. - -+ propagation -The propagation rule calls its body exactly once for the constraints in -its head. - -+ simpagation -The simpagation rule removes the constraints in its head after the -`\` and then calls its body. It is an optimization of -simplification rules of the form: \[constraints_1, constraints_2 <=> -constraints_1, body \] Namely, in the simpagation form: - -~~~~~ -constraints1 \ constraints2 <=> body -~~~~~ - _constraints1_ -constraints are not called in the body. - - - - */ - -/** @defgroup CHR_Rule_Names Rule Names -@ingroup CHR -@{ - -Naming a rule is optional and has no semantical meaning. It only functions -as documentation for the programmer. - - - */ - -/** @defgroup CHRPragmas Pragmas -@ingroup CHR_Rule_Names -@{ - -The semantics of the pragmas are: - -+ passive(Identifier) -The constraint in the head of a rule _Identifier_ can only act as a -passive constraint in that rule. - - -Additional pragmas may be released in the future. - - - */ - -/** @defgroup CHR_Options Options -@ingroup CHR_Rule_Names -@{ - -It is possible to specify options that apply to all the CHR rules in the module. -Options are specified with the `option/2` declaration: - -~~~~~ - option(Option,Value). -~~~~~ - -Available options are: - -+ check_guard_bindings -This option controls whether guards should be checked for illegal -variable bindings or not. Possible values for this option are -`on`, to enable the checks, and `off`, to disable the -checks. - -+ optimize -This is an experimental option controlling the degree of optimization. -Possible values are `full`, to enable all available -optimizations, and `off` (default), to disable all optimizations. -The default is derived from the SWI-Prolog flag `optimise`, where -`true` is mapped to `full`. Therefore the commandline -option `-O` provides full CHR optimization. -If optimization is enabled, debugging should be disabled. - -+ debug -This options enables or disables the possibility to debug the CHR code. -Possible values are `on` (default) and `off`. See -`debugging` for more details on debugging. The default is -derived from the prolog flag `generate_debug_info`, which -is `true` by default. See `-nodebug`. -If debugging is enabled, optimization should be disabled. - -+ mode -This option specifies the mode for a particular constraint. The -value is a term with functor and arity equal to that of a constraint. -The arguments can be one of `-`, `+` or `?`. -The latter is the default. The meaning is the following: - -+ - -The corresponding argument of every occurrence -of the constraint is always unbound. -+ + -The corresponding argument of every occurrence -of the constraint is always ground. -+ ? -The corresponding argument of every occurrence -of the constraint can have any instantiation, which may change -over time. This is the default value. - -The declaration is used by the compiler for various optimizations. -Note that it is up to the user the ensure that the mode declaration -is correct with respect to the use of the constraint. -This option may occur once for each constraint. - -+ type_declaration -This option specifies the argument types for a particular constraint. The -value is a term with functor and arity equal to that of a constraint. -The arguments can be a user-defined type or one of -the built-in types: - -+ int -The corresponding argument of every occurrence -of the constraint is an integer number. -+ float -...{} a floating point number. -+ number -...{} a number. -+ natural -...{} a positive integer. -+ any -The corresponding argument of every occurrence -of the constraint can have any type. This is the default value. - - -Currently, type declarations are only used to improve certain -optimizations (guard simplification, occurrence subsumption, ...{}). - -+ type_definition -This option defines a new user-defined type which can be used in -type declarations. The value is a term of the form -`type(` _name_`,` _list_`)`, where - _name_ is a term and _list_ is a list of alternatives. -Variables can be used to define generic types. Recursive definitions -are allowed. Examples are - -~~~~~ -type(bool,[true,false]). -type(complex_number,[float + float * i]). -type(binary_tree(T),[ leaf(T) | node(binary_tree(T),binary_tree(T)) ]). -type(list(T),[ [] | [T | list(T)]). -~~~~~ - - - -The mode, type_declaration and type_definition options are provided -for backward compatibility. The new syntax is described below. - - - */ - -/** @defgroup CHR_in_YAP_Programs CHR in YAP Programs -@ingroup CHR -@{ - - -The CHR constraints defined in a particulary chr file are -associated with a module. The default module is `user`. One should -never load different chr files with the same CHR module name. - - - */ - -/** @defgroup Constraint_declaration Constraint declaration -@ingroup CHR_in_YAP_Programs -@{ - - -Every constraint used in CHR rules has to be declared. -There are two ways to do this. The old style is as follows: - -~~~~~ -option(type_definition,type(list(T),[ [] , [T|list(T)] ]). -option(mode,foo(+,?)). -option(type_declaration,foo(list(int),float)). -:- constraints foo/2, bar/0. -~~~~~ - -The new style is as follows: - -~~~~~ -:- chr_type list(T) ---> [] ; [T|list(T)]. -:- constraints foo(+list(int),?float), bar. -~~~~~ - - - */ - -/** @defgroup Compilation Compilation - -The@{ - SWI-Prolog CHR compiler exploits term_expansion/2 rules to translate -the constraint handling rules to plain Prolog. These rules are loaded -from the library chr. They are activated if the compiled file -has the chr extension or after finding a declaration of the -format below. - -~~~~~ -:- constraints ... -~~~~~ - -It is adviced to define CHR rules in a module file, where the module -declaration is immediately followed by including the chr -library as examplified below: - -~~~~~ -:- module(zebra, [ zebra/0 ]). -:- use_module(library(chr)). - -:- constraints ... -~~~~~ - -Using this style CHR rules can be defined in ordinary Prolog -pl files and the operator definitions required by CHR do not -leak into modules where they might cause conflicts. - - - */ - -/** @defgroup CHR_Debugging Debugging -@ingroup CHR -@{ - - - -The CHR debugging facilities are currently rather limited. Only tracing -is currently available. To use the CHR debugging facilities for a CHR -file it must be compiled for debugging. Generating debug info is -controlled by the CHR option debug, whose default is derived -from the SWI-Prolog flag `generate_debug_info`. Therefore debug -info is provided unless the `-nodebug` is used. - - - */ - -/** @defgroup Ports Ports -@ingroup CHR -@{ - - -For CHR constraints the four standard ports are defined: - -+ call -A new constraint is called and becomes active. -+ exit -An active constraint exits: it has either been inserted in the store after -trying all rules or has been removed from the constraint store. -+ fail -An active constraint fails. -+ redo -An active constraint starts looking for an alternative solution. - - -In addition to the above ports, CHR constraints have five additional -ports: - -+ wake -A suspended constraint is woken and becomes active. -+ insert -An active constraint has tried all rules and is suspended in -the constraint store. -+ remove -An active or passive constraint is removed from the constraint -store, if it had been inserted. -+ try -An active constraints tries a rule with possibly -some passive constraints. The try port is entered -just before committing to the rule. -+ apply -An active constraints commits to a rule with possibly -some passive constraints. The apply port is entered -just after committing to the rule. - - - - */ - -/** @defgroup Tracing Tracing -@ingroup CHR -@{ - - -Tracing is enabled with the chr_trace/0 predicate -and disabled with the chr_notrace/0 predicate. - -When enabled the tracer will step through the `call`, -`exit`, `fail`, `wake` and `apply` ports, -accepting debug commands, and simply write out the other ports. - -The following debug commans are currently supported: - -~~~~~ - CHR debug options: - - creep c creep - s skip - g ancestors - n nodebug - b break - a abort - f fail - ? help h help -~~~~~ - -Their meaning is: - -+ creep -Step to the next port. -+ skip -Skip to exit port of this call or wake port. -+ ancestors -Print list of ancestor call and wake ports. -+ nodebug -Disable the tracer. -+ break -Enter a recursive Prolog toplevel. See break/0. -+ abort -Exit to the toplevel. See abort/0. -+ fail -Insert failure in execution. -+ help -Print the above available debug options. - - - - */ - -/** @defgroup CHR_Debugging_Predicates CHR Debugging Predicates -@ingroup CHR -@{ - - -The chr module contains several predicates that allow -inspecting and printing the content of the constraint store. - -+ chr_trace -Activate the CHR tracer. By default the CHR tracer is activated and -deactivated automatically by the Prolog predicates trace/0 and -notrace/0. - - -*/ - -/** @pred chr_notrace -De-activate the CHR tracer. By default the CHR tracer is activated and -deactivated automatically by the Prolog predicates trace/0 and -notrace/0. - -+ chr_leash/0 - -Define the set of CHR ports on which the CHR -tracer asks for user intervention (i.e. stops). _Spec_ is either a -list of ports or a predefined `alias`. Defined aliases are: -`full` to stop at all ports, `none` or `off` to never -stop, and `default` to stop at the `call`, `exit`, -`fail`, `wake` and `apply` ports. See also leash/1. - - -*/ - -/** @pred chr_show_store(+ _Mod_) -Prints all suspended constraints of module _Mod_ to the standard -output. This predicate is automatically called by the SWI-Prolog toplevel at -the end of each query for every CHR module currently loaded. The prolog-flag -`chr_toplevel_show_store` controls whether the toplevel shows the -constraint stores. The value `true` enables it. Any other value -disables it. - - - - - */ - -/** @defgroup CHR_Examples Examples -@ingroup CHR -@{ - - - -Here are two example constraint solvers written in CHR. - -+ -The program below defines a solver with one constraint, -`leq/2`, which is a less-than-or-equal constraint. - -~~~~~ -:- module(leq,[cycle/3, leq/2]). -:- use_module(library(chr)). - -:- constraints leq/2. -reflexivity @ leq(X,X) <=> true. -antisymmetry @ leq(X,Y), leq(Y,X) <=> X = Y. -idempotence @ leq(X,Y) \ leq(X,Y) <=> true. -transitivity @ leq(X,Y), leq(Y,Z) ==> leq(X,Z). - -cycle(X,Y,Z):- - leq(X,Y), - leq(Y,Z), - leq(Z,X). -~~~~~ - -+ -The program below implements a simple finite domain -constraint solver. - -~~~~~ -:- module(dom,[dom/2]). -:- use_module(library(chr)). - -:- constraints dom/2. - -dom(X,[]) <=> fail. -dom(X,[Y]) <=> X = Y. -dom(X,L1), dom(X,L2) <=> intersection(L1,L2,L3), dom(X,L3). - -intersection([],_,[]). -intersection([H|T],L2,[H|L3]) :- - member(H,L2), !, - intersection(T,L2,L3). -intersection([_|T],L2,L3) :- - intersection(T,L2,L3). -~~~~~ - - - - - */ - -/** @defgroup CHR_Compatibility Compatibility with SICStus CHR -@ingroup packages -@{ - - - -There are small differences between CHR in SWI-Prolog and newer -YAPs and SICStus and older versions of YAP. Besides differences in -available options and pragmas, the following differences should be -noted: - -+ [The handler/1 declaration] -In SICStus every CHR module requires a `handler/1` -declaration declaring a unique handler name. This declaration is valid -syntax in SWI-Prolog, but will have no effect. A warning will be given -during compilation. - -+ [The rules/1 declaration] -In SICStus, for every CHR module it is possible to only enable a subset -of the available rules through the `rules/1` declaration. The -declaration is valid syntax in SWI-Prolog, but has no effect. A -warning is given during compilation. - -+ [Sourcefile naming] -SICStus uses a two-step compiler, where chr files are -first translated into pl files. For SWI-Prolog CHR -rules may be defined in a file with any extension. - - - - */ - -/** @defgroup CHR_Guidelines Guidelines -@ingroup packages -@{ - - - -In this section we cover several guidelines on how to use CHR to write -constraint solvers and how to do so efficiently. - -+ [Set semantics] -The CHR system allows the presence of identical constraints, i.e. -multiple constraints with the same functor, arity and arguments. For -most constraint solvers, this is not desirable: it affects efficiency -and possibly termination. Hence appropriate simpagation rules should be -added of the form: - -~~~~~ -{constraint \ constraint <=> true}. -~~~~~ - -+ [Multi-headed rules] -Multi-headed rules are executed more efficiently when the constraints -share one or more variables. - -+ [Mode and type declarations] -Provide mode and type declarations to get more efficient program execution. -Make sure to disable debug (`-nodebug`) and enable optimization -(`-O`). - - - - */ - -/** @defgroup Logtalk Logtalk -@ingroup packages -@{ - -The Logtalk object-oriented extension is available after running its -standalone installer by using the `yaplgt` command in POSIX -systems or by using the `Logtalk - YAP` shortcut in the Logtalk -program group in the Start Menu on Windows systems. For more information -please see the URL . - - -\copydoc real - - - */ - -/** @defgroup Threads Threads -@ingroup builtins -@{ - -YAP implements a SWI-Prolog compatible multithreading -library. Like in SWI-Prolog, Prolog threads have their own stacks and -only share the Prolog heap: predicates, records, flags and other -global non-backtrackable data. The package is based on the POSIX thread -standard (Butenhof:1997:PPT) used on most popular systems except -for MS-Windows. - - - */ - -/** @defgroup Creating_and_Destroying_Prolog_Threads Creating and Destroying Prolog Threads -@ingroup Threads -@{ - - - - @pred thread_create(: _Goal_, - _Id_, + _Options_) - - - -Create a new Prolog thread (and underlying C-thread) and start it -by executing _Goal_. If the thread is created successfully, the -thread-identifier of the created thread is unified to _Id_. - _Options_ is a list of options. Currently defined options are: - -+ stack -Set the limit in K-Bytes to which the Prolog stacks of -this thread may grow. If omitted, the limit of the calling thread is -used. See also the commandline `-S` option. - -+ trail -Set the limit in K-Bytes to which the trail stack of this thread may -grow. If omitted, the limit of the calling thread is used. See also the -commandline option `-T`. - -+ alias -Associate an alias-name with the thread. This named may be used to -refer to the thread and remains valid until the thread is joined -(see thread_join/2). - -+ at_exit -Define an exit hook for the thread. This hook is called when the thread -terminates, no matter its exit status. - -+ detached -If `false` (default), the thread can be waited for using -thread_join/2. thread_join/2 must be called on this thread -to reclaim the all resources associated to the thread. If `true`, -the system will reclaim all associated resources automatically after the -thread finishes. Please note that thread identifiers are freed for reuse -after a detached thread finishes or a normal thread has been joined. -See also thread_join/2 and thread_detach/1. - - -The _Goal_ argument is copied to the new Prolog engine. -This implies further instantiation of this term in either thread does -not have consequences for the other thread: Prolog threads do not share -data from their stacks. - - -*/ - -/** @pred thread_create(: _Goal_, - _Id_) - - -Create a new Prolog thread using default options. See thread_create/3. - - -*/ - -/** @pred thread_create(: _Goal_) - - -Create a new Prolog detached thread using default options. See thread_create/3. - - -*/ - -/** @pred thread_self(- _Id_) - - -Get the Prolog thread identifier of the running thread. If the thread -has an alias, the alias-name is returned. - - -*/ - -/** @pred thread_join(+ _Id_, - _Status_) - - -Wait for the termination of thread with given _Id_. Then unify the -result-status of the thread with _Status_. After this call, - _Id_ becomes invalid and all resources associated with the thread -are reclaimed. Note that threads with the attribute `detached` -`true` cannot be joined. See also current_thread/2. - -A thread that has been completed without thread_join/2 being -called on it is partly reclaimed: the Prolog stacks are released and the -C-thread is destroyed. A small data-structure representing the -exit-status of the thread is retained until thread_join/2 is called on -the thread. Defined values for _Status_ are: - -+ true -The goal has been proven successfully. - -+ false -The goal has failed. - -+ exception( _Term_) -The thread is terminated on an -exception. See print_message/2 to turn system exceptions into -readable messages. - -+ exited( _Term_) -The thread is terminated on thread_exit/1 using the argument _Term_. - - -+ thread_detach(+ _Id_) - - -Switch thread into detached-state (see `detached` option at -thread_create/3 at runtime. _Id_ is the identifier of the thread -placed in detached state. - -One of the possible applications is to simplify debugging. Threads that -are created as `detached` leave no traces if they crash. For -not-detached threads the status can be inspected using -current_thread/2. Threads nobody is waiting for may be created -normally and detach themselves just before completion. This way they -leave no traces on normal completion and their reason for failure can be -inspected. - - -*/ - -/** @pred thread_yield - - -Voluntarily relinquish the processor. - - -*/ - -/** @pred thread_exit(+ _Term_) - - -Terminates the thread immediately, leaving `exited( _Term_)` as -result-state for thread_join/2. If the thread has the attribute -`detached` `true` it terminates, but its exit status cannot be -retrieved using thread_join/2 making the value of _Term_ -irrelevant. The Prolog stacks and C-thread are reclaimed. - - -*/ - -/** @pred thread_at_exit(: _Term_) - - -Run _Goal_ just before releasing the thread resources. This is to -be compared to `at_halt/1`, but only for the current -thread. These hooks are ran regardless of why the execution of the -thread has been completed. As these hooks are run, the return-code is -already available through thread_property/2 using the result of -thread_self/1 as thread-identifier. If you want to guarantee the -execution of an exit hook no matter how the thread terminates (the thread -can be aborted before reaching the thread_at_exit/1 call), consider -using instead the `at_exit/1` option of thread_create/3. - - -*/ - -/** @pred thread_setconcurrency(+ _Old_, - _New_) - - -Determine the concurrency of the process, which is defined as the -maximum number of concurrently active threads. `Active` here means -they are using CPU time. This option is provided if the -thread-implementation provides -`pthread_setconcurrency()`. Solaris is a typical example of this -family. On other systems this predicate unifies _Old_ to 0 (zero) -and succeeds silently. - - -*/ - -/** @pred thread_sleep(+ _Time_) - - -Make current thread sleep for _Time_ seconds. _Time_ may be an -integer or a floating point number. When time is zero or a negative value -the call succeeds and returns immediately. This call should not be used if -alarms are also being used. - - - - */ - -/** @defgroup Monitoring_Threads Monitoring Threads -@ingroup Threads -@{ - -Normal multi-threaded applications should not need these the predicates -from this section because almost any usage of these predicates is -unsafe. For example checking the existence of a thread before signalling -it is of no use as it may vanish between the two calls. Catching -exceptions using catch/3 is the only safe way to deal with -thread-existence errors. - -These predicates are provided for diagnosis and monitoring tasks. - - -*/ - -/** @pred thread_property(? _Id_, ? _Property_) - - -Enumerates the properties of the specified thread. -Calling thread_property/2 does not influence any thread. See also -thread_join/2. For threads that have an alias-name, this name can -be used in _Id_ instead of the numerical thread identifier. - _Property_ is one of: - -+ status( _Status_) -The thread status of a thread (see below). - -+ alias( _Alias_) -The thread alias, if it exists. - -+ at_exit( _AtExit_) -The thread exit hook, if defined (not available if the thread is already terminated). - -+ detached( _Boolean_) -The detached state of the thread. - -+ stack( _Size_) -The thread stack data-area size. - -+ trail( _Size_) -The thread trail data-area size. - -+ system( _Size_) -The thread system data-area size. - - - -*/ - -/** @pred current_thread(+ _Id_, - _Status_) - - -Enumerates identifiers and status of all currently known threads. -Calling current_thread/2 does not influence any thread. See also -thread_join/2. For threads that have an alias-name, this name is -returned in _Id_ instead of the numerical thread identifier. - _Status_ is one of: - -+ running -The thread is running. This is the initial status of a thread. Please -note that threads waiting for something are considered running too. - -+ false -The _Goal_ of the thread has been completed and failed. - -+ true -The _Goal_ of the thread has been completed and succeeded. - -+ exited( _Term_) -The _Goal_ of the thread has been terminated using thread_exit/1 -with _Term_ as argument. If the underlying native thread has -exited (using pthread_exit()) _Term_ is unbound. - -+ exception( _Term_) -The _Goal_ of the thread has been terminated due to an uncaught -exception (see throw/1 and catch/3). - - - -*/ - -/** @pred thread_statistics(+ _Id_, + _Key_, - _Value_) - - -Obtains statistical information on thread _Id_ as `statistics/2` -does in single-threaded applications. This call returns all keys -of `statistics/2`, although only information statistics about the -stacks and CPU time yield different values for each thread. - -+ mutex_statistics - - -Print usage statistics on internal mutexes and mutexes associated -with dynamic predicates. For each mutex two numbers are printed: -the number of times the mutex was acquired and the number of -collisions: the number times the calling thread has to -wait for the mutex. The collision-count is not available on -Windows as this would break portability to Windows-95/98/ME or -significantly harm performance. Generally collision count is -close to zero on single-CPU hardware. - -+ threads - - -Prints a table of current threads and their status. - - - - */ - -/** @defgroup Thread_Communication Thread communication -@ingroup Threads -@{ - -Prolog threads can exchange data using dynamic predicates, database -records, and other globally shared data. These provide no suitable means -to wait for data or a condition as they can only be checked in an -expensive polling loop. Message queues provide a means for -threads to wait for data or conditions without using the CPU. - -Each thread has a message-queue attached to it that is identified -by the thread. Additional queues are created using -`message_queue_create/2`. - - - - @pred thread_send_message(+ _Term_) - - -Places _Term_ in the message-queue of the thread running the goal. -Any term can be placed in a message queue, but note that the term is -copied to the receiving thread and variable-bindings are thus lost. -This call returns immediately. - - -*/ - -/** @pred thread_send_message(+ _QueueOrThreadId_, + _Term_) - -Place _Term_ in the given queue or default queue of the indicated -thread (which can even be the message queue of itself (see -thread_self/1). Any term can be placed in a message queue, but note that -the term is copied to the receiving thread and variable-bindings are -thus lost. This call returns immediately. - -If more than one thread is waiting for messages on the given queue and -at least one of these is waiting with a partially instantiated - _Term_, the waiting threads are all sent a wakeup signal, -starting a rush for the available messages in the queue. This behaviour -can seriously harm performance with many threads waiting on the same -queue as all-but-the-winner perform a useless scan of the queue. If -there is only one waiting thread or all waiting threads wait with an -unbound variable an arbitrary thread is restarted to scan the queue. - - - - - -*/ - -/** @pred thread_get_message(? _Term_) - - -Examines the thread message-queue and if necessary blocks execution -until a term that unifies to _Term_ arrives in the queue. After -a term from the queue has been unified unified to _Term_, the -term is deleted from the queue and this predicate returns. - -Please note that not-unifying messages remain in the queue. After -the following has been executed, thread 1 has the term `gnu` -in its queue and continues execution using _A_ is `gnat`. - -~~~~~ - - thread_get_message(a(A)), - - - thread_send_message(b(gnu)), - thread_send_message(a(gnat)), -~~~~~ - -See also thread_peek_message/1. - - -*/ - -/** @pred message_queue_create(? _Queue_) - - -If _Queue_ is an atom, create a named queue. To avoid ambiguity -on `thread_send_message/2`, the name of a queue may not be in use -as a thread-name. If _Queue_ is unbound an anonymous queue is -created and _Queue_ is unified to its identifier. - - -*/ - -/** @pred message_queue_destroy(+ _Queue_) - - -Destroy a message queue created with message_queue_create/1. It is -not allows to destroy the queue of a thread. Neither is it -allowed to destroy a queue other threads are waiting for or, for -anonymous message queues, may try to wait for later. - - -*/ - -/** @pred thread_get_message(+ _Queue_, ? _Term_) - -As thread_get_message/1, operating on a given queue. It is allowed to -peek into another thread's message queue, an operation that can be used -to check whether a thread has swallowed a message sent to it. - - -*/ - -/** @pred thread_peek_message(? _Term_) - - -Examines the thread message-queue and compares the queued terms -with _Term_ until one unifies or the end of the queue has been -reached. In the first case the call succeeds (possibly instantiating - _Term_. If no term from the queue unifies this call fails. - - -*/ - -/** @pred thread_peek_message(+ _Queue_, ? _Term_) - -As thread_peek_message/1, operating on a given queue. It is allowed to -peek into another thread's message queue, an operation that can be used -to check whether a thread has swallowed a message sent to it. - - - -Explicit message queues are designed with the worker-pool model -in mind, where multiple threads wait on a single queue and pick up the -first goal to execute. Below is a simple implementation where the -workers execute arbitrary Prolog goals. Note that this example provides -no means to tell when all work is done. This must be realised using -additional synchronisation. - -~~~~~ -% create_workers(+Id, +N) -% -% Create a pool with given Id and number of workers. - -create_workers(Id, N) :- - message_queue_create(Id), - forall(between(1, N, _), - thread_create(do_work(Id), _, [])). - -do_work(Id) :- - repeat, - thread_get_message(Id, Goal), - ( catch(Goal, E, print_message(error, E)) - -> true - ; print_message(error, goal_failed(Goal, worker(Id))) - ), - fail. - -% work(+Id, +Goal) -% -% Post work to be done by the pool - -work(Id, Goal) :- - thread_send_message(Id, Goal). -~~~~~ - - - */ - -/** @defgroup Signalling_Threads Signalling Threads -@ingroup Threadas -@{ - -These predicates provide a mechanism to make another thread execute some -goal as an interrupt. Signalling threads is safe as these -interrupts are only checked at safe points in the virtual machine. -Nevertheless, signalling in multi-threaded environments should be -handled with care as the receiving thread may hold a mutex -(see with_mutex/2). Signalling probably only makes sense to start -debugging threads and to cancel no-longer-needed threads with throw/1, -where the receiving thread should be designed carefully do handle -exceptions at any point. - - -*/ - -/** @pred thread_signal(+ _ThreadId_, : _Goal_) - - -Make thread _ThreadId_ execute _Goal_ at the first -opportunity. In the current implementation, this implies at the first -pass through the Call-port. The predicate thread_signal/2 -itself places _Goal_ into the signalled-thread's signal queue -and returns immediately. - -Signals (interrupts) do not cooperate well with the world of -multi-threading, mainly because the status of mutexes cannot be -guaranteed easily. At the call-port, the Prolog virtual machine -holds no locks and therefore the asynchronous execution is safe. - - _Goal_ can be any valid Prolog goal, including throw/1 to make -the receiving thread generate an exception and trace/0 to start -tracing the receiving thread. - - - - - */ - -/** @defgroup Threads_and_Dynamic_Predicates Threads and Dynamic Predicates -@ingroup Threads -@{ - -Besides queues threads can share and exchange data using dynamic -predicates. The multi-threaded version knows about two types of -dynamic predicates. By default, a predicate declared dynamic -(see dynamic/1) is shared by all threads. Each thread may -assert, retract and run the dynamic predicate. Synchronisation inside -Prolog guarantees the consistency of the predicate. Updates are -logical: visible clauses are not affected by assert/retract -after a query started on the predicate. In many cases primitive from -thread synchronisation should be used to ensure application invariants on -the predicate are maintained. - -Besides shared predicates, dynamic predicates can be declared with the -thread_local/1 directive. Such predicates share their -attributes, but the clause-list is different in each thread. - - -*/ - -/** @pred thread_local( _+Functor/Arity_) - - -related to the dynamic/1 directive. It tells the system that the -predicate may be modified using assert/1, retract/1, -etc, during execution of the program. Unlike normal shared dynamic -data however each thread has its own clause-list for the predicate. -As a thread starts, this clause list is empty. If there are still -clauses as the thread terminates these are automatically reclaimed by -the system. The `thread_local` property implies -the property `dynamic`. - -Thread-local dynamic predicates are intended for maintaining -thread-specific state or intermediate results of a computation. - -It is not recommended to put clauses for a thread-local predicate into -a file as in the example below as the clause is only visible from the -thread that loaded the source-file. All other threads start with an -empty clause-list. - -~~~~~ -:- thread_local - foo/1. - -foo(gnat). -~~~~~ - - - - - */ - -/** @defgroup Thread_Synchronisation Thread Synchronisation - -All@{ - internal Prolog operations are thread-safe. This implies two Prolog -threads can operate on the same dynamic predicate without corrupting the -consistency of the predicate. This section deals with user-level -mutexes (called monitors in ADA or -critical-sections by Microsoft). A mutex is a -MUTual EXclusive device, which implies at most one thread -can hold a mutex. - -Mutexes are used to realise related updates to the Prolog database. -With `related', we refer to the situation where a `transaction' implies -two or more changes to the Prolog database. For example, we have a -predicate `address/2`, representing the address of a person and we want -to change the address by retracting the old and asserting the new -address. Between these two operations the database is invalid: this -person has either no address or two addresses, depending on the -assert/retract order. - -Here is how to realise a correct update: - -~~~~~ -:- initialization - mutex_create(addressbook). - -change_address(Id, Address) :- - mutex_lock(addressbook), - retractall(address(Id, _)), - asserta(address(Id, Address)), - mutex_unlock(addressbook). -~~~~~ - - -*/ - -/** @pred mutex_create(? _MutexId_) - - -Create a mutex. if _MutexId_ is an atom, a named mutex is -created. If it is a variable, an anonymous mutex reference is returned. -There is no limit to the number of mutexes that can be created. - - -*/ - -/** @pred mutex_destroy(+ _MutexId_) - - -Destroy a mutex. After this call, _MutexId_ becomes invalid and -further references yield an `existence_error` exception. - - -*/ - -/** @pred with_mutex(+ _MutexId_, : _Goal_) - - -Execute _Goal_ while holding _MutexId_. If _Goal_ leaves -choicepoints, these are destroyed (as in once/1). The mutex is unlocked -regardless of whether _Goal_ succeeds, fails or raises an exception. -An exception thrown by _Goal_ is re-thrown after the mutex has been -successfully unlocked. See also `mutex_create/2`. - -Although described in the thread-section, this predicate is also -available in the single-threaded version, where it behaves simply as -once/1. - - -*/ - -/** @pred mutex_lock(+ _MutexId_) - - -Lock the mutex. Prolog mutexes are recursive mutexes: they -can be locked multiple times by the same thread. Only after unlocking -it as many times as it is locked, the mutex becomes available for -locking by other threads. If another thread has locked the mutex the -calling thread is suspended until to mutex is unlocked. - -If _MutexId_ is an atom, and there is no current mutex with that -name, the mutex is created automatically using mutex_create/1. This -implies named mutexes need not be declared explicitly. - -Please note that locking and unlocking mutexes should be paired -carefully. Especially make sure to unlock mutexes even if the protected -code fails or raises an exception. For most common cases use -with_mutex/2, which provides a safer way for handling Prolog-level -mutexes. - - -*/ - -/** @pred mutex_trylock(+ _MutexId_) - - -As mutex_lock/1, but if the mutex is held by another thread, this -predicates fails immediately. - - -*/ - -/** @pred mutex_unlock(+ _MutexId_) - - -Unlock the mutex. This can only be called if the mutex is held by the -calling thread. If this is not the case, a `permission_error` -exception is raised. - - -*/ - -/** @pred mutex_unlock_all - - -Unlock all mutexes held by the current thread. This call is especially -useful to handle thread-termination using abort/0 or exceptions. See -also thread_signal/2. - - -*/ - -/** @pred current_mutex(? _MutexId_, ? _ThreadId_, ? _Count_) - - -Enumerates all existing mutexes. If the mutex is held by some thread, - _ThreadId_ is unified with the identifier of the holding thread and - _Count_ with the recursive count of the mutex. Otherwise, - _ThreadId_ is `[]` and _Count_ is 0. - - - - */ - -/** @defgroup Parallelism Parallelism -@ingroup packages -@{ - -There has been a sizeable amount of work on an or-parallel -implementation for YAP, called *YAPOr*. Most of this work has -been performed by Ricardo Rocha. In this system parallelism is exploited -implicitly by running several alternatives in or-parallel. This option -can be enabled from the `configure` script or by checking the -system's `Makefile`. - - *YAPOr* is still a very experimental system, going through rapid -development. The following restrictions are of note: - -+ *YAPOr* currently only supports the Linux/X86 and SPARC/Solaris -platforms. Porting to other Unix-like platforms should be straightforward. - -+ *YAPOr* does not support parallel updates to the -data-base. - -+ *YAPOr* does not support opening or closing of streams during -parallel execution. - -+ Garbage collection and stack shifting are not supported in - *YAPOr*. - -+ Built-ins that cause side-effects can only be executed when -left-most in the search-tree. There are no primitives to provide -asynchronous or cavalier execution of these built-ins, as in Aurora or -Muse. - -+ YAP does not support voluntary suspension of work. - - -We expect that some of these restrictions will be removed in future -releases. - - - */ - -/** @defgroup Tabling Tabling -@ingroup builtins -@{ - - *YAPTab* is the tabling engine that extends YAP's execution -model to support tabled evaluation for definite programs. YAPTab was -implemented by Ricardo Rocha and its implementation is largely based -on the ground-breaking design of the XSB Prolog system, which -implements the SLG-WAM. Tables are implemented using tries and YAPTab -supports the dynamic intermixing of batched scheduling and local -scheduling at the subgoal level. Currently, the following restrictions -are of note: - -+ YAPTab does not handle tabled predicates with loops through negation (undefined behaviour). -+ YAPTab does not handle tabled predicates with cuts (undefined behaviour). -+ YAPTab does not support coroutining (configure error). -+ YAPTab does not support tabling dynamic predicates (permission error). - - -To experiment with YAPTab use `--enable-tabling` in the configure -script or add `-DTABLING` to `YAP_EXTRAS` in the system's -`Makefile`. We next describe the set of built-ins predicates -designed to interact with YAPTab and control tabled execution: - - -*/ - -/** @pred table( + _P_ ) - - -Declares predicate _P_ (or a list of predicates - _P1_,..., _Pn_ or [ _P1_,..., _Pn_]) as a tabled -predicate. _P_ must be written in the form - _name/arity_. Examples: - -~~~~~ -:- table son/3. -:- table father/2. -:- table mother/2. -~~~~~ - or - -~~~~~ -:- table son/3, father/2, mother/2. -~~~~~ - or - -~~~~~ -:- table [son/3, father/2, mother/2]. -~~~~~ - - -*/ - -/** @pred is_tabled(+ _P_) - - -Succeeds if the predicate _P_ (or a list of predicates - _P1_,..., _Pn_ or [ _P1_,..., _Pn_]), of the form - _name/arity_, is a tabled predicate. - - -*/ - -/** @pred tabling_mode(+ _P_,? _Mode_) - - -Sets or reads the default tabling mode for a tabled predicate _P_ -(or a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). The list of _Mode_ options includes: - -+ `batched` - - Defines that, by default, batched scheduling is the scheduling -strategy to be used to evaluated calls to predicate _P_. - -+ `local` - - Defines that, by default, local scheduling is the scheduling -strategy to be used to evaluated calls to predicate _P_. - -+ `exec_answers` - - Defines that, by default, when a call to predicate _P_ is -already evaluated (completed), answers are obtained by executing -compiled WAM-like code directly from the trie data -structure. This reduces the loading time when backtracking, but -the order in which answers are obtained is undefined. - -+ `load_answers` - - Defines that, by default, when a call to predicate _P_ is -already evaluated (completed), answers are obtained (as a -consumer) by loading them from the trie data structure. This -guarantees that answers are obtained in the same order as they -were found. Somewhat less efficient but creates less choice-points. - -The default tabling mode for a new tabled predicate is `batched` -and `exec_answers`. To set the tabling mode for all predicates at -once you can use the yap_flag/2 predicate as described next. - -*/ - -/** @pred yap_flag(tabling_mode,? _Mode_) -Sets or reads the tabling mode for all tabled predicates. The list of - _Mode_ options includes: - -+ `default` - - Defines that (i) all calls to tabled predicates are evaluated -using the predicate default mode, and that (ii) answers for all -completed calls are obtained by using the predicate default mode. - -+ `batched` - - Defines that all calls to tabled predicates are evaluated using -batched scheduling. This option ignores the default tabling mode -of each predicate. - -+ `local` - - Defines that all calls to tabled predicates are evaluated using -local scheduling. This option ignores the default tabling mode -of each predicate. - -+ `exec_answers` - - Defines that answers for all completed calls are obtained by -executing compiled WAM-like code directly from the trie data -structure. This option ignores the default tabling mode -of each predicate. - -+ `load_answers` - - Defines that answers for all completed calls are obtained by -loading them from the trie data structure. This option ignores -the default tabling mode of each predicate. - - - -*/ - -/** @pred abolish_table(+ _P_) - - -Removes all the entries from the table space for predicate _P_ (or -a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). The predicate remains as a tabled predicate. - - -*/ - -/** @pred abolish_all_tables/0 - - -Removes all the entries from the table space for all tabled -predicates. The predicates remain as tabled predicates. - - -*/ - -/** @pred show_table(+ _P_) - - -Prints table contents (subgoals and answers) for predicate _P_ -(or a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). - - -*/ - -/** @pred table_statistics(+ _P_) - - -Prints table statistics (subgoals and answers) for predicate _P_ -(or a list of predicates _P1_,..., _Pn_ or -[ _P1_,..., _Pn_]). - - -*/ - -/** @pred tabling_statistics/0 - - -Prints statistics on space used by all tables. - - - - */ - -/** @defgroup Low_Level_Tracing Tracing at Low Level -@ingroup builtins -@{ - -It is possible to follow the flow at abstract machine level if -YAP is compiled with the flag `LOW_LEVEL_TRACER`. Note -that this option is of most interest to implementers, as it quickly generates -an huge amount of information. - -Low level tracing can be toggled from an interrupt handler by using the -option `T`. There are also two built-ins that activate and -deactivate low level tracing: - - -*/ - -/** @pred start_low_level_trace - - -Begin display of messages at procedure entry and retry. - - -*/ - -/** @pred stop_low_level_trace - - -Stop display of messages at procedure entry and retry. - - -Note that this compile-time option will slow down execution. - - - */ - -/** @defgroup Low_Level_Profiling Profiling the Abstract Machine - -Implementors may be interested in detecting on which abstract machine -instructions are executed by a program. The `ANALYST` flag can give -WAM level information. Note that this option slows down execution very -substantially, and is only of interest to developers of the system -internals, or to system debuggers. - - -*/ - -/** @pred wam_profiler_reset_op_counters - - -Reinitialize all counters. - - -*/ - -/** @pred wam_profiler_show_op_counters(+ _A_) - - -Display the current value for the counters, using label _A_. The -label must be an atom. - - -*/ - -/** @pred wam_profiler_show_ops_by_group(+ _A_) - - -Display the current value for the counters, organized by groups, using -label _A_. The label must be an atom. - - - - - */ - -/** @defgroup Debugging Debugging -@ingroup builtins -@{ - - - */ - -/** @defgroup Deb_Preds Debugging Predicates - -@{ -The - following predicates are available to control the debugging of -programs: - -+ debug - - Switches the debugger on. - -+ debugging - - - Outputs status information about the debugger which includes the leash -mode and the existing spy-points, when the debugger is on. - -+ nodebug - - - Switches the debugger off. - - -*/ - -/** @pred spy( + _P_ ). - - -Sets spy-points on all the predicates represented by - _P_. _P_ can either be a single specification or a list of -specifications. Each one must be of the form _Name/Arity_ -or _Name_. In the last case all predicates with the name - _Name_ will be spied. As in C-Prolog, system predicates and -predicates written in C, cannot be spied. - - -*/ - -/** @pred nospy( + _P_ ) - - -Removes spy-points from all predicates specified by _P_. -The possible forms for _P_ are the same as in `spy P`. - - -*/ - -/** @pred nospyall - - -Removes all existing spy-points. - - -*/ - -/** @pred leash(+ _M_) - - -Sets leashing mode to _M_. -The mode can be specified as: - -+ `full` -prompt on Call, Exit, Redo and Fail - -+ `tight` -prompt on Call, Redo and Fail - -+ `half` -prompt on Call and Redo - -+ `loose` -prompt on Call - -+ `off` -never prompt - -+ `none` -never prompt, same as `off` - -The initial leashing mode is `full`. - -The user may also specify directly the debugger ports -where he wants to be prompted. If the argument for leash -is a number _N_, each of lower four bits of the number is used to -control prompting at one the ports of the box model. The debugger will -prompt according to the following conditions: - -+ if `N/\ 1 =\= 0` prompt on fail -+ if `N/\ 2 =\= 0` prompt on redo -+ if `N/\ 4 =\= 0` prompt on exit -+ if `N/\ 8 =\= 0` prompt on call - -Therefore, `leash(15)` is equivalent to `leash(full)` and -`leash(0)` is equivalent to `leash(off)`. - -Another way of using `leash` is to give it a list with the names of -the ports where the debugger should stop. For example, -`leash([call,exit,redo,fail])` is the same as `leash(full)` or -`leash(15)` and `leash([fail])` might be used instead of -`leash(1)`. - - -*/ - -/** @pred trace - - -Switches on the debugger and enters tracing mode. - - -*/ - -/** @pred notrace - - -Ends tracing and exits the debugger. This is the same as -nodebug/0. - - - - - */ - -/** @defgroup Deb_Interaction Interacting with the debugger - -Deb@{ -ugging with YAP is similar to debugging with C-Prolog. Both systems -include a procedural debugger, based on Byrd's four port model. In this -model, execution is seen at the procedure level: each activation of a -procedure is seen as a box with control flowing into and out of that -box. - -In the four port model control is caught at four key points: before -entering the procedure, after exiting the procedure (meaning successful -evaluation of all queries activated by the procedure), after backtracking but -before trying new alternative to the procedure and after failing the -procedure. Each one of these points is named a port: - -~~~~~ -@group - *--------------------------------------* - Call | | Exit ----------> + descendant(X,Y) :- offspring(X,Y). + ---------> - | | - | descendant(X,Z) :- | -<--------- + offspring(X,Y), descendant(Y,Z). + <--------- - Fail | | Redo - *--------------------------------------* -~~~~~ - - - -+ `Call` - - The call port is activated before initial invocation of -procedure. Afterwards, execution will try to match the goal with the -head of existing clauses for the procedure. - -+ `Exit` - - This port is activated if the procedure succeeds. -Control will now leave the procedure and return to its ancestor. - -+ `Redo` - - If the goal, or goals, activated after the call port -fail then backtracking will eventually return control to this procedure -through the redo port. - -+ `Fail` - - If all clauses for this predicate fail, then the -invocation fails, and control will try to redo the ancestor of this -invocation. - - -To start debugging, the user will either call `trace` or spy the -relevant procedures, entering debug mode, and start execution of the -program. When finding the first spy-point, YAP's debugger will take -control and show a message of the form: - -~~~~~ -* (1) call: quicksort([1,2,3],_38) ? -~~~~~ - -The debugger message will be shown while creeping, or at spy-points, -and it includes four or five fields: - -+ -The first three characters are used to point out special states of the -debugger. If the port is exit and the first character is '?', the -current call is non-deterministic, that is, it still has alternatives to -be tried. If the second character is a `\*`, execution is at a -spy-point. If the third character is a `>`, execution has returned -either from a skip, a fail or a redo command. -+ -The second field is the activation number, and uniquely identifies the -activation. The number will start from 1 and will be incremented for -each activation found by the debugger. -+ -In the third field, the debugger shows the active port. -+ -The fourth field is the goal. The goal is written by -`write_term/3` on the standard error stream, using the options -given by debugger_print_options. - - -If the active port is leashed, the debugger will prompt the user with a -`?`, and wait for a command. A debugger command is just a -character, followed by a return. By default, only the call and redo -entries are leashed, but the leash/1 predicate can be used in -order to make the debugger stop where needed. - -There are several commands available, but the user only needs to -remember the help command, which is `h`. This command shows all the -available options, which are: - -+ `c` - creep - - this command makes YAP continue execution and stop at the next -leashed port. - -+ `return` - creep - - the same as c - -+ `l` - leap - - YAP will execute until it meets a port for a spied predicate; this mode -keeps all computation history for debugging purposes, so it is more -expensive than standard execution. Use k or z for fast execution. - -+ `k` - quasi-leap - - similar to leap but faster since the computation history is -not kept; useful when leap becomes too slow. - -+ `z` - zip - - - same as k -+ `s` - skip - - YAP will continue execution without showing any messages until -returning to the current activation. Spy-points will be ignored in this -mode. Note that this command keeps all debugging history, use t for fast execution. This command is meaningless, and therefore illegal, in the fail -and exit ports. - -+ `t` - fast-skip - - similar to skip but faster since computation history is not -kept; useful if skip becomes slow. - -+ `f [ _GoalId_]` - fail - - If given no argument, forces YAP to fail the goal, skipping the fail -port and backtracking to the parent. -If f receives a goal number as -the argument, the command fails all the way to the goal. If goal _GoalId_ has completed execution, YAP fails until meeting the first active ancestor. - -+ `r` [ _GoalId_] - retry - - This command forces YAP to jump back call to the port. Note that any -side effects of the goal cannot be undone. This command is not available -at the call port. If f receives a goal number as the argument, the -command retries goal _GoalId_ instead. If goal _GoalId_ has -completed execution, YAP fails until meeting the first active ancestor. - -+ `a` - abort - - execution will be aborted, and the interpreter will return to the -top-level. YAP disactivates debug mode, but spypoints are not removed. - -+ `n` - nodebug - - stop debugging and continue execution. The command will not clear active -spy-points. - -+ `e` - exit - - leave YAP. - -+ `h` - help - - show the debugger commands. - -+ `!` Query - - execute a query. YAP will not show the result of the query. - -+ `b` - break - - break active execution and launch a break level. This is the same as `!break`. - -+ `+` - spy this goal - - start spying the active goal. The same as `! spy G` where _G_ -is the active goal. - -+ `-` - nospy this goal - - stop spying the active goal. The same as `! nospy G` where _G_ is -the active goal. - -+ `p` - print - - shows the active goal using print/1 - -+ `d` - display - - shows the active goal using display/1 - -+ `deterministic programs often -boils down to a recursive loop of the form: - -~~~~~ -loop(Env) :- - do_something(Env,NewEnv), - loop(NewEnv). -~~~~~ - - - - - */ - -/** @defgroup Indexing Indexing - -The@{ - indexation mechanism restricts the set of clauses to be tried in a -procedure by using information about the status of the instantiated -arguments of the goal. These arguments are then used as a key, -selecting a restricted set of a clauses from all the clauses forming the -procedure. - -As an example, the two clauses for concatenate: - -~~~~~ -concatenate([],L,L). -concatenate([H|T],A,[H|NT]) :- concatenate(T,A,NT). -~~~~~ - -If the first argument for the goal is a list, then only the second clause -is of interest. If the first argument is the nil atom, the system needs to -look only for the first clause. The indexation generates instructions that -test the value of the first argument, and then proceed to a selected clause, -or group of clauses. - -Note that if the first argument was a free variable, then both clauses -should be tried. In general, indexation will not be useful if the first -argument is a free variable. - -When activating a predicate, a Prolog system needs to store state -information. This information, stored in a structure known as choice point -or fail point, is necessary when backtracking to other clauses for the -predicate. The operations of creating and using a choice point are very -expensive, both in the terms of space used and time spent. -Creating a choice point is not necessary if there is only a clause for -the predicate as there are no clauses to backtrack to. With indexation, this -situation is extended: in the example, if the first argument was the atom -nil, then only one clause would really be of interest, and it is pointless to -create a choice point. This feature is even more useful if the first argument -is a list: without indexation, execution would try the first clause, creating -a choice point. The clause would fail, the choice point would then be used to -restore the previous state of the computation and the second clause would -be tried. The code generated by the indexation mechanism would behave -much more efficiently: it would test the first argument and see whether it -is a list, and then proceed directly to the second clause. - -An important side effect concerns the use of "cut". In the above -example, some programmers would use a "cut" in the first clause just to -inform the system that the predicate is not backtrackable and force the -removal the choice point just created. As a result, less space is needed but -with a great loss in expressive power: the "cut" would prevent some uses of -the procedure, like generating lists through backtracking. Of course, with -indexation the "cut" becomes useless: the choice point is not even created. - -Indexation is also very important for predicates with a large number -of clauses that are used like tables: - -~~~~~ -logician(aristoteles,greek). -logician(frege,german). -logician(russel,english). -logician(godel,german). -logician(whitehead,english). -~~~~~ - -An interpreter like C-Prolog, trying to answer the query: - -~~~~~ -?- logician(godel,X). -~~~~~ - -would blindly follow the standard Prolog strategy, trying first the -first clause, then the second, the third and finally finding the -relevant clause. Also, as there are some more clauses after the -important one, a choice point has to be created, even if we know the -next clauses will certainly fail. A "cut" would be needed to prevent -some possible uses for the procedure, like generating all logicians. In -this situation, the indexing mechanism generates instructions that -implement a search table. In this table, the value of the first argument -would be used as a key for fast search of possibly matching clauses. For -the query of the last example, the result of the search would be just -the fourth clause, and again there would be no need for a choice point. - -If the first argument is a complex term, indexation will select clauses -just by testing its main functor. However, there is an important -exception: if the first argument of a clause is a list, the algorithm -also uses the list's head if not a variable. For instance, with the -following clauses, - -~~~~~ -rules([],B,B). -rules([n(N)|T],I,O) :- rules_for_noun(N,I,N), rules(T,N,O). -rules([v(V)|T],I,O) :- rules_for_verb(V,I,N), rules(T,N,O). -rules([q(Q)|T],I,O) :- rules_for_qualifier(Q,I,N), rules(T,N,O). -~~~~~ -if the first argument of the goal is a list, its head will be tested, and only -the clauses matching it will be tried during execution. - -Some advice on how to take a good advantage of this mechanism: - - - -+ -Try to make the first argument an input argument. - -+ -Try to keep together all clauses whose first argument is not a -variable, that will decrease the number of tests since the other clauses are -always tried. - -+ -Try to avoid predicates having a lot of clauses with the same key. -For instance, the procedure: - - - -~~~~~ -type(n(mary),person). -type(n(john), person). -type(n(chair),object). -type(v(eat),active). -type(v(rest),passive). -~~~~~ - -becomes more efficient with: - -~~~~~ -type(n(N),T) :- type_of_noun(N,T). -type(v(V),T) :- type_of_verb(V,T). - -type_of_noun(mary,person). -type_of_noun(john,person). -type_of_noun(chair,object). - -type_of_verb(eat,active). -type_of_verb(rest,passive). -~~~~~ - -*/ - -/** @page ChYInterface C Language interface to YAP - -YAP provides the user with three facilities for writing -predicates in a language other than Prolog. Under Unix systems, -most language implementations were linkable to `C`, and the first interface exported the YAP machinery to the C language. YAP also implements most of the SWI-Prolog foreign language interface. -This gives portability with a number of SWI-Prolog packages. Last, a new C++ based interface is -being designed to work with the swig (@url(www.swig.org}) interface compiler. - -+ The @ref c-interface YAP C-interface exports the YAP engine. -+ The @ref swi-c-interface emulates Jan Wielemaker's SWI foreign language interface. -+ The @ref yap-cplus-interface is desiged to interface with Object-Oriented systems. - - - - - */ - -/** @defgroup Loading_Objects Loading Object Files - -The@{ - primitive predicate - - -*/ - -/** @pred load_foreign_files( _Files_, _Libs_, _InitRoutine_) - -should be used, from inside YAP, to load object files produced by the C -compiler. The argument _ObjectFiles_ should be a list of atoms -specifying the object files to load, _Libs_ is a list (possibly -empty) of libraries to be passed to the unix loader (`ld`) and -InitRoutine is the name of the C routine (to be called after the files -are loaded) to perform the necessary declarations to YAP of the -predicates defined in the files. - -YAP will search for _ObjectFiles_ in the current directory first. If -it cannot find them it will search for the files using the environment -variable: - -+ YAPLIBDIR - -if defined, or in the default library. - -YAP also supports the SWI-Prolog interface to loading foreign code: - - -*/ - -/** @pred open_shared_object(+ _File_, - _Handle_) - -File is the name of a shared object file (called dynamic load -library in MS-Windows). This file is attached to the current process -and _Handle_ is unified with a handle to the library. Equivalent to -`open_shared_object(File, [], Handle)`. See also -load_foreign_library/1 and `load_foreign_library/2`. - -On errors, an exception `shared_object`( _Action_, - _Message_) is raised. _Message_ is the return value from -dlerror(). - - -*/ - -/** @pred open_shared_object(+ _File_, - _Handle_, + _Options_) - -As `open_shared_object/2`, but allows for additional flags to -be passed. _Options_ is a list of atoms. `now` implies the -symbols are -resolved immediately rather than lazily (default). `global` implies -symbols of the loaded object are visible while loading other shared -objects (by default they are local). Note that these flags may not -be supported by your operating system. Check the documentation of -`dlopen()` or equivalent on your operating system. Unsupported -flags are silently ignored. - - -*/ - -/** @pred close_shared_object(+ _Handle_) - -Detach the shared object identified by _Handle_. - - -*/ - -/** @pred call_shared_object_function(+ _Handle_, + _Function_) - - -Call the named function in the loaded shared library. The function -is called without arguments and the return-value is -ignored. In SWI-Prolog, normally this function installs foreign -language predicates using calls to `PL_register_foreign()`. - - - - */ - -/** @defgroup SavebQeERest Saving and Restoring - -YAP@{ -4 currently does not support `save` and `restore` for object code -loaded with `load_foreign_files/3`. We plan to support save and restore -in future releases of YAP. - -*/ diff --git a/editors/Prolog.xlangspec b/editors/Prolog.xlangspec deleted file mode 100644 index d9c888a9d..000000000 --- a/editors/Prolog.xlangspec +++ /dev/null @@ -1,261 +0,0 @@ -// Python -( - -/****************************************************************************/ -// MARK: Python keywords -/****************************************************************************/ - - { - Identifier = "xcode.lang.prolog.identifier"; - Syntax = { - StartChars = "abcdefghijklmnopqrstuvwxyz"; - Chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"; - Words = ( - "and", - "as", - "assert", - "break", - "class", - "continue", - "def", - "del", - "elif", - "else", - "except", - "exec", - "finally", - "for", - "from", - "global", - "if", - "import", - "in", - "is", - "lambda", - "not", - "or", - "pass", - "print", - "raise", - "return", - "try", - "while", - "with", - "yield", - "None", - ); - Type = "xcode.syntax.keyword"; - AltType = "xcode.syntax.identifier"; // non-keywords are identifiers - }; - }, - - -/****************************************************************************/ -// MARK: Python Syntax Coloring -/****************************************************************************/ - - { - Identifier = "xcode.lang.python"; - Description = "Python Coloring"; - BasedOn = "xcode.lang.simpleColoring"; - IncludeInMenu = YES; - Name = "Prolog"; - Syntax = { - Tokenizer = "xcode.lang.prolog.lexer"; - IncludeRules = ( - "xcode.lang.prolog.fact", - "xcode.lang.prolog.rule", - "xcode.lang.prolog.dcg", - "xcode.lang.prolog.directive", - ); - Type = "xcode.syntax.plain"; - DirtyPreviousRightEdge = YES; - }; - }, - - { - Identifier = "xcode.lang.[prolog].lexer"; - Syntax = { - SourceScannerClassName = "XCPrologner"; // does the magical indentation parsing - IncludeRules = ( - "xcode.lang.comment.singleline.percent", - "xcode.lang.python.string.backquote", - "xcode.lang.python.string.singlequote", - "xcode.lang.string", - "xcode.lang.character", - "xcode.lang.number", - "xcode.lang.prolog.identifier", - "xcode.lang.prolog.constant", - ); - Type = "xcode.syntax.plain"; - }; - }, - - // declare "fake" tokens for XCPrologScanner to return - { - Identifier = "xcode.lang.prolog.indent"; - Syntax = { - Type = "xcode.syntax.plain"; - }; - }, - { - Identifier = "xcode.lang.prolog.dedent"; - Syntax = { - Type = "xcode.syntax.plain"; - }; - }, - - { - // ignores indentation - Identifier = "xcode.lang.prolog.lexer.simple"; - Syntax = { - IncludeRules = ( - "xcode.lang.comment.singleline.pound", - "xcode.lang.python.string.tripledoublequote", - "xcode.lang.python.string.triplesinglequote", - "xcode.lang.string", - "xcode.lang.character", - "xcode.lang.number", - "xcode.lang.python.identifier", - ); - Type = "xcode.syntax.plain"; - }; - }, - - { - Identifier = "xcode.lang.python.class"; - Syntax = { - Tokenizer = "xcode.lang.python.lexer"; - Rules = ( - "xcode.lang.python.class.declarator", - "xcode.lang.python.block", - ); - Type = "xcode.syntax.definition.class"; - }; - }, - { - Identifier = "xcode.lang.python.class.declarator"; - Syntax = { - Tokenizer = "xcode.lang.python.lexer"; - Rules = ( - "class", - "xcode.lang.python.name", - "xcode.lang.python.parenexpr?", - ":", - ); - }; - }, - - { - Identifier = "xcode.lang.python.function"; - Syntax = { - Tokenizer = "xcode.lang.python.lexer"; - Rules = ( - "xcode.lang.python.function.declarator", - "xcode.lang.python.block", - ); - Type = "xcode.syntax.definition.function"; - }; - }, - { - Identifier = "xcode.lang.python.function.declarator"; - Syntax = { - Tokenizer = "xcode.lang.python.lexer"; - Rules = ( - "def", - "xcode.lang.python.name", - "xcode.lang.python.parenexpr", - ":", - ); - }; - }, - - { - Identifier = "xcode.lang.python.block"; - Syntax = { - Tokenizer = "xcode.lang.python.lexer"; - Start = "xcode.lang.python.indent"; - End = "xcode.lang.python.dedent"; - Foldable = YES; - Recursive = YES; - IncludeRules = ( - "xcode.lang.python.class", - "xcode.lang.python.function", - "xcode.lang.python.bracketexpr", - "xcode.lang.python.parenexpr", - ); - }; - }, - - { - Identifier = "xcode.lang.prolog.name"; - Syntax = { - StartChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEF"; - Chars = "0123456789abcdefABCDEF"; - Type = "xcode.syntax.name.partial"; - }; - }, - - { - Identifier = "xcode.lang.python.string.backquote"; - Syntax = { - Start = "`"; - End = "`"; - Foldable = YES; - Type = "xcode.syntax.string"; - }; - }, - - { - Identifier = "xcode.lang.prolog.string.singlequote"; - Syntax = { - Start = "'"; - EscapeChar = "\'"; - End = "'"; - Foldable = YES; - Type = "xcode.syntax.string"; - }; - }, - - { - Identifier = "xcode.lang.prolog.parenexpr"; - Syntax = { - Tokenizer = "xcode.lang.prolog.lexer.simple"; - Start = "("; - End = ")"; - Recursive = YES; - IncludeRules = ( - "xcode.lang.prolog.bracketexpr", - "xcode.lang.prolog.curlybracketexpr", - ); - }; - }, - - { - Identifier = "xcode.lang.prolog.bracketexpr"; - Syntax = { - Tokenizer = "xcode.lang.prolog.lexer.simple"; - Start = "["; - End = "]"; - Recursive = YES; - IncludeRules = ( - "xcode.lang.prolog.parenexpr", - "xcode.lang.prolog.curlybracketexpr", - ); - }; - }, - -{ - Identifier = "xcode.lang.prolog.curlybracketexpr"; - Syntax = { - Tokenizer = "xcode.lang.prolog.lexer.simple"; - Start = "{"; - End = "}"; - Recursive = YES; - IncludeRules = ( - "xcode.lang.prolog.parenexpr", - "xcode.lang.prolog.bracketexpr", - ); - }; -}, -) diff --git a/fetchatgs b/fetchatgs deleted file mode 100644 index 163b4d3f4..000000000 --- a/fetchatgs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/jhc b/jhc deleted file mode 100644 index fac4ed1a5..000000000 --- a/jhc +++ /dev/null @@ -1,192 +0,0 @@ -BEAM/eam_am.c: if (beam_su->prev==b) { beam_su=b; return; } /* It was the last one */ -BEAM/eam_am.c: b->prev=beam_su->prev; -BEAM/eam_am.c: beam_su->prev=b; -BEAM/eam_am.c: s->prev=beam_su->prev; -BEAM/eam_am.c: beam_su->prev=s; -BEAM/eam_am.c: if (beam_su->next==beam_su) { /* so existem 2 elementos na lista */ -BEAM/eam_am.c: beam_su->next=s; -BEAM/eam_am.c: beam_ABX=beam_su->and_box; -BEAM/eam_am.c: beam_ABX=beam_su->and_box; -BEAM/eam_am.c: beam_su=beam_su->next; -BEAM/eam_am.c: l=beam_su->prev; -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s/%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/absmi.c~: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s/%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/amasm.c: ic->SiblingIndex = cl_u->lui.ChildIndex; -C/amasm.c: cl_u->lui.ChildIndex = ic; -C/amasm.c: cl_u->lui.ChildIndex = ic; -C/amasm.c: cl_u->lui.ClRefCount++; -C/amasm.c: ic->SiblingIndex = cl_u->si.ChildIndex; -C/amasm.c: cl_u->si.ChildIndex = ic; -C/amasm.c: cl_u->luc.Id = FunctorDBRef; -C/amasm.c: cl_u->luc.ClFlags = LogUpdMask; -C/amasm.c: cl_u->luc.ClFlags |= HasCutMask; -C/amasm.c: cl_u->luc.ClRefCount = 0; -C/amasm.c: cl_u->luc.ClPred = cip->CurrentPred; -C/amasm.c: cl_u->luc.ClTimeStart = cip->CurrentPred->TimeStampOfPred; -C/amasm.c: cl_u->luc.ClTimeEnd = TIMESTAMP_EOT; -C/amasm.c: cl_u->luc.ClFlags |= HasBlobsMask; -C/amasm.c: cl_u->luc.ClFlags |= HasDBTMask; -C/amasm.c: cl_u->luc.ClExt = NULL; -C/amasm.c: cl_u->luc.ClPrev = cl_u->luc.ClNext = NULL; -C/amasm.c: //INIT_LOCK(cl_u->luc.ClLock); -C/amasm.c: INIT_CLREF_COUNT(&(cl_u->luc)); -C/amasm.c: code_p = cl_u->luc.ClCode; -C/amasm.c: cl_u->ic.ClFlags = DynamicMask; -C/amasm.c: cl_u->ic.ClFlags |= HasBlobsMask; -C/amasm.c: cl_u->ic.ClFlags |= HasDBTMask; -C/amasm.c: cl_u->ic.ClSize = size; -C/amasm.c: cl_u->ic.ClRefCount = 0; -C/amasm.c: INIT_LOCK(cl_u->ic.ClLock); -C/amasm.c: INIT_CLREF_COUNT(&(cl_u->ic)); -C/amasm.c: code_p = cl_u->ic.ClCode; -C/amasm.c: cl_u->sc.ClFlags = StaticMask; -C/amasm.c: cl_u->sc.ClFlags |= HasCutMask; -C/amasm.c: cl_u->sc.ClNext = NULL; -C/amasm.c: cl_u->sc.ClSize = size; -C/amasm.c: cl_u->sc.usc.ClLine = Yap_source_line_no(); -C/amasm.c: cl_u->sc.ClFlags |= HasBlobsMask; -C/amasm.c: cl_u->sc.ClFlags |= HasDBTMask; -C/amasm.c: code_p = cl_u->sc.ClCode; -C/amasm.c: cl_u->lui.ClFlags = LogUpdMask|IndexedPredFlag|IndexMask|SwitchRootMask; -C/amasm.c: cl_u->lui.ChildIndex = NULL; -C/amasm.c: cl_u->lui.SiblingIndex = NULL; -C/amasm.c: cl_u->lui.PrevSiblingIndex = NULL; -C/amasm.c: cl_u->lui.ClPred = cip->CurrentPred; -C/amasm.c: cl_u->lui.ParentIndex = NULL; -C/amasm.c: cl_u->lui.ClSize = size; -C/amasm.c: cl_u->lui.ClRefCount = 0; -C/amasm.c: // INIT_LOCK(cl_u->lui.ClLock); -C/amasm.c: INIT_CLREF_COUNT(&(cl_u->lui)); -C/amasm.c: code_p = cl_u->lui.ClCode; -C/amasm.c: cl_u->si.ClSize = size; -C/amasm.c: cl_u->si.ClFlags = IndexMask; -C/amasm.c: cl_u->si.ChildIndex = NULL; -C/amasm.c: cl_u->si.SiblingIndex = NULL; -C/amasm.c: cl_u->si.ClPred = cip->CurrentPred; -C/amasm.c: code_p = cl_u->si.ClCode; -C/cdmgr.c: if (clau->ClFlags & ErasedMask) { -C/cdmgr.c: if (!clau->ClRefCount) { -C/cdmgr.c: decrease_log_indices(clau, (yamop *)&(clau->ClPred->cs.p_code.ExpandCode)); -C/cdmgr.c: if (clau->ClFlags & SwitchRootMask) { -C/cdmgr.c: kill_off_lu_block(clau, NULL, clau->ClPred); -C/cdmgr.c: kill_off_lu_block(clau, clau->ParentIndex, clau->ClPred); -C/cdmgr.c: if (clau->ClFlags & SwitchRootMask) { -C/cdmgr.c: kill_first_log_iblock(clau, NULL, clau->ClPred); -C/cdmgr.c: clau->ClRefCount++; -C/cdmgr.c: kill_first_log_iblock(clau, clau->ParentIndex, clau->ClPred); -C/cdmgr.c: clau->ClRefCount--; -C/dbase.c: if (clau->ClFlags & FactMask) -C/dbase.c: cp = clau->lusl.ClSource->DBRefs; -C/dbase.c: if (clau->ClNext) -C/dbase.c: clau->ClNext->ClPrev = clau->ClPrev; -C/dbase.c: if (clau->ClPrev) { -C/dbase.c: clau->ClPrev->ClNext = clau->ClNext; -C/dbase.c: DBErasedList = clau->ClNext; -C/dbase.c: Yap_LUClauseSpace -= clau->ClSize; -C/dbase.c: ap = clau->ClPred; -C/dbase.c: if (!(clau->ClFlags & ErasedMask)) { -C/dbase.c: if (clau->ClNext != NULL) { -C/dbase.c: clau->ClNext->ClPrev = clau->ClPrev; -C/dbase.c: if (clau->ClPrev != NULL) { -C/dbase.c: clau->ClPrev->ClNext = clau->ClNext; -C/dbase.c: if (clau->ClCode == ap->cs.p_code.FirstClause) { -C/dbase.c: if (clau->ClNext == NULL) { -C/dbase.c: ap->cs.p_code.FirstClause = clau->ClNext->ClCode; -C/dbase.c: if (clau->ClCode == ap->cs.p_code.LastClause) { -C/dbase.c: if (clau->ClPrev == NULL) { -C/dbase.c: ap->cs.p_code.LastClause = clau->ClPrev->ClCode; -C/dbase.c: clau->ClFlags |= ErasedMask; -C/dbase.c: clau->ClPrev = clau->ClNext = NULL; -C/dbase.c: clau->ClNext = er_head; -C/dbase.c: clau->ClPrev = NULL; -C/dbase.c: clau->ClRefCount++; -C/dbase.c: clau->ClTimeEnd = ap->TimeStampOfPred; -C/dbase.c: Yap_RemoveClauseFromIndex(ap, clau->ClCode); -C/dbase.c: clau->ClRefCount--; -C/dbase.c: ref = (DBRef) NEXTOP(clau->ClCode,Otapl)->y_u.Osbpp.bmap; -C/dbase.c: if ( P == clau->ClCode ) { -C/dbase.c: Yap_LUClauseSpace -= clau->ClSize; -C/dbase.c: yamop *code_p = clau->ClCode; -C/dbase.c: PredEntry *p = clau->ClPred; -C/dbase.c: if (clau->ClFlags & ErasedMask) { -C/dbase.c: clau->ClFlags |= ErasedMask; -C/dbase.c: if (!(clau->ClFlags & ErasedMask)) -C/dbase.c: if (!(clau->ClFlags & ErasedMask)) -C/index.c: if (clau->ClFlags & ErasedMask) { -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s:%d: (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -C/myabsmi.c: if (trace_interrupts) fprintf(stderr,"[%d] %lu--%lu %s/%d (YENV=%p ENV=%p ASP=%p)\n", worker_id, LOCAL_FirstActiveSignal, LOCAL_LastActiveSignal, \ -docs/builtins.tex:?- atomic_list_concat(L, -, 'gnu-gnat'). -docs/new_header.html: