OCaml pattern reconstruction with let
So I've noticed it is possible to reconstruct any patterns with "let" expressions, even when it's a function declaration.
It can be pretty useful in cases like:
let [c; f; x] = map (fun _ -> scanf " %f" id) (1--3) in ...
However, this emits a warning because the pattern isn't exhaustive: indeed, it could fail. But in my case, that is exactly the intended behavior when the pattern doesn't match (and my assertion about the input is wrong): the statement should fail (and the failure could possibly be caught at some point up the stack).
I don't like having those warnings (and I don't want to globally turn them off!) so I'm forced to fall back on the very cumbersome (and no safer):
let c, f, x = match (map (fun _ -> scanf " %f" id) (1--3)) with
| [c; f; x] -> c, f, x
| _ -> failwith "wrong assertion"
in ...
Isn't there a way to get the succinct syntax of the first alternative without the scary warnings? Or another construct that would involve less typing than a full-blown match statement?
Note: I think it would also be nice to be able to specify a function only takes a given alternative of a sum type without emitting a warning at the declaration site. It would be for the caller to ensure he uses the right argument, or he would get a warning...
type ast = Id of string | Var of string * int
let foo (Var(s,n)) = ...
foo (Var("bar", 42)) (* ok *)
foo (Id "bar") (* warning; or even error *)
(This is because to me having a signature like "foo sn" doesn't make it clear foo is intended to be used with the data of a Var-constructed ast.)
你可以使用不同的类型:
type ast = [`Id of string | `Var of string * int]
let foo (`Var (s, n)) = (s, n)
(* val foo : [< `Var of 'a * 'b ] -> 'a * 'b *)
foo (`Var("bar", 42)) (* : string * int = ("bar", 42) *)
foo (`Id "bar") (* Error: This expression has type [> `Id of string ] *)
链接地址: http://www.djcxy.com/p/62638.html
下一篇: 让OCaml模式重建