Is there a way to `match` on a string that starts with some value?

Viewed 370

For example, consider the following expression:

match string with
| "Foo " ^ rest -> rest
| "Bar " ^ rest -> rest
| _ -> "unmatched"

Unfortunately, this is a syntax error. Is there some way to achieve this behavior?

2 Answers

There are some explanations in OCaml function parameter pattern matching for strings on why it's not possible to deconstruct strings in pattern-matching. You can only match on plain strings.

Instead, you could use the new String.starts_with (OCaml 4.13) to compare the string with a fixed prefix, or use the Str module that provides regular expressions, or convert the string to a list and match on that list.

Another possibility is to split the string going into your match, so that you can match based on a tuple of plain old strings.

String.(
  match sub s 0 4, sub s 4 (length s - 4) with 
  | "foo ", rest -> ...
  | "bar ", rest -> ...
  | _ -> ...
)

If you create a function to partition a string on a certain number of characters, this becomes nicer to look at.

let part s n =
  String.(sub s 0 n, sub s n (length s - n))

Now:

match part s 4 with 
| "foo ", rest -> ...
| "bar ", rest -> ...
| _ -> ...
Related