Why is my string of type `bytes`?
Asked Answered
K

3

12

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.)

Kalimantan answered 19/7, 2015 at 11:13 Comment(0)
P
14

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.

Pisces answered 19/7, 2015 at 11:21 Comment(3)
You post sounds like one really needs to enable this mode. That's not true. Everything other this recommendation is written well. Consider removing this misleading recommendation.Bork
I think that @Bork is right in the sense that your first sentence is awkwardly worded, I would have written it as "in order to achieve this behaviour, string mode must be explicitly enabled"Cowherd
should this be updated today? Is it enabled by default now?Agrigento
B
11

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.

Bork answered 19/7, 2015 at 15:56 Comment(0)
C
8

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.

Cowherd answered 19/7, 2015 at 22:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.