ocaml

OCaml function parameter pattern matching for strings


I tried to pass a string in to get a reversed string. Why can't I do this:

let rec reverse x = 
  match x with
  | "" -> ""
  | e ^ s -> (reverse s) ^ e;;

The compiler says it's a syntax error. Can't I use ^ to destructure parameters?


Solution

  • The reason for this is that strings are not represented as a datatype in the same way as lists are. Therefore, while cons (::) is a constructor, ^ is not. Instead, strings are represented as a lower level type without a recursive definition (as lists are). 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. Here's an example implementation of them.