| Did you know ... | Search Documentation: |
| Pack starlog -- METHOD_CHAIN_IMPLEMENTATION.md |
Implement all combinations and configurations of nested predicate calls also being able to be called as method chains, e.g., d(a(b(1,C))) can be called b(1,C).a.d
Due to SWI-Prolog's built-in dictionary syntax using `.` for dict access, we implemented method chains using the >> operator instead. This provides the same functionality with a syntax commonly used in functional programming for piping/chaining operations.
% Original nested calls X is d(a(b(1,c))) % Method chain syntax (implemented) X is b(1,c) >> a >> d % Both produce: X = d(a(b(1,c)))
>> operator definition with precedence 650 (between is and other Starlog operators):- op(650, yfx, user:(>>))>> to operator definitions for pattern matchingis_starlog_expr clause to recognize method chainscontains_starlog_operator clause for >>compile_starlog_expr clause to handle method chain compilationb(1,c) >> a >> dreverse([1,2,3]) >> lengthsort([3,1,2]) >> reverse >> length% Simple chain ?- starlog_call(R is b(1,c) >> wrap_a). R = a(b(1,c)). % Multiple steps ?- starlog_call(R is b(1,c) >> wrap_a >> wrap_d). R = d(a(b(1,c))).
?- starlog_call(R is reverse([1,2,3]) >> length). R = 3. ?- starlog_call(R is sort([3,1,2]) >> reverse). R = [3,2,1].
?- starlog_call(R is ([1,2]&[3,4]) >> reverse).
R = [4,3,2,1].
?- starlog_call(R is ("hello":"world") >> string_length).
R = 10.
?- starlog_call(R is ([1,2]&[3,4]) >> reverse >> length). R = 4. ?- starlog_call(R is (reverse([1,2])&reverse([3,4])) >> flatten). R = [2,1,4,3].
b(1,c) >> a >> d works correctly>> instead of `.`?
SWI-Prolog version 7+ uses `.` as a built-in operator for dictionary access (e.g., Dict.key). This syntax is deeply integrated into the parser and takes precedence over custom operator definitions. Using >>:
>> operator is parsed as a right-associative binary operatora >> b >> c is parsed as a >> (b >> c)[a, b, c]a, then apply b to result, then apply c to that resultc(b(a(...)))Method chains work seamlessly with:
starlog_registry.pl:, &, •)
The method chain syntax implementation successfully addresses the problem statement by providing a fluent, left-to-right chaining syntax that is equivalent to nested predicate calls. The use of >> instead of `.` provides a practical solution that works reliably within SWI-Prolog's constraints while maintaining full backward compatibility.