如何将 char 选项与 char 进行比较

How to compare char option with char

据我所知,字符选项可以是 None 或任何字符,例如 'a'.

如何将字符选项与常规字符进行比较。

let first = Some 'a';;
let second = 'a';;
let third= 'b';;

我如何比较第一个和第二个所以 returns 正确,第一个和第三个所以 returns 错误。

在这种情况下,您可以执行以下三项操作之一,具体取决于您的使用方式

let first = Some 'a'
let second = 'a'
let third = 'b'

首先,您可以将非选项变量转换为选项,然后通过执行以下操作测试(结构)相等性:

if first = Some second then begin
  Printf.printf "First and Second are equal!"
end

其次,您可以使用匹配语句。这是 "unwrap" 选项的更标准方法:

match first with
| Some c -> 
  if c = second then print_endline "First and second are equal"; 
  if c = third then print_endline "First and third are equal."
| None -> print_endline "None."

此外,您可以像@ivg 在他的示例中所做的那样将匹配包装在一个函数中。

最后,您可以使用 BatOption.get:

try
  if BatOption.get first = second then print_endline "First and second are equal";
  if BatOption.get first = third then print_endline "First and third are equal";
with
  No_value -> print_endline "ERROR: No value!!"

如果您使用 BatOption.get,您需要将其包装在 try/with 中,因为如果 firstNone,它将引发 No_value 例外。

不过,一般来说,match 是最标准的方法。正如@ivg 指出的那样,使用匹配比构造 Option 对象和 运行 比较要快一些(尤其是在限制类型和生成函数时)。如果速度不是一个大问题,那么两者都可以。这取决于您以及看起来最易读的内容。

此外,作为一个不相关的方面note/suggestion:除了main之后不要使用双分号,例如

let main () = begin
...
end ;;
main () ;;

你只需要那两个双分号。这种做法可以让您忘记所有奇怪的双分号规则,让您的程序 "just work".

我建议您使用最清晰的解决方案:

first = Some second

虽然,可以说这不是一种非常有效的方法,因为它执行了额外的分配。但是你不应该为此烦恼,除非它在一个非常紧密的循环中使用。如果它是一个紧密的循环,并且你真的用跟踪器精确定位,你需要优化它,那么你可以使用

let option_contains opt (x : char) = match opt with
  | None -> false
  | Some y -> x = y

注意,这个函数被特别限制为只接受char类型的值,这使得它非常快。但同样,这只是优化中的一个游戏。一般来说,只需坚持使用最易读的解决方案,即 first = Some second.