Anonymous user
String prepend: Difference between revisions
→{{header|Prolog}}: Added proper answer.
(→{{header|Prolog}}: Added proper answer.) |
|||
Line 450:
=={{header|Prolog}}==
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:
<lang prolog>
:- op(200, xfx, user:(=+)).
%% +Prepend =+ +Chars
%
% 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:
<lang prolog>
?-
</lang>
Note: I can't imagine when I would want to do this in Prolog.
=={{header|PureBasic}}==
|