### Initialize HTTP Server with Handlers Source: https://www.scryer.pl/http/http_server Demonstrates how to start an HTTP server on a specific port and define handlers for GET and POST requests using route matching. ```prolog :- use_module(library(http/http_server)). text_handler(Request, Response) :- http_status_code(Response, 200), http_body(Response, text("Welcome to Scryer Prolog!")). parameter_handler(User, Request, Response) :- http_body(Response, text(User)). run:- http_listen(7890, [ get(echo, text_handler), post(user/User, parameter_handler(User)) ]). ``` -------------------------------- ### HTTP Server Usage Example Source: https://www.scryer.pl/http/http_server Demonstrates how to set up an HTTP server with different handlers for GET and POST requests. ```APIDOC ## HTTP Server Setup ### Description This example shows how to configure and run an HTTP server using the `http_server` module. It includes handlers for a simple text response and a handler that accepts a user parameter. ### Method N/A (This is a setup example) ### Endpoint N/A (This is a setup example) ### Parameters N/A ### Request Example N/A ### Response N/A ## Handler Predicates ### Description These are example handler predicates that process incoming HTTP requests and generate responses. ### Method N/A (These are handler definitions) ### Endpoint N/A (These are handler definitions) #### `text_handler/2` - **Description**: Handles requests to the `/echo` endpoint, returning a welcome message. - **Arguments**: `Request`, `Response` #### `parameter_handler/3` - **Description**: Handles POST requests to `/user/`, returning the provided user value in the response body. - **Arguments**: `User`, `Request`, `Response` ### Code Example ```prolog :- use_module(library(http/http_server)). text_handler(Request, Response) :- http_status_code(Response, 200), http_body(Response, text("Welcome to Scryer Prolog!")). parameter_handler(User, Request, Response) :- http_body(Response, text(User)). run:- http_listen(7890, [ get(echo, text_handler), % GET /echo post(user/User, parameter_handler(User)) % POST /user/ ]). ``` ``` -------------------------------- ### Indexing dif/2 Predicate Example Source: https://www.scryer.pl/reif Demonstrates the usage of the tfilter/3 predicate with an example query showcasing its behavior with reified terms and difference lists. ```APIDOC ## Indexing dif/2 Predicate ### Description This section provides an example of how to use the `tfilter/3` predicate, which is related to indexing difference lists and reified terms. The example query illustrates various outcomes based on term unification and the `dif/2` constraint. ### Method N/A (Example Query) ### Endpoint N/A (Prolog Predicate) ### Parameters N/A ### Request Example ```prolog ?- tfilter(=(a), [X,Y], Es). ``` ### Response #### Success Response (Example Outcomes) - **X, Y, Es**: Variables that get instantiated based on the query. - **dif:dif(Term1, Term2)**: Represents a constraint that Term1 and Term2 are different. #### Response Example ```prolog X = a, Y = a, Es = "aa" ; X = a, Es = "a", dif:dif(a,Y) ; Y = a, Es = "a", dif:dif(a,X) ; Es = [], dif:dif(a,X), dif:dif(a,Y). ``` ``` -------------------------------- ### Prolog Game Initialization and Setup Source: https://www.scryer.pl/learn/lets-play-brisca Code snippets for initializing and setting up the game state. This includes resetting the game with all cards in the stock, shuffling the cards, and setting the trump suit based on the last card in the stock. ```Prolog reset --> state(_, [stock(Cards)]), { setof(Card, card(Card), Cards) }. shuffle_cards --> state(S0, S), { select(stock(Cards), S0, S1), shuffle(Cards, ShuffledCards), S = [stock(ShuffledCards)|S1] }. set_trump --> state(S0, S), { member(stock(Cards), S0), length(Cards, N), nth1(N, Cards, LastCard), LastCard = Trump-_, S = [trump(Trump)|S0] }. ``` -------------------------------- ### Perform HTTP GET request with http_open Source: https://www.scryer.pl/http/http_open This snippet demonstrates how to open a connection to a URL and read the response content. It uses the http_open/3 predicate to initiate the request and get_n_chars/3 to read the resulting stream. ```prolog :- use_module(library(http/http_open)). ?- http_open("https://www.example.com", S, []), get_n_chars(S, N, HTML). ``` -------------------------------- ### Prolog CLP(Z) Constraint Example: Factorial Query Source: https://www.scryer.pl/clpz Illustrates querying the factorial predicate with CLP(Z) constraints. The first example shows a standard query with N instantiated, and the second shows a query with N as a variable, demonstrating improved termination. ```Prolog ?- n_factorial(47, F). F = 258623241511168180642964355153611979969197632389120000000000 ; false. ``` ```Prolog ?- n_factorial(N, 1). N = 0 ; N = 1 ; false. ``` ```Prolog ?- n_factorial(N, 3). false. ``` -------------------------------- ### Example: Boolean circuit Source: https://www.scryer.pl/clpb Models a boolean circuit for XOR using NAND gates with CLP(B) constraints. ```APIDOC ## Example: Boolean circuit Consider a Boolean circuit that express the Boolean function =|XOR|=with 4 =|NAND|=wates. We can model such a circuit with CLP(B) constraints as follows: ``` :- use_module(library(clpb)). nand_gate(X, Y, Z) :- sat(Z =:= ~(X*Y)). xor(X, Y, Z) :- nand_gate(X, Y, T1), nand_gate(X, T1, T2), nand_gate(Y, T1, T3), nand_gate(T2, T3, Z). ``` Using universally quantified variables, we can show that the circuit does compute =|XOR|=ws intended: ``` ?- xor(x, y, Z). clpb:sat(Z=:=x#y). ``` ``` -------------------------------- ### Example: Pigeons Source: https://www.scryer.pl/clpb Demonstrates modeling the pigeonhole problem using cardinality constraints and Prolog DCG notation. ```APIDOC ## Example: Pigeons In this example, we are attempting to place _I_ pigeons into _J_ holes in such a way that each hole contains at most one pigeon. One interesting property of this task is that it can be formulated using only _cardinality constraints_ (`card/2`). Another interesting aspect is that this task has no short resolution refutations in general. In the following, we use **Prolog DCG notation** to describe a list `Cs` of CLP(B) constraints that must all be satisfied. ``` :- use_module(library(clpb)). :- use_module(library(clpz)). :- use_module(library(lists)). :- use_module(library(dcgs)). pigeon(I, J, Rows, Cs) :- length(Rows, I), length(Row, J), maplist(same_length(Row), Rows), transpose(Rows, TRows), phrase((all_cards(Rows,[1]),all_cards(TRows,[0,1])), Cs). all_cards([], _) --> []. all_cards([Ls|Lss], Cs) --> [card(Cs,Ls)], all_cards(Lss, Cs). ``` Example queries: ``` ?- pigeon(9, 8, Rows, Cs), sat(*(Cs)). false. ?- pigeon(2, 3, Rows, Cs), sat(*(Cs)), append(Rows, Vs), labeling(Vs), maplist(portray_clause, Rows). [0,0,1]. [0,1,0]. etc. ``` ``` -------------------------------- ### Environment Variables Source: https://www.scryer.pl/os Predicates for getting, setting, and unsetting environment variables. ```APIDOC ## Environment Variables API ### Description Provides predicates for interacting with environment variables. ### getenv(+Key, -Value) #### Description True iff Value contains the value of the environment variable Key. #### Method GET (conceptual) #### Endpoint N/A (predicate) #### Parameters - **Key** (string) - Required - The name of the environment variable. - **Value** (string) - Output - The value of the environment variable. ### setenv(+Key, +Value) #### Description Sets the environment variable Key to Value. #### Method SET (conceptual) #### Endpoint N/A (predicate) #### Parameters - **Key** (string) - Required - The name of the environment variable to set. - **Value** (string) - Required - The value to set the environment variable to. ### unsetenv(+Key) #### Description Unsets the environment variable Key. #### Method DELETE (conceptual) #### Endpoint N/A (predicate) #### Parameters - **Key** (string) - Required - The name of the environment variable to unset. ### Request Example ```prolog ?- getenv("LANG", Ls). Ls = "en_US.UTF-8". ``` ### Response Example (N/A for predicates, shows result of query) ``` -------------------------------- ### Querying Simplex Solver Results in Scryer PL Source: https://www.scryer.pl/simplex This example shows how to query the results of a solved simplex problem in Scryer PL. It uses `coins(S)` to solve the problem and then `variable_value/3` to extract the values of specific variables (c(1), c(5), c(20)) from the solved state S. ```Prolog ?- coins(S), variable_value(S, c(1), C1), variable_value(S, c(5), C5), variable_value(S, c(20), C20). S = solved(...), C1 = 1 rdiv 1, C5 = 2 rdiv 1, C20 = 5 rdiv 1. ``` -------------------------------- ### Create and Manage System Processes Source: https://www.scryer.pl/process Demonstrates the usage of process_create to spawn a new process with specific options like working directory, environment variables, and stream redirection. ```prolog process_create(Exe, Args, [cwd(Path), stdout(pipe(Stream))]). ``` -------------------------------- ### Serialized Task Constraint (serialized/2) Source: https://www.scryer.pl/clpz The serialized/2 predicate constrains a set of tasks to be non-overlapping. It takes lists of start times (variables or integers) and non-negative durations. The constraint ensures that for any two tasks i and j, task i finishes before task j starts, or task j finishes before task i starts. ```Prolog ?- length(Vs, 3), Vs ins 0..3, serialized(Vs, [1,2,3]), label(Vs). Vs = [0,1,3] ; Vs = [2,0,3] ; false. ``` -------------------------------- ### Retrieve and Format System Time Source: https://www.scryer.pl/time Demonstrates how to import the time library, retrieve the current system timestamp, and format it into a human-readable string using phrase/2 and format_time//2. ```prolog :- use_module(library(time)). ?- current_time(T), phrase(format_time("%d.%m.%Y (%H:%M:%S)", T), Cs). ``` -------------------------------- ### Open and Read from Files Source: https://www.scryer.pl/builtins Shows how to open a file stream with specific options and read characters from it using Scryer Prolog stream predicates. ```prolog ?- open("README.md", read, S, []), get_n_chars(S, 20, C). ``` -------------------------------- ### GET /assoc/list Source: https://www.scryer.pl/assoc Predicates for converting association lists to standard Prolog lists and vice versa. ```APIDOC ## GET /assoc/to_list ### Description Translates an association list into a list of Key-Value pairs sorted by key. ### Method GET ### Endpoint assoc_to_list(+Assoc, -Pairs) ### Parameters #### Path Parameters - **Assoc** (assoc) - Required - The association list to convert. ### Response #### Success Response (200) - **Pairs** (list) - A list of Key-Value pairs sorted in ascending order by key. ``` -------------------------------- ### Importing the pio module Source: https://www.scryer.pl/pio This snippet demonstrates how to import the pure I/O library into a Scryer Prolog module to enable DCG-based file and stream operations. ```prolog :- use_module(library(pio)). ``` -------------------------------- ### GET /assoc/query Source: https://www.scryer.pl/assoc Predicates for retrieving data from association lists, including lookups and range queries. ```APIDOC ## GET /assoc/get ### Description Retrieves a value associated with a specific key from an association list. ### Method GET ### Endpoint get_assoc(+Key, +Assoc, -Value) ### Parameters #### Path Parameters - **Key** (any) - Required - The key to search for. - **Assoc** (assoc) - Required - The association list to query. ### Response #### Success Response (200) - **Value** (any) - The value associated with the key. #### Error Handling - Throws `type_error(assoc, Assoc)` if the input is not a valid association list. ``` -------------------------------- ### Importing and Using the si Module Source: https://www.scryer.pl/si Demonstrates how to import the si library and use the chars_si/1 predicate to perform a safe type test on a list of characters. ```Prolog :- use_module(library(si)). ?- chars_si(Cs). error(instantiation_error,list_si/1). ?- chars_si("hello"). true. ?- chars_si(hello). false. ``` -------------------------------- ### Initialize CLP(B) Library Source: https://www.scryer.pl/clpb Load the clpb module into the current Prolog environment to enable Boolean constraint solving. ```Prolog :- use_module(library(clpb)). ``` -------------------------------- ### TLS Client Context and Negotiation (Prolog) Source: https://www.scryer.pl/tls Provides functions for managing TLS client contexts and negotiating secure connections. Requires the tls library to be imported. ```Prolog tls_client_context/2 ``` ```Prolog tls_client_negotiate/3 ``` -------------------------------- ### Get All Vertices from a Graph (Prolog) Source: https://www.scryer.pl/ugraphs Unifies a list with all vertices present in a given graph. The graph is expected to be in S-representation. ```Prolog :- use_module(library(ugraphs)). ?- vertices([1-[3,5],2-[4],3-[],4-[5],5-[]], L). L = [1, 2, 3, 4, 5] ``` -------------------------------- ### Get File Size - Prolog Source: https://www.scryer.pl/files Retrieves the size of a file in bytes. The file must exist for this predicate to succeed. ```Prolog :- use_module(library(files)). file_size(+File, ?Size). ``` -------------------------------- ### Creating and Querying Association Lists Source: https://www.scryer.pl/assoc Demonstrates basic creation of an association list from a list of pairs and retrieving a value by key. ```prolog list_to_assoc([a-1, b-2], Assoc), get_assoc(a, Assoc, Value). ``` -------------------------------- ### Implement Deterministic Factorial with zcompare Source: https://www.scryer.pl/clpz Demonstrates using zcompare to create a deterministic factorial implementation that preserves generality. It uses first-argument indexing to distinguish between base and recursive cases. ```Prolog n_factorial(N, F) :- zcompare(C, N, 0), n_factorial_(C, N, F). n_factorial_(=, _, 1). n_factorial_(>, N, F) :- F #= F0*N, N1 #= N - 1, n_factorial(N1, F0). ``` -------------------------------- ### List Aggregation with Foldl Source: https://www.scryer.pl/lists The foldl/N predicates perform reduction on lists. This example shows how to define sum_list using foldl. ```Prolog sum_(L, S0, S) :- S is S0 + L. sum_list(Ls, S) :- foldl(sum_, Ls, 0, S). ``` -------------------------------- ### Implement HTTP Basic Authentication Source: https://www.scryer.pl/http/http_server Shows how to wrap a handler with HTTP Basic Authentication using the http_basic_auth meta-predicate to restrict access. ```prolog main :- http_listen(8800,[get('/', http_basic_auth(login, inside_handler("data")))]). login(User, Pass) :- User = "aarroyoc", Pass = "123456". inside_handler(Data, User, Request, Response) :- http_body(Response, text(User)). ``` -------------------------------- ### Get All Edges from a Graph (Prolog) Source: https://www.scryer.pl/ugraphs Unifies a list with all edges present in a given graph. Each edge is represented as a pair (Source-Destination). ```Prolog :- use_module(library(ugraphs)). ?- edges([1-[3,5],2-[4],3-[],4-[5],5-[]], L). L = [1-3, 1-5, 2-4, 4-5] ``` -------------------------------- ### Introduction to CLP(Z) Source: https://www.scryer.pl/clpz This section introduces the CLP(Z) library, its core concepts, and its primary use cases in declarative integer arithmetic and combinatorial problem-solving. ```APIDOC ## Introduction to CLP(Z) ### Description This library provides CLP(ℤ): Constraint Logic Programming over Integers. CLP(ℤ) is an instance of the general CLP(_X_) scheme, extending logic programming with reasoning over specialised domains. CLP(ℤ) lets us reason about **integers** in a way that honors the relational nature of Prolog. There are two major use cases of CLP(ℤ) constraints: 1. **declarative integer arithmetic** 2. solving **combinatorial problems** such as planning, scheduling and allocation tasks. ### Key Predicates The predicates of this library can be classified as: * _arithmetic_ constraints like `(#=)/2`, `(#>)/2` and `(#\=)/2` * the _membership_ constraints `(in)/2` and `(ins)/2` * the _enumeration_ predicates `indomain/1`, `label/1` and `labeling/2` * _combinatorial_ constraints like `all_distinct/1` and `global_cardinality/2` * _reification_ predicates such as `(#<==>)/2` * _reflection_ predicates such as `fd_dom/2` ### Usage Recommendation In most cases, _arithmetic constraints_ are the only predicates you will ever need from this library. When reasoning over integers, simply replace low-level arithmetic predicates like `(is)/2` and `(>)/2` by the corresponding CLP(ℤ) constraints like `(#=)/2` and `(#>)/2` to honor and preserve declarative properties of your programs. For satisfactory performance, arithmetic constraints are implicitly rewritten at compilation time so that low-level fallback predicates are automatically used whenever possible. Almost all Prolog programs also reason about integers. Therefore, it is highly advisable that you make CLP(ℤ) constraints available in all your programs. One way to do this is to put the following directive in your `~/.scryerrc` initialisation file: ```prolog :- use_module(library(clpz)). ``` All example programs that appear in the CLP(ℤ) documentation assume that you have done this. ### Further Information Important concepts and principles of this library are illustrated by means of usage examples that are available in a public git repository: **https://github.com/triska/clpz** If you are used to the complicated operational considerations that low-level arithmetic primitives necessitate, then moving to CLP(ℤ) constraints may, due to their power and convenience, at first feel to you excessive and almost like cheating. It _isn't_. Constraints are an integral part of all popular Prolog systems, and they are designed to help you eliminate and avoid the use of low-level and less general primitives by providing declarative alternatives that are meant to be used instead. When teaching Prolog, CLP(ℤ) constraints should be introduced _before_ explaining low-level arithmetic predicates and their procedural idiosyncrasies. This is because constraints are easy to explain, understand and use due to their purely relational nature. In contrast, the modedness and directionality of low-level arithmetic primitives are impure limitations that are better deferred to more advanced lectures. More information about CLP(ℤ) constraints and their implementation is contained in: **metalevel.at/drt.pdf** The best way to discuss applying, improving and extending CLP(ℤ) constraints is to use the dedicated `clpz` tag on stackoverflow.com. Several of the world's foremost CLP(ℤ) experts regularly participate in these discussions and will help you for free on this platform. ``` -------------------------------- ### Find Reachable Vertices Source: https://www.scryer.pl/ugraphs Calculates the set of all vertices reachable from a specific starting vertex within a UGraph. Returns an ordered list of vertices. ```prolog ?- reachable(1,[1-[3,5],2-[4],3-[],4-[5],5-[]],V). ``` -------------------------------- ### Get Current Hostname in Prolog Source: https://www.scryer.pl/sockets Retrieves the hostname of the machine where the Scryer Prolog process is currently running. This can be useful for network identification or configuration. ```prolog current_hostname(-HostName). ``` -------------------------------- ### TLS Server Context and Negotiation (Prolog) Source: https://www.scryer.pl/tls Provides functions for managing TLS server contexts and negotiating secure connections. Requires the tls library to be imported. ```Prolog tls_server_context/2 ``` ```Prolog tls_server_negotiate/3 ``` -------------------------------- ### Terminate and Release Processes Source: https://www.scryer.pl/process Demonstrates how to forcefully kill a process using its handle and how to release the handle after the process has concluded. ```prolog process_kill(Process). process_release(Process). ``` -------------------------------- ### Get Neighbors of a Vertex (Alias) (Prolog) Source: https://www.scryer.pl/ugraphs An alias for the `neighbours/3` predicate, providing the same functionality to retrieve a sorted list of a vertex's neighbours in a graph. ```Prolog :- use_module(library(ugraphs)). % Same functionality as neighbours/3. % Example: neighbors(4, Graph, NeighborsList). ``` -------------------------------- ### Initialize Random Library Source: https://www.scryer.pl/random Imports the random library module into the current Prolog environment to enable probabilistic predicates. ```prolog :- use_module(library(random)). ``` -------------------------------- ### Complex Data Extraction Predicate Source: https://www.scryer.pl/xpath A comprehensive example defining a predicate to extract product names, URLs, and prices from a table structure using multiple XPath operations. ```prolog product(DOM, Name, URL, Price) :- xpath(DOM, //tr, TR), xpath(TR, td(1), C1), xpath(C1, /self(normalize_space), Name), xpath(C1, a(@href), URL), xpath(TR, td(2, number), Price). ``` -------------------------------- ### Using Lambda Expressions with maplist Source: https://www.scryer.pl/lambda Demonstrates how to use lambda expressions to filter or process lists. The example uses a lambda to check if elements in a list are greater than 3. ```prolog :- use_module(library(lambda)). :- use_module(library(lists)). ?- maplist(\X^(X>3), [4,5,9]). ``` -------------------------------- ### Create Directory Path - Prolog Source: https://www.scryer.pl/files Recursively creates directories if they do not exist, similar to 'mkdir -p' in Unix. This is useful for ensuring the entire path to a new directory exists. ```Prolog :- use_module(library(files)). make_directory_path(+Directory). ``` -------------------------------- ### Modeling Boolean Circuits with CLP(B) Source: https://www.scryer.pl/clpb Shows how to implement a Boolean XOR gate using NAND gates and CLP(B) constraints. It demonstrates verifying the circuit logic using universal quantification. ```Prolog :- use_module(library(clpb)). nand_gate(X, Y, Z) :- sat(Z =:= ~(X*Y)). xor(X, Y, Z) :- nand_gate(X, Y, T1), nand_gate(X, T1, T2), nand_gate(Y, T1, T3), nand_gate(T2, T3, Z). ?- xor(x, y, Z). clpb:sat(Z=:=x#y). ``` -------------------------------- ### Scryer PL Simplex Predicate: gen_state/1 Source: https://www.scryer.pl/simplex Generates an initial state corresponding to an empty linear program. This is the starting point for defining a new linear programming problem. ```Prolog gen_state(-State) ``` -------------------------------- ### Equivalence of Lambda Expressions and call/N Source: https://www.scryer.pl/lambda Illustrates that lambda expressions are equivalent to standard call/N patterns, demonstrating how arguments are passed through nested lambdas. ```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). ``` -------------------------------- ### Scryer PL Simplex Predicate: constraint/4 Source: https://www.scryer.pl/simplex Similar to constraint/3, but also attaches a Name to the new constraint. This allows referencing the constraint later, for example, when querying shadow prices. ```Prolog constraint(+Name, +Constraint, +S0, -S) ``` -------------------------------- ### Create Directory - Prolog Source: https://www.scryer.pl/files Creates a new directory with the specified name. For creating nested directories, use `make_directory_path/1`. ```Prolog :- use_module(library(files)). make_directory(+Directory). ``` -------------------------------- ### Prolog: Generate list of integers between Lower and Upper (numlist/3) Source: https://www.scryer.pl/between Generates a list of integers starting from Lower and ending at Upper (inclusive). This predicate is useful for creating specific ranges of numbers. ```prolog numlist(?Lower, ?Upper, ?List). ?- numlist(5, 10, X). ``` -------------------------------- ### Open Client Socket Connection in Prolog Source: https://www.scryer.pl/sockets Opens a socket connection to a specified server address and port, returning a stream for communication. Options can configure stream alias, end-of-file action, repositioning, and data type (text/binary). ```prolog socket_client_open(+Addr, -Stream, +Options). ``` -------------------------------- ### Get Neighbours of a Vertex (Prolog) Source: https://www.scryer.pl/ugraphs Retrieves a sorted list of all direct neighbours (vertices connected by an edge) of a specified vertex within a graph. Handles cases where a vertex may not have any neighbours. ```Prolog :- use_module(library(ugraphs)). ?- neighbours(4,[1-[3,5],2-[4],3-[], 4-[1,2,7,5],5-[],6-[],7-[],8-[]], NL). NL = [1,2,7,5] ``` -------------------------------- ### Generate UUID v4 String (Prolog) Source: https://www.scryer.pl/uuid Generates a new version 4 UUID (random) and unifies it with its hexadecimal string representation. This is a convenient way to get a UUID in a commonly used format. ```prolog :- use_module(library(uuid)). % Example usage: % ?- uuidv4_string(X). % X = "428499fc-76e3-4240- ...". ``` -------------------------------- ### Import Process Module Source: https://www.scryer.pl/process Loads the process library into the current Prolog environment to enable process management predicates. ```prolog :- use_module(library(process)). ``` -------------------------------- ### Importing the Assoc Module Source: https://www.scryer.pl/assoc This snippet demonstrates how to load the association list library into a Scryer Prolog module. ```prolog :- use_module(library(assoc)). ``` -------------------------------- ### List Manipulation with append/3 in Scryer Prolog Source: https://www.scryer.pl/ Demonstrates the use of the append/3 predicate to concatenate lists or determine missing list segments. This example shows how Scryer Prolog resolves the variable X to complete the string. ```prolog ?- append("Hello, ", X, "Hello, Scryer Prolog!"). X = "Scryer Prolog!". ``` -------------------------------- ### Accept Incoming Connection in Prolog Source: https://www.scryer.pl/sockets Accepts an incoming connection on a given ServerSocket. It returns client information and a stream for communication with the connected client. Options similar to `socket_client_open/3` are available for stream configuration. ```prolog socket_server_accept(+ServerSocket, -Client, -Stream, +Options). ``` -------------------------------- ### Prolog: Use library(between) Source: https://www.scryer.pl/between Imports the 'between' library, which contains predicates for reasoning about integers in a reduced domain. ```prolog :- use_module(library(between)). ``` -------------------------------- ### Topological Sort for Unconnected Graphs Source: https://www.scryer.pl/ugraphs Demonstrates how to use connect_ugraph to handle disconnected graphs for topological sorting. It attempts a standard sort and falls back to connecting all vertices to a new start node if the graph is not connected. ```prolog top_sort_unconnected(Graph, Vertices) :- ( top_sort(Graph, Vertices) -> true ; connect_ugraph(Graph, Start, Connected), top_sort(Connected, Ordered0), Ordered0 = [Start|Vertices] ). ``` -------------------------------- ### Collect Unique Sorted Solutions with setof/3 Source: https://www.scryer.pl/builtins Similar to bagof/3, setof/3 collects all solutions for Template from Goal. However, the resulting Solution list is sorted and duplicates are removed. The example demonstrates collecting unique values of X. ```Prolog f(1, 2). f(1, 3). f(2, 4). ?- setof(X, Y^f(X, Y), Set). Set = [1, 2]. ``` -------------------------------- ### HTTP Server Configuration Source: https://www.scryer.pl/http/http_server Details on configuring the http_server, including listening port and handlers. ```APIDOC ## `http_listen/2` and `http_listen/3` ### Description These predicates are used to start an HTTP server, specifying the port to listen on and a list of handlers. ### Method N/A (Predicate definitions) ### Endpoint N/A (Predicate definitions) ### Parameters #### `http_listen(+Port, +Handlers)` - **Port** (integer) - The port number to listen on. - **Handlers** (list) - A list of handlers, each defined as `HttpVerb(PathUnification, Predicate)`. #### `http_listen(+Port, +Handlers, +Options)` - **Port** (integer) - The port number to listen on. - **Handlers** (list) - A list of handlers. - **Options** (list) - A list of configuration options. - `tls_key` (string) - Path to the TLS key for HTTPS. - `tls_cert` (string) - Path to the TLS certificate for HTTPS. - `content_length_limit` (integer) - Maximum length of incoming request bodies (default: 32KB). ### Request Example ```prolog http_listen(8080, [ get('/', index_handler) ], [tls_key('server.key'), tls_cert('server.crt')]) ``` ``` -------------------------------- ### Using tfilter/3 with dif/2 in Scryer Prolog Source: https://www.scryer.pl/reif Demonstrates the usage of the tfilter/3 predicate with dif/2 for filtering lists based on conditions involving difference lists. This example shows how to filter a list of variables and observe the resulting bindings and constraints. ```Prolog :- use_module(library(reif)). ?- tfilter(=(a), [X,Y], Es). X = a, Y = a, Es = "aa" ; X = a, Es = "a", dif:dif(a,Y) ; Y = a, Es = "a", dif:dif(a,X) ; Es = [], dif:dif(a,X), dif:dif(a,Y). ``` -------------------------------- ### Resource Cleanup with setup_call_cleanup/3 Source: https://www.scryer.pl/iso_ext This predicate ensures that a cleanup goal is executed regardless of whether the main goal succeeds or fails. It is commonly used for resource management, such as closing file streams. ```prolog ?- setup_call_cleanup(open(File, read, Stream), do_something_with_stream(Stream), close(Stream)). ``` -------------------------------- ### process_create/3 Source: https://www.scryer.pl/process Creates a new process by executing a specified executable with given arguments and options. ```APIDOC ## POST /process/create ### Description Creates a new process by executing the specified executable with the given arguments. ### Method POST ### Endpoint /process/create ### Parameters #### Request Body - **exe** (string) - Required - The executable to run. - **args** (list) - Required - A list of string arguments for the executable. - **options** (list) - Optional - A list of options to configure the process: - **cwd** (string) - The working directory for the process. Defaults to ".". - **process** (variable) - If provided, will be unified with a process handle. - **env** (list) - A list of string pairs (e.g., 'KEY=VALUE') to set environment variables, replacing inherited ones. Cannot be used with `environment`. - **environment** (list) - A list of string pairs (e.g., 'KEY=VALUE') to set/override environment variables, inheriting existing ones. Cannot be used with `env`. - **stdin** (string) - How to redirect the standard input. Possible values: `std`, `file(Path)`, `null`, `pipe(-Stream)`. - **stdout** (string) - How to redirect the standard output. Possible values: `std`, `file(Path)`, `null`, `pipe(-Stream)`. - **stderr** (string) - How to redirect the standard error. Possible values: `std`, `file(Path)`, `null`, `pipe(-Stream)`. ### Request Example ```json { "exe": "/bin/ls", "args": ["-l", "-a"], "options": { "cwd": "/home/user", "stdout": "pipe(-Stream)" } } ``` ### Response #### Success Response (200) - **process_handle** (string) - A handle to the created process if `process` option was used. - **stream** (object) - If `stdout` was set to `pipe(-Stream)`, this contains the stream object. #### Response Example ```json { "process_handle": "", "stream": "" } ``` ``` -------------------------------- ### Sub-Atom Extraction: sub_atom/5 Source: https://www.scryer.pl/builtins This predicate relates an atom to a subatom within it, specifying the starting position (Before), length (Length), and characters remaining after the subatom (After). It's useful for extracting parts of atoms, though strings are recommended for complex operations. ```Prolog ?- sub_atom(abcdefg, 2, 3, X, SubAtom). X = 2, SubAtom = cde. ``` -------------------------------- ### Solve Boolean Satisfiability and Tautologies Source: https://www.scryer.pl/clpb Demonstrates basic usage of sat/1 for satisfiability, taut/2 for tautology checking, and labeling/1 for assigning truth values to variables. ```Prolog ?- sat(X*Y). ?- sat(X * ~X). ?- taut(X * ~X, T). ?- sat(X*Y + X*Z), labeling([X,Y,Z]). ``` -------------------------------- ### Finite Domain Equivalence Constraint (#<==>) Source: https://www.scryer.pl/clpz The #<==> predicate establishes logical equivalence between two finite domain constraints P and Q. It's used for reifying constraints, relating variables to the truth of a condition. For example, it can link a boolean variable to whether a constraint holds. ```Prolog ?- X #= 4 #<==> B, X #\= 4. B = 0, X in inf..3\/5..sup. vs_n_num(Vs, N, Num) :- maplist(eq_b(N), Vs, Bs), sum(Bs, #=, Num). eq_b(X, Y, B) :- X #= Y #<==> B. ?- Vs = [X,Y,Z], Vs ins 0..1, vs_n_num(Vs, 4, Num). Vs = [X, Y, Z], Num = 0, X in 0..1, Y in 0..1, Z in 0..1. ?- vs_n_num([X,Y,Z], 2, 3). X = 2, Y = 2, Z = 2. ``` -------------------------------- ### Hamiltonian Circuit Constraint (circuit/1) Source: https://www.scryer.pl/clpz The circuit/1 predicate constrains a list of finite domain variables to represent a Hamiltonian circuit. The k-th element of the list denotes the successor of node k, with node indexing starting from 1. It's used for problems involving cycles in graphs. ```Prolog ?- length(Vs, _), circuit(Vs), label(Vs). Vs = [] ; Vs = [1] ; Vs = [2,1] ; Vs = [2,3,1] ; Vs = [3,1,2] ; Vs = [2,3,4,1] ; ... . ``` -------------------------------- ### Generate Random Numbers and Probabilities Source: https://www.scryer.pl/random Demonstrates common random generation tasks including floating point numbers, integers, and probabilistic success. ```prolog % Succeeds with 0.5 probability maybe. % Generate float between 0 and 1 random(R). % Generate integer between Lower and Upper random_integer(1, 10, R). % Set seed for reproducibility set_random(12345). ``` -------------------------------- ### Prolog DCG: Phrase Matching with Remainder Source: https://www.scryer.pl/dcgs This snippet illustrates the usage of the `phrase/3` predicate in Prolog DCGs, which allows matching a grammar body against a portion of a list and returning the remaining part. The example uses a `seq(X)` grammar to demonstrate matching and returning the rest of the input string. ```Prolog :- use_module(library(dcgs)). ?- phrase(seq(X), "aaa", Y). X = [], Y = "aaa" ; X = "a", Y = "aa" ; X = "aa", Y = "a" ; X = "aaa", Y = []. ``` -------------------------------- ### Load XPath Library Source: https://www.scryer.pl/xpath This snippet shows how to load the necessary xpath library in Prolog. It's a prerequisite for using any of the xpath predicates. ```Prolog :- use_module(library(xpath)). ``` -------------------------------- ### Cumulative Constraint for Resource Scheduling Source: https://www.scryer.pl/clpz The cumulative/2 constraint schedules tasks with limited resources. It ensures that at any given time, the total resource consumption of active tasks does not exceed a specified limit. Tasks are defined by their start time, duration, end time, resource consumption, and identifier. The 'limit(L)' option specifies the global resource limit. ```Prolog tasks_starts(Tasks, [S1,S2,S3]) :- Tasks = [task(S1,3,_,1,_), task(S2,2,_,1,_), task(S3,2,_,1,_)]. ?- tasks_starts(Tasks, Starts), Starts ins 0..10, cumulative(Tasks, [limit(2)]), label(Starts). Tasks = [task(0, 3, 3, 1, _G36), task(0, 2, 2, 1, _G45), ...], Starts = [0, 0, 2] . ``` -------------------------------- ### Importing the format library Source: https://www.scryer.pl/format Standard directive to include the format library in a Scryer Prolog module. ```prolog :- use_module(library(format)). ``` -------------------------------- ### Importing the atts module Source: https://www.scryer.pl/atts This snippet demonstrates how to import the library(atts) module into a Scryer Prolog source file. It is a prerequisite for using attributed variables within the module. ```prolog :- use_module(library(atts)). ``` -------------------------------- ### Importing the Terms Library Source: https://www.scryer.pl/terms This snippet demonstrates how to import the terms library in Scryer Prolog to gain access to term manipulation predicates. ```prolog :- use_module(library(terms)). ``` -------------------------------- ### Use Sockets Library in Prolog Source: https://www.scryer.pl/sockets This snippet demonstrates how to load the sockets library in Scryer Prolog. It's a prerequisite for using any of the socket-related predicates. ```prolog :- use_module(library(sockets)). ``` -------------------------------- ### Basic Term Output: write/2, write/1, write_canonical/2, write_canonical/1, writeq/2, writeq/1 Source: https://www.scryer.pl/builtins Documentation for basic predicates to write terms to streams using different syntaxes. ```APIDOC ## Basic Term Output Predicates ### Description Provides predicates for writing terms to streams using various Prolog syntaxes. ### Predicates #### `write(+Term)` / `write(+Stream, +Term)` - **Description**: Writes a term using a standard Prolog-like syntax. #### `write_canonical(+Term)` / `write_canonical(+Stream, +Term)` - **Description**: Writes a term using canonical Prolog syntax, ensuring it can be read back. #### `writeq(+Term)` / `writeq(+Stream, +Term)` - **Description**: Writes a term similar to `write/1` but quotes atoms that require quoting for valid Prolog syntax. ``` -------------------------------- ### Open Server Socket in Prolog Source: https://www.scryer.pl/sockets Opens a server socket to listen for incoming connections on a specified address and port. The returned ServerSocket can then be used with `socket_server_accept/4` to handle client connections. ```prolog socket_server_open(+Addr, -ServerSocket). ``` -------------------------------- ### Generate Random Bytes and Convert to Integer Source: https://www.scryer.pl/crypto Shows how to generate cryptographically secure random bytes using crypto_n_random_bytes/2 and convert them into a large integer using CLP(Z) constraints. ```Prolog :- use_module(library(clpz)). :- use_module(library(lists)). bytes_integer(Bs, N) :- foldl(pow, Bs, 0-0, N-_). pow(B, N0-I0, N-I) :- B in 0..255, N #= N0 + B*256^I0, I #= I0 + 1. ?- crypto_n_random_bytes(32, Bs), bytes_integer(Bs, I). ``` -------------------------------- ### Write CSV Data with Scryer Prolog Source: https://www.scryer.pl/csv Demonstrates how to write CSV data to files using the write_csv/2 and write_csv/3 predicates. Supports custom line separators, token separators, and header toggles. ```prolog ?- use_module(library(csv)). ?- write_csv('./test.csv', frame(["col1","col2","col3","col4"], [["one",2,[],"three"]])). ?- write_csv('./test.csv', frame( ["col1","col2","col3","col4"], [["one",2,[],"three"]] ), [with_header(false), line_separator('\r\n'), token_separator(';'), null_value('\\N')]). ``` -------------------------------- ### Query N-Queens Solver Source: https://www.scryer.pl/clpz Demonstrates how to invoke the n_queens/2 predicate to find solutions for a standard 8x8 board and a larger 80x80 board using specific labeling strategies like 'ff' (first-fail). ```prolog ?- n_queens(8, Qs), label(Qs). ?- n_queens(80, Qs), labeling([ff], Qs). ?- time((n_queens(90, Qs), labeling([ff], Qs))). ``` -------------------------------- ### Encrypt and Decrypt Data with ChaCha20-Poly1305 Source: https://www.scryer.pl/crypto Demonstrates how to generate random keys and nonces, encrypt a string, and subsequently decrypt it using the authenticated chacha20-poly1305 scheme. It highlights the necessity of the authentication tag for successful decryption. ```prolog ?- Algorithm = 'chacha20-poly1305', crypto_n_random_bytes(32, Key), crypto_n_random_bytes(12, IV), crypto_data_encrypt("this text is to be encrypted", Algorithm, Key, IV, CipherText, [tag(Tag)]), crypto_data_decrypt(CipherText, Algorithm, Key, IV, RecoveredText, [tag(Tag)]). ``` -------------------------------- ### Import tls Library (Prolog) Source: https://www.scryer.pl/tls Imports the 'tls' library in Prolog. This is a prerequisite for using any of the functions defined within the tls module. ```Prolog :- use_module(library(tls)). ``` -------------------------------- ### Knapsack Problem LP (Prolog) Source: https://www.scryer.pl/simplex Solves a knapsack problem using the simplex library. It defines constraints for capacity and item limits, then maximizes the value of items. An integral version is also provided. ```prolog :- use_module(library(simplex)). knapsack(S) :- knapsack_constraints(S0), maximize([7*x(1), 4*x(2)], S0, S). knapsack_constraints(S) :- gen_state(S0), constraint([6*x(1), 4*x(2)] =< 8, S0, S1), constraint([x(1)] =< 1, S1, S2), constraint([x(2)] =< 2, S2, S). ``` ```prolog knapsack_integral(S) :- knapsack_constraints(S0), constraint(integral(x(1)), S0, S1), constraint(integral(x(2)), S1, S2), maximize([7*x(1), 4*x(2)], S2, S). ```