According to Real World OCaml, the type of "abc"
should be string
. But actually in my utop
REPL, it's of type bytes
.
I've already opened Core.Std
. Why is that?
(The version of OCaml
is 4.02.2
; Core
is 112.24.01
; utop
is 1.18
.)
According to Real World OCaml, the type of "abc"
should be string
. But actually in my utop
REPL, it's of type bytes
.
I've already opened Core.Std
. Why is that?
(The version of OCaml
is 4.02.2
; Core
is 112.24.01
; utop
is 1.18
.)
You must enable safe string mode explicitly. Just start utop with:
$ utop -safe-string
Before the introduction of type bytes
in OCaml 4.02, strings were mutable. Now, strings are intended to be immutable, and bytes
is the type to be used for "mutable strings".
In order not to break too much existing code, this distinction is not yet enabled by default. In default mode, bytes
and string
are synonymous.
There is a slow pace movement in OCaml from mutable string to immutable. A new name for mutable string is bytes
. The immutable will be still called string
. As at the time of writing bytes
and string
are just synonyms, so whenever you see bytes
you may read it as string
. Moreover, if you update you core version to 112.35.00 or later, you will not see this issue with bytes
. String will became string again.
As @ivg said, there is a slow movement in OCaml to make the string
type immutable, and the bytes
type is going to replace the current string
type, since it's always useful to have mutable strings in addition to immutable ones.
As of version 4.02.2, there are separate modules for working with the types string
and bytes
(String
and Bytes
, respectively), but they both just use bytes
by default.
Byte strings may be modified either with Bytes.set
or with the <-
operator, although the latter method will throw a warning. Example:
# let byte_string = "dolphins";;
val byte_string : bytes = "dolphins"
# byte_string.[0] <- 'w';;
Characters 0-15:
Warning 3: deprecated: String.set
Use Bytes.set instead.
Characters 0-15:
Warning 3: deprecated: String.set
Use Bytes.set instead.
- : unit = ()
# byte_string;;
- : bytes = "wolphins"
Of course, more normal behaviour may be achieved by running OCaml with the -safe-string
directive, as @rafix said.
© 2022 - 2024 — McMap. All rights reserved.