Anonymous user
Repeat a string: Difference between revisions
→{{header|OCaml}}: Bytes instead of String
(Add Kotlin) |
(→{{header|OCaml}}: Bytes instead of String) |
||
Line 1,012:
=={{header|OCaml}}==
Since Ocaml 4.02 strings are immutable, as is convenient for a functional language. Mutable strings are now implemented in the module Bytes.
<lang ocaml>let string_repeat s n =
let len =
let res =
for i = 0 to pred n do
done;
Bytes.to_string res (* not stricly necessary, the bytes type is equivalent to string except mutability *)
;;</lang>
which gives the signature<lang ocaml> val string_repeat : bytes -> int -> string = <fun></lang>
testing in the toplevel:
Line 1,025 ⟶ 1,027:
- : string = "HiuoaHiuoaHiuoa"</lang>
Alternately create an array initialized to s, and concat:
<lang ocaml>let string_repeat s n =
String.concat "" (Array.to_list (Array.make n s))
Line 1,035 ⟶ 1,037:
;;</lang>
To repeat a single character use:
<lang ocaml>String.make 5 '*'</lang>
|