Copy a string: Difference between revisions

m
Line 1,561:
 
=={{header|OCaml}}==
<lang ocaml>let src = "foobar"</lang>
<br/>
Before OCaml 4.02 (2014), strings were mutable and explicit deep copying was needed:
<lang ocaml>let dst = String.copy src</lang>
<br/>
Between 4.02 and 4.06 (2017), immutable strings were optionally enabled via a flag: <code>-safe-string</code>. A <code>Bytes</code> module was added to provide safe and unsafe mutable views on strings. The two modules were synonymous unless the aforementioned flag was added.
<lang ocaml>(* Special-case synonymy between types, explicit type annotations are just for emphasis *)
let dst1 : string = Bytes.copy (src : bytes)
let dst2 : bytes = Bytes.copy (src : string)
(* fails to compile with -safe-string *)</lang>
<br/>
After 4.06, immutable strings became the default, <code>Bytes</code> still exists, but its type is now distinct. The only way to get mutable strings and type synonymy back is at configure-time on the compiler itself.<br/>
<code>String.copy</code> issues a deprecation warning, and a (shallow) copy would simply be an assignment by default:
<lang ocaml>let dst = src</lang>
To get a mutable deep-copy still, just convert the string to bytes via <code>Bytes.of_string</code>, which copies for safety, or <code>String.sub/map/init/blit/..</code> for an immutable copy.
<br/>
<br/>
depending on your compiler version, choose the example accordingly.
 
=={{header|Octave}}==
13

edits