Prolog in WebAssembly

Prolog is a logic programming language with several different implementations. Trealla Prolog is the one most frequently associated with WebAssembly.

Available Implementations

Usage

The easiest way to use Trealla Prolog is with the Spin plugin. It will manage the Prolog runtime for you.

Install the Spin plugin:

$ spin templates install --git https://github.com/guregu/trealla-spin --update

Otherwise, you can follow the installation and build instructions on the Trealla Prolog GitHub page.

Pros and Cons

Things we like:

Example

Create a new app:

$ spin new http-prolog hello-prolog --accept-defaults

Run the app:

$ cd hello-prolog
$ spin up

Logging component stdio to ".spin/logs/"
Storing default key-value data to ".spin/sqlite_key_value.db"

Serving http://127.0.0.1:3000
Available Routes:
  hello-prolog: http://127.0.0.1:3000 (wildcard)

Doing spin up fetches the prolog interpreter, so there is no spin build step.

The scaffolded code looks like this:

:- use_module(library(spin)).

% See library/spin.pl for all the predicates built-in
% https://github.com/guregu/trealla/blob/main/library/spin.pl

%% http_handler(+Spec, +Headers, +Body, -Status)

http_handler(get("/", _QueryParams), _RequestHeaders, _RequestBody, 200) :-
	html_content,
	setup_call_cleanup(
		store_open(default, Store),
		(
			(  store_get(Store, counter, N0)
			-> true
			;  N0 = 0
			),
			succ(N0, N),
			store_set(Store, counter, N)
		),
		store_close(Store)
	),
	http_header_set("x-powered-by", "memes"),
	current_prolog_flag(dialect, Dialect),
	% stream alias http_body is the response body
	write(http_body, '<!doctype html><html>'),
	format(http_body, "<h1>Hello, ~a prolog!</h1>", [Dialect]),
	format(http_body, "Welcome, visitor #<b>~d!</b>", [N]),
	write(http_body, '</html>').

http_handler(get("/json", _), _, _, 200) :-
	wall_time(Time),
	% json_content({"time": Time}) works too
	json_content(pairs([string("time")-number(Time)])).

Learn More

Here are some great resources: