Reputation: 1028
say i have the following type definition:
type e = AES | DES | SALSA20
Then, i have a function which has an argument of type string, this argument could be "AES", "DES", "SALSA20", or something else. How could I first turn this string into a type and then match this type with possible types? Or, is it necessary because one may argue you can just match a string directly as the following?
match str with
| "AES" -> do something...
| "DES" -> do something else...
If possible, can I also get a basic intro to how pattern-matching works on string? I feel direct string matching will be much slower...
Upvotes: 0
Views: 1943
Reputation: 66818
You can write a function like this:
let e_of_string = function
| "AES" -> AES
| "DES" -> DES
| "SALSA20" -> SALSA20
| _ -> raise (Invalid_argument "e_of_string")
I examined the native code generated by OCaml 4.01.0; it compares the supplied string against each of the given strings in order. If there are a lot of strings to check, this is, as you say, pretty slow.
To get more powerful string matching, you could use regular expressions from the Str
module, or you could use ocamllex.
Upvotes: 2
Reputation: 9377
You can do it either way. If you are going to perform multiple matches then mapping the string to a data type first makes a lot of sense. For just a single match, I would pick whichever leads to the most straightforward code (or the most consistent, if this is something that is done elsewhere in your code base).
Mapping to a type might look something like:
type thing = AES | DES | SALSA20
let thing_of_string = function
| "AES" -> AES
| "DES" -> DES
| "SALSA20" -> SALSA20
| _ -> failwith "not a thing"
String matching was improved recently and should be acceptably efficient for what it is. I would still avoid performing the same string match many times.
Upvotes: 1