4 ms·
I've never seen OCaml code before. Can someone explain this part of the code? (* sorry, can't resist some pattern matching. sweet sickly arcane sugar. *)
by mshafrir 17y ago
I've never seen OCaml code before. Can someone explain this part of the code?
(* sorry, can't resist some pattern matching. sweet sickly arcane sugar. *)
let _ =
match Sys.argv with
[| _; q |] -> display (search q)
| _ -> failwith "Usage: twittersearch \"search terms\""
- mrkurt 17y agoI don't know if you're familiar with pattern matching in general, but you can think of it as a switch-on-crack. The jist of that code is: we're going to look at Sys.argv, which is a list. If it's a two element list, ignore the first element (underscore as "hole") and pass the second element to search, then display the result. If it's anything else, fail with a nice message.
- mrkurt 17y agoOh, silentbicycle is right. [| ... |] is array syntax, rather than a list.
- silentbicycle 17y ago_ as a variable name means, "(match anything here, doesn't matter)". It's similar to . in a regular expression -- you're testing a list of multiple values, and while for your purposes you only care about a specific one of them, you need to verify that it has the right number of values. Much like "..e" will match any three-letter word ending in e, (_, 21, _) will match any three-value list whose second value is 21. ( (_, x, _) will match a three-value list parametrically, and extract the variable x for further use.) That's probably a somewhat confusing explanation, but in practice, idiomatic code using deconstructive pattern matching is usually quite a bit clearer than the alternative, several layers of nested switch statements. It's also incredibly useful. Haskell has the same feature. (I'm pretty sure Erlang does, too.) For one good example of this making complex code relatively simple, check out Chris Okasaki's thesis (Purely Functional Data Structures, http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf), page 79, or the red-black tree balanced-insertion code in the book. (Note: That's SML, which is a different dialect of ML.) In this case: switch on sys.argv (command line args) -- if it's a two-variable array, then ignore the first parameter, put the second in a variable called 'q', and then display the result of executing search(q). Otherwise, raise an exception with that error message.
- deleted 17y ago[deleted]