toplevel_residue_vars
is missing
When this is set true it will print any variables possibly missed by ones constraint solver.
Did you know ... | Search Documentation: |
Predicate current_prolog_flag/2 |
Flags marked changeable can be modified by the user using
set_prolog_flag/2.
Flag values are typed. Flags marked as bool
can have the
values true
or false
. The predicate
create_prolog_flag/3
may be used to create flags that describe or control behaviour of
libraries and applications. The library
library(settings)
provides an alternative interface for
managing notably application parameters.
Some Prolog flags are not defined in all versions, which is normally
indicated in the documentation below as “if present and true’.
A boolean Prolog flag is true iff the Prolog flag is present
and the Value is the atom true
. Tests for
such flags should be written as below:
( current_prolog_flag(windows, true) -> <Do MS-Windows things> ; <Do normal things> )
Some Prolog flags are scoped to a source file. This implies that if they are set using a directive inside a file, the flag value encountered when loading of the file started is restored when loading of the file is completed. Currently, the following flags are scoped to the source file: generate_debug_info and optimise.
A new thread (see section 10) copies all flags from the thread that created the new thread (its parent).15This is implemented using the copy-on-write technique. As a consequence, modifying a flag inside a thread does not affect other threads.
user
,
default) or a‘system’view. In system view all system code is
fully accessible as if it was normal user code. In user view, certain
operations are not permitted and some details are kept invisible. We
leave the exact consequences undefined, but, for example, system code
can be traced using system access and system predicates can be
redefined.true
(default false
16Future
versions are likely to change the default to true
.),
that atom garbage collector streams that are garbage collected while
being open. In addition, a warning is printed. Below is an example of
such a warning.
WARNING: AGC: closed <stream>(0x560e29014400)
Note that closing I/O streams should not be left to the (atom) garbage collector because it may take long before the atom garbage collector runs and because that atom garbage collector is conservative, which implies that it is not guaranteed that all garbage atoms are reclaimed. Code that uses I/O streams should use setup_call_cleanup/3 using the skeleton below, where process/1 is a predicate that reads from or writes to Stream.
setup_call_cleanup( open(..., Stream), process(Stream), close(Stream)), ...
Note that the setting for this flag in the main
thread
applies.
true
(default false
), dots may be embedded
into atoms that are not quoted and start with a letter. The embedded dot
must be followed by an identifier continuation character (i.e.,
letter, digit or underscore). The dot is allowed in identifiers in many
languages, which can make this a useful flag for defining DSLs. Note
that this conflicts with cascading functional notation. For example,
Post.meta.author
is read as .(Post,’meta.author’
if this flag is set to true
.Functor(arg)
is read as if it
were written ’Functor’(arg)
. Some applications
use the Prolog read/1
predicate for reading an application-defined script language. In these
cases, it is often difficult to explain to non-Prolog users of the
application that constants and functions can only start with a lowercase
letter. Variables can be turned into atoms starting with an uppercase
atom by calling read_term/2
using the option variable_names
and binding the variables
to their name. Using this feature, F(x) can be turned into valid syntax
for such script languages. Suggested by Robert van Engelen. SWI-Prolog
specific.__ANDROID_API__
. It is not defined if
running on other operating systems. The API level may or may not match
the API level of the running device, since it is the API level at
compile time.[quoted(true),
portray(true), max_depth(10), attributes(portray)]
.true
, the operating
system is MacOSX. Defined if the C compiler used to compile this version
of SWI-Prolog defines
__APPLE__
. Note that the unix
is also defined for MacOSX.true
, SWI-Prolog has been build as a
universal binary. Universal binaries contain native executable
code for multiple architectures. Currently the supported architectures
are x86_64
and arm64
. The archirecture prefix
for components is fat-darwin
while the arch
depends on the actual CPU type.--
or the first
non-option argument. See also os_argv.18Prior
to version 6.5.2, argv
was defined as os_argv
is now. The change was made for compatibility reasons and because the
current definition is more practical.false
, but to autoload library predicates into the
global
user
module. This makes the development tools and library
implicitly available to the toplevel, but not to modules.explicit
with user
, providing lazy
loading of predicates imported using autoload/[1,2]
and implicit access to the whole library for the toplevel.codes
.
If --traditional is given, the default is symbol_char
,
which allows using `
in operators composed of symbols.19Older
versions had a boolean flag backquoted_strings
, which
toggled between string
and symbol_char
See also section 5.2.true
(default), print a backtrace on an uncaught
exception.true
(default), try to reconstruct the line number at
which the exception happened.true
, integer representation is bound
by
min_integer and max_integer.
If
false
integers can be arbitrarily large and the
min_integer and max_integer
are not present. The flag max_integer_size
may be used to enforce an arbitrary limit rather than exhausting memory.
See section 4.27.2.1.gcc
, clang
or cc
. See section
12.5.-lswipl
on COFF-based
systems. See section 12.5.-lswipl
if the SWI-Prolog kernel is a shared (DLL). If the
SWI-Prolog kernel is in a static library, this flag also contains the
dependencies.true
(default), read/1
interprets \
escape sequences in quoted atoms and strings.
May be changed. This flag is local to the module in which it is changed.
See section 2.15.1.3.true
(default), write/1
and friends write escaped characters using the \uXXXX
or \UXXXXXXXX
syntax rather than the ISO Prolog \x<hex>\
syntax.
SWI-Prolog reads both.library(ansi_term)
, which
is loaded at startup if the two conditions below are both true. Note
that this implies that setting this flag to false
from the
system or personal initialization file (see section
2.2 disables colored output. The predicate message_property/2
can be used to control the actual color scheme depending in the message
type passed to
print_message/2.
stream_property(current_output, tty(true))
\+ current_prolog_flag(color_term, false)
^
’(see meta_predicate/1).
Supported values are:
true
when built in a Conda
environment.true
in swipl-win.exe to indicate that the
console supports menus. See also section
4.35.4.library(thread)
. This flag is not available on systems
where we do not know how to get the number of CPUs. This flag is not
included in a saved state (see qsave_program/1).true
if this instance of Prolog supports DDE as
described in section 4.44.Disabling these optimisations can cause the system to run out of memory on programs that behave correctly if debug mode is off.
true
, start the tracer after an error is detected.
Otherwise just continue execution. The goal that raised the error will
normally fail. See also the Prolog flag report_error.
Default is true
.true
, start the debugger on Control-C.21More
precisely when receiving SIGINT
. The initial
value is
false
and the value is set to true
when
entering the interactive top level. See --debug-on-interrupt
to start handling interrupts immediately.true
, show the context module while printing a
stack-frame in the tracer. Normally controlled using the‘C’option
of the tracer.[quoted(true),
portray(true), max_depth(10), attributes(portray)]
.error
(default), warning
and silent
.swi
. The code below is a reliable and portable way
to detect SWI-Prolog.
is_dialect(swi) :- catch(current_prolog_flag(dialect, swi), _, fail).
/
,
but \
on Windows.string
, which
produces a string as described in section
5.2. If
--traditional is given, the default is codes
,
which produces a list of character codes, integers that represent a
Unicode code-point. The value chars
produces a list of
one-character atoms and the value atom
makes double quotes
the same as single quotes, creating a atom. See also section
5.EMACS
is t
and INFERIOR
is yes
.text
mode. The
initial value is deduced from the environment. See section
2.18.1 for details.elf
for when
swipl
is an ELF binary file.true
(default false
), expand $\arg{varname}
and ~
in arguments of built-in predicates that
accept a file name (open/3, exists_file/1, access_file/2,
etc.). The predicate
expand_file_name/2
can be used to expand environment variables and wildcard patterns. This
Prolog flag is intended for backward compatibility with older versions
of SWI-Prolog.error
(default) or infinity
. The first
is ISO compliant. Using infinity
, floating point overflow
is mapped to positive or negative Inf
. See section
4.27.2.4. This flag also affects read_term/3
and friends, causing them to read too large floating point number as
infinity.to_nearest
(default), to_positive
, to_negative
or to_zero
. For most scenarios the function
roundtoward/2
provides a safer and faster alternative.error
(default) or nan
. The first is
ISO compliant. Using nan
, undefined operations such as
sqrt(-2.0)
is mapped to NaN
. See section
4.27.2.4.error
or ignore
(default). The second
is ISO compliant, binding the result to 0.0.error
(default) or infinity
. The first
is ISO compliant. Using infinity
, division by 0.0 is mapped
to positive or negative Inf
. See section
4.27.2.4.true
(default if threading is enabled), atom and clause
garbage collection are executed in a separate thread with the
alias gc
. Otherwise the thread that detected
sufficient garbage executes the garbage collector. As running these
global collectors may take relatively long, using a separate thread
improves real time behaviour. The gc
thread can be
controlled using
set_prolog_gc_thread/1,
which either enables the gc thread or kills the gc thread and waits for
it to die.true
(default) generate code that can be debugged using
trace/0, spy/1,
etc. Can be set to false
using the
--no-debug. This flag is scoped within a source file.
Many of the libraries have
:- set_prolog_flag(generate_debug_info, false)
to hide
their details from a normal trace.22In
the current implementation this only causes a flag to be set on the
predicate that causes children to be hidden from the debugger. The name
anticipates further changes to the compiler.true
if XPCE is around and can be used for graphics.<home>/boot.prc
and to find its library as <home>/library
.
Some installations may put architecture independent files in a shared
home and also define shared_home.
System files can be found using
absolute_file_name/3
as swi(file)
. See file_search_path/2.//
and rem
arithmetic functions. Value depends on the C compiler used./
/2
(float division) always
returns a float, even if applied to integers that can be divided.[a :- b, c].
must now be disambiguated to mean [(a :- b), c].
or [(a
:- b, c)].
X
== -, true.
write X == (-), true.
Currently, this is
not entirely enforced.true
, SWI-Prolog has been compiled with
large file support (LFS) and is capable of accessing files
larger than 2GB. This flag is always true
on 64-bit
hardware and true on 32-bit hardware if the configuration detected
support for LFS. Note that it may still be the case that the file
system on which a particular file resides puts limits on the file
size.libswipl
, the
SWI-Prolog shared object that provides Prolog, resides. On some systems
this can be determined reliably from the running system. On these
systems the flag is read-only. On other systems it is the
configured target installation location and thus this value can be wrong
if the installation has been relocated. As we do not have a
cross-platform reliable way to compute this path the flag is read-write
on such platforms.23When running
from the build environment, this flag is adjusted to reflect the
location in the build tree.
Currently, this flag is reliable on Windows and POSIX systems providing the dladdr() function. This function is provided on Linux and MacOS.
tcmalloc
and
ptmalloc
. See section
4.43.2 for details.infinite
clears the flag. By default this flag is not
defined. See section
7.10 for details.bounded_rationality
, error
(default) or
suspend
.0xffff
on Windows (UCS-2) and
0x10ffff
on most other platforms.representation_error(max_procedure_arity)
exception. Currently set to 1024.true
creates excessively big rational numbers and, if
precision is not required, one should use floating point arithmetic.
Note that rationals are also implicitly limited by the Prolog flag max_integer_size.error
(default),
which throws a tripwire resource error and float
, which
converts the rational number into a floating point number. Note that
rational numbers may exceed the range for floating point numbers.infinite
clears the flag. By default this flag is not
defined. See section
7.10 for details.error
(default), bounded_rationality
,
suspend
and fail
.infinite
clears the flag. By default this flag is not
defined. See section
7.10 for details.error
(default), abstract
and suspend
.error
and
warning
. The list may contain the elements thread
to add the thread that generates the message to the message, time
or time(Format)
to add a time stamp. The default time
format is %T.%3f
. The default is [thread]
. See
also format_time/3
and print_message/2.true
(default false
), enforce mitigation
against the
Spectre
timing-based security vulnerability. Spectre based attacks can extract
information from memory owned by the process that should remain
invisible, such as passwords or the private key of a web server. The
attacks work by causing speculative access to sensitive data, and
leaking the data via side-channels such as differences in the duration
of successive instructions. An example of a potentially vulnerable
application is SWISH.
SWISH allows users to run Prolog code while the swish server must
protect the privacy of other users as well as its HTTPS private keys,
cookies and passwords.
Currently, enabling this flag reduces the resolution of get_time/1 and statistics/2 CPU time to 20μs.
WARNING: Although a coarser timer makes a successful attack of this type harder, it does not reliably prevent such attacks in general. Full mitigation may require compiler support to disable speculative access to sensitive data.
false
(default), unification succeeds, creating an infinite
tree. Using true
, unification behaves as unify_with_occurs_check/2,
failing silently. Using error
, an attempt to create a
cyclic term results in an occurs_check
exception. The
latter is intended for debugging unintentional creations of cyclic
terms. Note that this flag is a global flag modifying fundamental
behaviour of Prolog. Changing the flag from its default may cause
libraries to stop functioning properly.print
(default), status
and halt
.
Using
halt
the process halts immediately with status 1. Otherwise
execution continues. Using status
halt/0
exits with status 1 if one or more errors were printed by the process.
In compile mode (see -c) the default is status
.
This flag can be set from the commandline using --on-error.
See also section
4.3.2.1.print
. The commandline option is --on-warning..so
files) or dynamic link libraries (.DLL
files).true
, compile in optimised mode. The initial value is
true
if Prolog was started with the -O
command line option. The optimise
flag is scoped to a source file.
Currently optimised compilation implies compilation of arithmetic, and deletion of redundant true/0 that may result from expand_goal/2.
Later versions might imply various other optimisations such as integrating small predicates into their callers, eliminating constant expressions and other predictable constructs. Source code optimisation is never applied to predicates that are declared dynamic (see dynamic/1).
true
(default), allow the compiler to (re)move explicit
unification calls (=/2).
While this behaviour can significantly improve performance, it is not
yet handled properly by the source-level debugger. See section
2.17.3.true
, extension packs (add-ons) are attached. Can be set
to
false
using the --no-packs.PATH
for the OS. Normally :
, but ;
on Windows.open(pipe(command), mode, Stream)
, etc. are
supported. Can be changed to disable the use of pipes in applications
testing this feature. Not recommended.true
(default), generate .qlf
files and
saved states that run both on 32 bit and 64-bit hardware. If false
,
some optimized virtual machine instructions are only used if the integer
argument is within the range of a tagged integer for 32-bit machines./bin/sh
. This flag is used by shell/1
and qsave_program/2.true
, prefer arithmetic to produce rational numbers over
floats. This implies:
2^(-2)
evaluates to
1/4
.
Using true
can create excessively large rational
numbers. The Prolog flag max_rational_size
can be used to detect and act on this tripwire.
If false
, rational numbers can only be created using the
functions rational/1, rationalize/1
and
rdiv/2 or by reading
them. See also
rational_syntax, section
2.15.1.6 and
section 4.27.2.2.
The current default is false
. We consider changing this
to
true
in the future. Users are strongly encouraged to set
this flag to true
and report issues this may cause.
determinism
, which implies the system prompts for
alternatives if the goal succeeded while leaving choice points. Many
classical Prolog systems behave as groundness
: they prompt
for alternatives if and only if the query contains variables.true
(default false
), clause/2
does not operate on static code, providing some basic protection from
hackers that wish to list the static code of your Prolog program. Once
the flag is
true
, it cannot be changed back to false
.
Protection is default in ISO mode (see Prolog flag iso).
Note that many parts of the development environment require clause/2
to work on static code, and enabling this flag should thus only be used
for production code.qcompile(+Atom)
option of load_files/2.natural
(e.g., 1/3
) or compatibility
(e.g., 1r3
). The compatibility
syntax is
always accepted. This flag is module sensitive.
The default for this flag is currently compatibility
,
which reads and writes rational numbers as e.g., 1r3
.24There
is still some discussion on the separating character. See section
2.15.1.6. We will consider natural
as a
default in the future. Users are strongly encouraged to set this flag to
natural
and report issues this may cause.
true
if the system
supports rational numbers. For SWI-Prolog this flag is always set if the
flag bounded is false
.false
, readline
or
editline
. This causes the toplevel not to load a command
line editor (false
) or load the specified one. If loading
fails the flag is set to false
.
library(readline)
is loaded, providing line
editing based on the GNU readline library.library(editline)
is loaded, providing line
editing based on the BSD libedit. This is the default if library(editline)
is available and can be loaded.true
, print error messages; otherwise suppress them. May
be changed. See also the debug_on_error
Prolog flag. Default is true
, except for the runtime
version.boot32.prc
, the file specified with -x
or the running executable. See also resource/3.true
, SWI-Prolog is compiled with
-DO_RUNTIME, disabling various useful development features (currently
the tracer and profiler).true
(default false
), load_files/2
calls hooks to allow library(sandbox) to verify the safety of
directives.true
, Prolog has been started from a state
saved with qsave_program/[1,2].<prefix>/share/swipl
instead of in the
home at the
<prefix>/lib/swipl
. This flag indicates
the location of this
shared home and the directory is added to the file search path
swi
. See file_search_path/2
and the flag home..so
for most Unix systems and .dll
for Windows. Used for
locating files using the file_type
executable
.
See also
absolute_file_name/3.true
(default false
), check for
suspicious delimited continuations captured by shift_for_copy/1.false
if the hosting OS does not support signal
handling or the command line option --no-signals is
active. See
section
12.4.25.1 for details.true
, loading a relative file name from source
code searches relative to the location of the source file as well as
relative to the working directory. Searching relative to the working
directory is deprecated and a warning is printed if the file is found
this way. Furture versions are likely to change the default to
false
.25Searching the
working directory was supported up to version 9.3.8. Version 9.3.9
disabled this and version 9.3.10 re-enables it with a warning.false
(no checking), true
(full checking) and loose
. Using checking mode loose
(default), the system accepts byte I/O from text stream that use ISO
Latin-1 encoding and accepts writing text to binary streams.false
. See table/1.false
. See table/1.resource_error(table_space)
exception is raised.false
. See
table/1.false
and read-only. Otherwise
the value is true
unless the system was started with the
--no-threads. Threading may be disabled only if no
threads are running. See also the gc_thread
flag.timezone
variable associated
with the POSIX tzset() function. See also format_time/3.TMP
or TEMP
in windows. If this
variable is not defined a default is used. This default is typically /tmp
or
c:/temp
in windows.default
, starting a normal interactive
session. This value may be changed using the command line option -t.
The explicit value prolog
is equivalent to default
.
If initialization(Goal,main)
is used and the toplevel is default
,
the toplevel is set to
halt
(see halt/0).true
(default) and the answer is undefined
according to the Well Founded Semantics (see section
7.6), list the
residual program before the answer. Otherwise the answer
terminated with undefined. See also undefined/0.backtracking
(default), the toplevel backtracks after
completing a query. If recursive
, the toplevel is
implemented as a recursive loop. This implies that global variables set
using
b_setval/2
are maintained between queries. In recursive mode, answers to
toplevel variables (see section
2.9) are kept in backtrackable global variables and thus not
copied. In
backtracking mode answers to toplevel variables are kept in the
recorded database (see section
4.14.2).
The recursive mode has been added for interactive usage of CHR (see section 9),26Suggested by Falco Nogatz which maintains the global constraint store in backtrackable global variables.
true
(default), give names to variables at the toplevel
instead of printing them as _NNN. The variables are named
_A, _B, ... Variables that appear only once
(singletons) are printed as _.true
, top-level variables starting with an underscore (_
)
are printed normally. If false
(default) the binding of
such variables are omitted from the answer. This may be used to hide
bindings in complex queries from the top level. For example, the binding
for _List below is not printed.
?- numlist(1,1 000 000,_List), sum_list(_List, Sum). Sum = 500000500000.
true
(default false
) show the internal
sharing of subterms in the answer substitution. The example below
reveals internal sharing of leaf nodes in red-black trees as
implemented by the
library(rbtrees)
predicate rb_new/1 :
?- set_prolog_flag(toplevel_print_factorized, true). ?- rb_new(X). X = t(_S1, _S1), % where _S1 = black('', _G387, _G388, '').
If this flag is false
, the % where
notation
is still used to indicate cycles as illustrated below. This example also
shows that the implementation reveals the internal cycle length, and not
the minimal cycle length. Cycles of different length are
indistinguishable in Prolog (as illustrated by S == R
).
?- S = s(S), R = s(s(R)), S == R. S = s(S), R = s(s(R)).
~
(tilde) sequences are replaced:
m | Type in module if
not user (see module/1) |
l | Break level if not 0 (see break/0) |
d | Debugging state if not normal execution (see debug/0, trace/0) |
! | History event if history is enabled (see flag history) |
true
(default false
), print residual
variables as detected by call_residue_vars/2
that do not appear in the bindings returned by the goal.$
variable reference. When 0 (zero), the
variable recording and reuse is disabled. See section
2.9.true
(default false
), garbage collections
and stack-shifts will be reported on the terminal. May be changed.
Values are reported in bytes as G+T, where G
is the global stack value and T the trail stack value.‘Gained’describes
the number of bytes reclaimed.‘used’the number of bytes on
the stack after GC and‘free’the number of bytes allocated,
but not in use. Below is an example output.
% GC: gained 236,416+163,424 in 0.00 sec; used 13,448+5,808; free 72,568+47,440
true
,‘traditional’mode
has been selected using --traditional. Notice that some
SWI7 features, like the functional notation on dicts, do not work in
this mode. See also section
5.false
at startup, command line editing is disabled.
See also the --no-tty command line option.true
, the operating
system is some version of Unix. Defined if the C compiler used to
compile this version of SWI-Prolog either defines __unix__
or unix
. On other systems this flag is not available. See
also apple and windows.fail
, the predicate fails silently. If warn
, a
warning is printed, and execution continues as if the predicate was not
defined, and if error
(default), an existence_error
exception is raised. This flag is local to each module and inherited
from the module's import-module. Using default setup, this
implies that normal modules inherit the flag from user
,
which in turn inherit the value error
from system
.
The user may change the flag for module user
to change the
default for all application modules or for a specific module. It is
strongly advised to keep the error
default and use dynamic/1
and/or multifile/1
to specify possible non-existence of a predicate.domain_error
exception. This is
considered impractical as it makes it hard to write portable code if
different Prolog systems support different options and it makes it hard
to write predicates that process options and pass some of the options to
one predicate and others to some other predicate. For example, a
predicate reading a file to a list of terms must distribute options to open/4
and read_term/3.
SWI-Prolog has always ignored unknown options unless in ISO mode (see
the iso flag). This flag
provides full control over how options are processed.true
(default false
), unload all loaded
foreign libraries. Default is false
because modern OSes
reclaim the resources anyway and unloading the foreign code may cause
registered hooks to point to no longer existing data or code.silent
, warning
and error
. The first two create the flag on-the-fly, where warning
prints 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 silent
, but future versions may change that.
Developers are encouraged to use another value and ensure proper use of create_prolog_flag/3
to create flags for their library.true
(default false
), variables must start
with an underscore (_
). May be changed. This flag is local
to the module in which it is changed. See section
2.15.1.8.silent
, messages of type informational
and banner
are suppressed. The -q switches
the value from the initial
normal
to silent
.true
the normal consult message will be printed if a
library is autoloaded. By default this message is suppressed. Intended
to be used for debugging purposes.true
(default false
), print messages
indicating the progress of absolute_file_name/[2,3]
in locating files. Intended for debugging complicated file-search paths.
See also file_search_path/2.full
(print a message at the start and
end of each file loaded), normal
(print a message at the
end of each file loaded), brief
(print a message at end of
loading the toplevel file), and silent
(no messages are
printed, default). The value of this flag is normally controlled by the
option
silent(Bool)
provided by load_files/2.10000 × Major + 100 × Minor + Patch
tag(rc1)
.true
, unless debug mode is enabled.
Setting this flag to false
may improve other runtime
instrumentation results. Note that optimized arithmetic (-O,
see Prolog flag optimise)
is currently not translated into a normal predicate call.true
(default false
), warn when autoloading
predicates from a file that defines global term- or goal-expansion
rules. These rules typically enhance performance or provide cleaner
semantics and thus autoloading is not recommended. Future versions will
enable this flag by default.true
(default), a warning is printed if an implicitly
imported predicate is clobbered by a local definition. See
use_module/1
for details.true
, the
operating system is an implementation of Microsoft Windows. This flag is
only available on MS-Windows based versions. See also unix.attributes
option of
write_term/2.
Default is ignore
.true
it prints
bold and underlined text using
overstrike.true
and read-only for non-Windows systems. On Windows
systems the flag is true
but read-write when compiled under
Conda or MSYS2
and not defined otherwise. On
Windows, the search order is
true
false
true
if the XPCE graphics system is
loaded.true
, source code is being read for analysis
purposes such as cross-referencing. Otherwise (default) it is being read
to be compiled. This flag is used at several places by term_expansion/2
and
goal_expansion/2
hooks, notably if these hooks use side effects. See also the libraries library(prolog_source)
and library(prolog_xref)
.With the help of library(csv) and library(http/json), we read a CSV file and use the column names in the first row to emit JSON.
For this example, we use the file weather.csv
:
city,temp_lo,temp_hi,prcp,date San Francisco,46,50,0.25,1994-11-27 San Francisco,43,57,0,1994-11-29 Hayward,37,54,,1994-11-29
The script csv_to_json.pl
reads the CSV from standard input or from
the file provided as the first argument of the script. It converts
the contents to a list of dicts, then writes this as JSON to standard
output:
:- initialization(main, main). :- use_module(library(csv)). :- use_module(library(http/json)). main :- ( current_prolog_flag(argv, [CSV_file|_]) -> csv_read_file(CSV_file, CSV, []) ; csv_read_stream(current_input, CSV, []) ), CSV = [Colnames|Rows], Colnames =.. [row|Names], maplist(row_dict(Names), Rows, Dicts), json_write_dict(current_output, Dicts, [null('')]). row_dict(Names, Row, Dict) :- Row =.. [row|Fields], pairs_keys_values(Data, Names, Fields), dict_create(Dict, _, Data).
The null('')
option to json_write_dict/3 is necessary to convert the
empty "prcp" field in the last row to a missing value represented as
null
in the JSON output.
This is how we can use it to convert weather.csv
to JSON:
$ swipl csv_to_json.pl weather.csv [ { "city":"San Francisco", "date":"1994-11-27", "prcp":0.25, "temp_hi":50, "temp_lo":46 }, { "city":"San Francisco", "date":"1994-11-29", "prcp":0, "temp_hi":57, "temp_lo":43 }, { "city":"Hayward", "date":"1994-11-29", "prcp":null, "temp_hi":54, "temp_lo":37 } ]
toplevel_residue_vars
is missing
When this is set true it will print any variables possibly missed by ones constraint solver.
From the DCG page:
The flags
influence interpretation of "string"
and `string`
in "standard text".
In DCGs, both "string"
and `string`
are interpreted as "codes" by default.
Without any settings changed, consider this DCG:
representation(double_quotes) --> "bar". % SWI-Prolog decomposes this into CODES representation(back_quotes) --> `bar`. % SWI-Prolog decomposes this into CODES representation(explicit_codes_1) --> [98,97,114]. % explicit CODES (as obtained via atom_codes(bar,Codes)) representation(explicit_codes_2) --> [0'b,0'a,0'r]. % explicit CODES representation(explicit_chars) --> ['b','a','r']. % explicit CHARS
Which of the above matches codes?
?- findall(X, (atom_codes(bar,Codes), phrase(representation(X),Codes,[])), Reps). Reps = [double_quotes,back_quotes,explicit_codes_1,explicit_codes_2].
Which of the above matches chars?
?- findall(X, (atom_chars(bar,Chars),phrase(representation(X),Chars,[])), Reps). Reps = [explicit_chars].
...
)Instead of:
OutColl = [0xE3,0x82,0xA2,0xE3,0x82,0xA4,0xE3,0x82,0xA6|...].
I want
OutColl = [0xE3,0x82,0xA2,0xE3,0x82,0xA4,0xE3,0x82,0xA6,0xE3,0x82,0xA8,0xE3,0x82,0xAA].
And the command is:
(note that you have to set all the options, if you just set max_depth
for example you will scratch portray(true)
for example, leading to output like
'$VAR'('Suffix')
..this took me some time to find out.
Anyway:
?- Depth=100, Options=[quoted(true), portray(true), max_depth(Depth), attributes(portray)], set_prolog_flag(answer_write_options,Options), set_prolog_flag(debugger_write_options,Options).
or even unset any depth limit completely by setting Depth to 0 above.
As code:
my_print :- Depth=100, Options=[quoted(true), portray(true), max_depth(Depth), attributes(portray)], set_prolog_flag(answer_write_options,Options), set_prolog_flag(debugger_write_options,Options). :- my_print.
TODO
: Write a predicate to create a new options list with max_depth(Depth)
only changed.
Actually, if this follows "options list semantics", just prepending max_depth(100)
to the existing list should upgrade the depth. Try it:
?- current_prolog_flag(answer_write_options,Options),NewOptions=[max_depth(200)|Options],set_prolog_flag(answer_write_options,NewOptions). Options = [quoted(true),portray(true),max_depth(100),attributes(portray)], NewOptions = [max_depth(200),quoted(true),portray(true),max_depth(100),attributes(portray)]. ?- current_prolog_flag(answer_write_options,Options). Options = [max_depth(200),quoted(true),portray(true),max_depth(100),attributes(portray)].
The multiple values are retained... Not sure whether this is a bug.
Consider adding the instructions to your init.pl
($HOME/.config/swi-prolog/init.pl
) file so that it is run at startup.
home
is Prolog's "home", not the user's "home"This is not the user's home directory:
?- current_prolog_flag(home, X). X = '/usr/local/logic/swipl/lib/swipl'.
Use this instead:
?- expand_file_name("~", Home). Home = ['/home/paquette'].
Use file_search_path/2 for others:
bagof(X,file_search_path(user_app_data,X),UAD), bagof(X,file_search_path(common_app_data,X),CAD), bagof(X,file_search_path(user_app_config,X),UAC), (file_search_path(common_app_config,_) -> bagof(X,file_search_path(common_app_config,X),CAC); CAC = []), bagof(X,file_search_path(app_data,X),AD), bagof(X,file_search_path(app_config,X),AC). UAD = ['/home/paquette/.local/share/swi-prolog'], CAD = ['/usr/local/share/swi-prolog', '/usr/share/swi-prolog', '/etc/xdg/swi-prolog'], UAC = ['/home/paquette/.config/swi-prolog'], CAC = [], AD = [user_app_data('.'), common_app_data('.')], AC = [user_app_config('.'), common_app_config('.')].
Since only some flags are module local, we should be careful to document when a flag is so. E.g., under the double_quotes
flag, it says
This flag determines how double quoted strings are read by Prolog and is ---like character_escapes and back_quotes--- maintained for each module
but this fact isn't mentioned in the documentation for back_quotes
itself.
It might be good to just include a note on every flag, saying whether it is global or local to a module.