| Did you know ... | Search Documentation: |
| Pack starlog -- FOLDR_IMPLEMENTATION.md |
This implementation adds support for the foldr (fold right) higher-order predicate to the Starlog-in-Prolog library, enabling functional-style list processing operations.
Implement:
foldr(string_concat, reverse(string_chars("abc")), "", B). B= "cba"
Given all combinations and configurations.
Added the foldr/4 predicate to the user module:
foldr(Operation, List, Accumulator, Result)
Registered foldr as a value builtin with arity 3:
Result is foldr(operation, list, accumulator)default_value_builtin(foldr, 3).
For a list [x1, x2, x3] with operation f and accumulator acc:
foldr(f, [x1, x2, x3], acc) = f(x1, f(x2, f(x3, acc)))
Example with the problem statement:
string_chars("abc") → [a, b, c]
reverse([a, b, c]) → [c, b, a]
foldr(string_concat, [c,b,a], "", Result)
= string_concat(c, string_concat(b, string_concat(a, "")))
= string_concat(c, string_concat(b, "a"))
= string_concat(c, "ba")
= "cba" ✓
The implementation has been tested with all the following configurations:
string_chars("abc", Chars),
reverse(Chars, RevChars),
foldr(string_concat, RevChars, "", Result).
% Result = "cba"
starlog_call(B is foldr(string_concat, reverse(string_chars("abc")), "")).
% B = "cba"
Chars is string_chars("abc"),
RevChars is reverse(Chars),
Result is foldr(string_concat, RevChars, "").
% Result = "cba"
foldr(string_concat, [c,b,a], "", Result)foldr(append, [[1],[2],[3]], [], Result)foldr(atom_concat, [c,b,a], '', Result)foldr(string_concat, [], "init", Result) → Result = "init"foldr(string_concat, [x], "", Result) → Result = "x"foldl would be more efficientAll tests pass successfully:
✓ Pure Prolog syntax ✓ Starlog syntax with nested functions ✓ Different input strings (hello, world, x, empty) ✓ foldr with list append ✓ Empty list edge case ✓ Step-by-step evaluation ✓ Nested Starlog expressions
?- starlog_call(B is foldr(string_concat, reverse(string_chars("abc")), "")).
B = "cba".
?- foldr(append, [[1], [2], [3]], [], Result). Result = [1, 2, 3].
?- foldr(string_concat, [h, e, l, l, o], "", Result). Result = "hello".
The foldr predicate has been successfully implemented with full support for: