James Franco
James Franco

Reputation: 4716

Could anyone explain this OCAML syntax to me

I am trying to append a string to an existing string. I came across this thread here which explains it. Just for reference I am pasting the content here from that page

let (^$) c s = s ^ Char.escaped c (* append *)
let ($^) c s = Char.escaped c ^ s (* prepend *)

Now I wanted to know what does (^$) mean in

  let (^$) c s = s ^ Char.escaped c (* append *)

This page here states that

operator ^    is for string concatenation

what is (^$) ?

Upvotes: 1

Views: 104

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

@icktoofay is correct, this code:

let (^$) c s = s ^ Char.escaped c

is defining a new operator ^$.

You can use an operator as an ordinary (prefix) function name by enclosing it in parentheses. And, indeed, this is what you do when you define an operator.

$ ocaml
    OCaml version 4.02.1

# (+) 44 22;;
- : int = 66
# let (++++) x y = x * 100 + y;;
val ( ++++ ) : int -> int -> int = <fun>
# 3 ++++ 5;;
- : int = 305

Infix operators in OCaml start with one of the operator-like characters =<>@^|&+-*/$%, then can have any number of further operator-like characters !$%&*+-./:<=>?@^|~. So you can have an infix operator $^ or $^??@+ and so on.

See Section 6.1 of the OCaml manual.

Upvotes: 3

camlspotter
camlspotter

Reputation: 9040

It is to append the given character to the string with escaping:

'x' ^$ "hello" ----> "hellox"
'\n' ^$ "hello"  ----> "hello\\n"

Upvotes: 1

Related Questions