Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string to integer in Ocaml

I would like a working version of this:

let x = "a" ^ 0;;
like image 509
polerto Avatar asked Feb 17 '13 00:02

polerto


People also ask

How do I concatenate strings in Ocaml?

The (^) binary operator concatenates two strings.

How do I concatenate strings in Mongodb?

Concatenates strings and returns the concatenated string. $concat has the following syntax: { $concat: [ <expression1>, <expression2>, ... ] } The arguments can be any valid expression as long as they resolve to strings.


2 Answers

As you undoubtedly noticed, you can only concatenate strings with other strings - not integers. So you'll have to convert your integer to a string before you can concatenate it. If the integer is really hard coded like in your example, you can just write "0" instead of 0 (in fact in your example you can just write "a0" and not concatenate anything at all).

If the integer is not a constant, you can use string_of_int to convert it to a string. So this will work:

let x = "a" ^ string_of_int my_integer
like image 123
sepp2k Avatar answered Oct 29 '22 02:10

sepp2k


You can also use the usual printf functions but it is much slower:

let x = Printf.sprintf "a%d" my_integer
like image 38
Thomas Avatar answered Oct 29 '22 03:10

Thomas