All lessons

Working with Text

7 min · OCaml

Join strings, measure them, and print text with print_endline.

OCaml · Working with Text0/5 cleared

Enemy 1 of 5

Joining strings with ^

The ^ operator joins two strings into one new string, in order. This code joins a greeting and a name, then prints the result. Press Run to see it.

Why this works

OCaml uses `^` to join (concatenate) two strings: a dedicated operator, distinct from the numeric `+`, following the same philosophy you saw with `+` vs `+.` for floats: OCaml prefers a separate, unambiguous operator for each type rather than overloading one symbol to mean different things depending on context. `greeting ^ name` builds one new string out of the two, in order.

Because `^` only works on strings, trying to concatenate a string with a number directly (`"Score: " ^ 10`) is a compile error: the number first needs converting to a string with `string_of_int` (covered more in a later lesson). This is the same "no silent conversions" philosophy as the integer/float split: OCaml would rather flag the mismatch than guess.

You
Packet Wolf
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.