String prepend: Difference between revisions

→‎{{header|Prolog}}: Added proper answer.
(→‎{{header|Prolog}}: Added proper answer.)
Line 450:
=={{header|Prolog}}==
 
Using{{works with|SWI-Prolog's string handling predicates:}}
 
In its admirable wisdom, Prolog is generally unfriendly
to state mutations and destructive assignment. However, it
is also very flexible. Using the traditional representation
of strings as lists of character codes, and the non-logical
predicate `setarg/3`, we can destructively set the head and
tail of the list to achieve a mutation of the variable holding
the string. I define an operator for the purpose:
 
{{works with|SWI-Prolog 7}}
 
<lang prolog>
:- op(200, xfx, user:(=+)).
?- String = "World!", string_concat("Hello, ", String, StringPrepended).
 
String = "World!",
%% +Prepend =+ +Chars
StringPrepended = "Hello, World!".
%
% Will destructively update Chars
% So that Chars = Prepend prefixed to Chars.
 
[X|Xs] =+ Chars :-
duplicate_term(Chars, CharsDup),
append(Xs, CharsDup, Rest),
setarg(1, Chars, X),
setarg(2, Chars, Rest).
</lang>
 
Example of this abomination in action:
Using the traditional list of character codes, `append/3` suffices:
 
<lang prolog>
?- CharsStr = `World!`, append(`Hello, `, Chars,=+ CharsPrepended)Str.
CharsStr = "Hello World!",.
CharsPrepended = "Hello, World!".
</lang>
 
Note: I can't imagine when I would want to do this in Prolog.
The representation of these two approaches looks the same, but the underlying data differs.
 
=={{header|PureBasic}}==