Url Parsing in Prolog
Our URL parsing program demonstrates how to parse and extract components from a URL string in Prolog.
:- use_module(library(uri)).
main :-
% We'll parse this example URL, which includes a
% scheme, authentication info, host, port, path,
% query params, and query fragment.
S = "postgres://user:pass@host.com:5432/path?k=v#f",
% Parse the URL and ensure there are no errors.
uri_parse(S, URI),
% Accessing the scheme is straightforward.
uri_component(URI, scheme, Scheme),
writeln(Scheme),
% User contains all authentication info; we'll extract
% username and password separately.
uri_component(URI, user, User),
writeln(User),
uri_component(URI, username, Username),
writeln(Username),
uri_component(URI, password, Password),
writeln(Password),
% The Host contains both the hostname and the port,
% if present. We'll extract them separately.
uri_component(URI, host, Host),
writeln(Host),
uri_component(URI, hostname, Hostname),
writeln(Hostname),
uri_component(URI, port, Port),
writeln(Port),
% Here we extract the path and the fragment after
% the #.
uri_component(URI, path, Path),
writeln(Path),
uri_component(URI, fragment, Fragment),
writeln(Fragment),
% To get query params, we can use the search component.
% It returns a list of Key-Value pairs.
uri_component(URI, search, Search),
writeln(Search),
% We can also get the raw query string.
uri_component(URI, query, Query),
writeln(Query).Running our URL parsing program shows all the different pieces that we extracted:
$ swipl -q -t main -s url_parsing.pl
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
[k-v]
k=vIn this Prolog version:
We use the
urilibrary, which provides URL parsing functionality.The
uri_parse/2predicate is used to parse the URL string into a URI structure.We use
uri_component/3to extract various components from the parsed URI.Prolog doesn’t have a direct equivalent to Go’s
url.ParseQuery, but thesearchcomponent returns a list of Key-Value pairs, which is similar.Error handling in Prolog is typically done through predicate success or failure, rather than explicit error returns as in Go.
Prolog uses write predicates (
writeln/1) for output instead of afmt.Printlnfunction.
This example demonstrates how to work with URLs in Prolog, showing that while the syntax and approach differ from Go, similar functionality can be achieved.
Comments powered by Disqus