Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you append a char to a string in OCaml?

Tags:

string

char

ocaml

It seems as if there is no function in the standard library of type char -> string -> string, which insert a char in front of (or at the end of) a string. There are workarounds, e.g. by using String.make or String.blit. Is there an elegant way to do this?

like image 910
SoftTimur Avatar asked Nov 30 '11 13:11

SoftTimur


People also ask

Can you append a char to a string?

Use the strncat() function to append the character ch at the end of str.

How do I append to a string in OCaml?

The (^) operator concatenates two strings, e.g., # "hello" ^ ", " ^ "world!";; - : string = "hello, world!"

How do I match a string in OCaml?

There is a way to match strings as a list of characters, using a function from SML (which you can write in OCaml) called 'explode' and 'implode' which --respectively -- take a string to a char list and vice versa.

How do you capitalize a string in OCaml?

uppercase_ascii s is s with all lowercase letters translated to uppercase, using the US-ASCII character set. lowercase_ascii s is s with all uppercase letters translated to lowercase, using the US-ASCII character set.


2 Answers

The code from @pad is what I would use, because I like to treat strings as immutable if possible. But I wouldn't use Char.escaped; it's specialized for when you want the OCaml lexical representation of a character. So here's what you get if you make that change:

let prefix_char s c = String.make 1 c ^ s

let suffix_char s c = s ^ String.make 1 c

Update

In the years since this question was asked, OCaml has changed so that strings are immutable. Excellent.

like image 95
Jeffrey Scofield Avatar answered Sep 30 '22 13:09

Jeffrey Scofield


String.make and String.blit is a good way to do so, but they seem to be imperative. Personally I prefer to make infix functions using Char.escaped and string concatenation:

let (^$) c s = s ^ Char.escaped c (* append *)
let ($^) c s = Char.escaped c ^ s (* prepend *)
like image 34
pad Avatar answered Sep 30 '22 15:09

pad