Anonymous user
Repeat a string: Difference between revisions
→{{header|Prolog}}
(→{{header|C++}}: adding recursive version) |
|||
Line 1,840:
repeat(Str,Num1,Res1),
string_concat(Str, Res1, Res).</lang>
=== alternative using DCG strings ===
This tail-recursive DCG implemention
is more efficient than anything using lists:append .
{{works with|SWI-Prolog|7}}
<lang prolog>
:- system:set_prolog_flag(double_quotes,chars) .
repeat(SOURCEz0,COUNT0,TARGETz)
:-
prolog:phrase(repeat(SOURCEz0,COUNT0),TARGETz)
.
%! repeat(SOURCEz0,COUNT0)//2
repeat(_SOURCEz0_,0)
-->
! ,
[]
.
repeat(SOURCEz0,COUNT0)
-->
SOURCEz0 ,
{ COUNT is COUNT0 - 1 } ,
repeat(SOURCEz0,COUNT)
.
</lang>
{{out}}
<pre>
/*
?- repeat("ha",5,TARGETz) .
TARGETz = [h, a, h, a, h, a, h, a, h, a].
?-
*/
</pre>
<pre>
:- begin_tests(basic) .
:- system:set_prolog_flag(double_quotes,chars) .
test('1',[])
:-
repeat("a",2,"aa")
.
test('2',[])
:-
repeat("ha",2,"haha")
.
test('3',[])
:-
repeat("ha",3,"hahaha")
.
test('4',[])
:-
repeat("",3,"")
.
test('5',[])
:-
repeat("ha",0,"")
.
test('6',[])
:-
repeat("ha",1,"ha")
.
:- end_tests(basic) .
</pre>
=={{header|Pure}}==
|