与int和bool匹配的ocaml模式

Dag*_*ong 1 ocaml pattern-matching

let disting v =
  match v with
  | int -> (*expression1*)
  | bool -> (*expression2*)
  | _ -> (*expression3*)
Run Code Online (Sandbox Code Playgroud)

每当我运行代码,disting true并且disting false结果是expression1.使用此代码,结果反之亦然

let disting v =
  match v with
  | bool -> (*expression2*)
  | int -> (*expression1*)    
  | _ -> (*expression3*)
Run Code Online (Sandbox Code Playgroud)

这一个也有类似的问题.我怎样才能得到我想要的结果?

ghi*_*esZ 5

模式匹配不像你想象的那样工作.

它允许您将表达式与值或模式匹配,如下所示:

match some_int with
| 1  -> 1 
| 10 -> 2
| x  -> x/2   (* this matches any possible int, and it gives it the name 'x' for the rest *)
Run Code Online (Sandbox Code Playgroud)

所以在这里你将始终匹配你的第一个案例,因为它不会过滤任何东西.你所说的是:将v与任何东西相匹配,让我们称之为"bool".

然后你可以尝试类似的东西

let disting v =
  match v with
  | true -> (*expression2*)
  | 2 -> (*expression1*)    
  | _ -> (*expression3*)
Run Code Online (Sandbox Code Playgroud)

在OCaml中没有进行类型检查,因为'v'既可以是int也可以是bool但不能同时使用.我不知道你想要做什么,但你应该阅读一些关于语言的基础.