Walrus (':=') operator

While reading the documentation on dicts, I came across the “:=” operator (which is called “walrus” in Python) and couldn’t understand how it works. There’s no direct link there, and neither the internal search nor Google helped me find its definition.

More than this specific instance, may I suggest that the builtin operators documentation contain links to every operator’s documentation? It’s usually hard to find these docs from Google, so much that Clojure has even created a page to explain them all in one place.

2 Likes

The example in the docs makes sense.

Note that := is not an operator created using op/3, i.e. source code. It is done using term_expansion/2.

HTH

All operators are created using op/3 (well, most built-in operators are created at initialization time from C before Prolog is started). Operators are no more than things that direct read/1 to properly parse terms holding them, so “1+2” is an alternative way to write “+(1,2)”, no more and no less. Operators are just syntactic constructs and carry no semantics.

Other code gives meaning to such terms, where a term may be given different meanings in different contexts. Some are implemented as predicates, e.g., >/2, others are functions for arithmetic evaluations (e.g., +/2) others guide the compiler (e.g., :- Directive), etc.

Linking the entries in the operator table to relevant documentation can indeed be useful (just needs work :frowning: )

It still doesn’t make sense to me, sorry. The code references a fqhead but I don’t understand what it does, nor found where it is defined.

AFAIU, this is just a syntactic “relocation”? So

M.multiply(F) := point{x:X, y:Y} :- ...

is equivalent to

M.multiply(F, point{x:X, y:Y}) :- ...

which in turn is equivalent to

multiply(M, F, point{x:X, y:Y}) :- ...

?

In the doc it notes

The . and := operators are used to abstract the location of the predicate arguments.

The . operator source code.

So point{x:1, y:2}.multiply(2). is taking point{x:1, y:2} and using the function multiply(F) to get point{x:2, y:4}.

./3 is defined as noted in the source code as .(Data, Func, Value) but used as an inline operator, e.g. X.Y as opposed to .(X,Y).

The user syntax then is point{x:1, y:2}.multiply(2). and used with is/2 to bind it to X, e.g. X is point{x:1, y:2}.multiply(2).

HTH

Do you want to know how it works or how to use it?

Thanks for the doc, the examples there made it ‘click’ to me that both ‘.’ and ‘:=’ rely on code rewriting to conform to the usual Prolog term syntax!

1 Like