Ben
Ben

Reputation: 3922

Why is my string of type `bytes`?

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

Upvotes: 12

Views: 4833

Answers (3)

chrismamo1
chrismamo1

Reputation: 977

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.

Upvotes: 8

ivg
ivg

Reputation: 35210

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.

Upvotes: 11

rafix
rafix

Reputation: 1749

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.

Upvotes: 14

Related Questions