let _ as s = "abc" in s ^ "def"
So how should understand this?
I guess it is some kind of let pattern = expression thing?
First, what’s the meaning/purpose/logic of let pattern = expression?
Also, in pattern matching, I know there is pattern as identifier usage, in let _ as s = "abc" in s ^ "def", _ is pattern, but behind as, it is an expression s = "abc" in s ^ "def", not an identifier, right?
edit:
finally, how about this: (fun (1 | 2) as i -> i + 1) 2, is this correct?
I know it is wrong, but why? fun pattern -> expression is allowed, right?
I really got lost here.
The expression
let pattern = expr1 in expr2is pretty central to OCaml. If the pattern is just a name, it lets you name an expression. This is like a local variable in other language. If the pattern is more complicated, it lets you destructureexpr1, i.e., it lets you give names to its components.In your expression, behind
asis just an identifier:s. I suspect your confusion all comes down to this one thing. The expression can be parenthesized as:as Andreas Rossberg shows.
Your final example is correct if you add some parentheses. The compiler/toplevel rightly complains that your function is partial; i.e., it doesn’t know what to do with most ints,
only with 1 and 2.
Edit: here’s a session that shows how to add the parentheses to your final example:
Edit 2: here’s a session that shows how to remove the warning by specifying an exhaustive set of patterns.