因此,据我所知,char选项可以是None或任何字符,例如'a'.
如何将char选项与常规char进行比较.
let first = Some 'a';;
let second = 'a';;
let third= 'b';;
Run Code Online (Sandbox Code Playgroud)
我如何比较第一个和第二个,所以它返回true,第一个和第三个,所以它返回false.
在这种情况下,您可以执行以下三种操作之一,具体取决于您的使用方式
let first = Some 'a'
let second = 'a'
let third = 'b'
Run Code Online (Sandbox Code Playgroud)
首先,您可以将非选项变量转换为选项,然后通过执行以下操作来测试(结构)相等:
if first = Some second then begin
Printf.printf "First and Second are equal!"
end
Run Code Online (Sandbox Code Playgroud)
其次,您可以使用匹配语句.这是"解包"选项的更标准方法:
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."
Run Code Online (Sandbox Code Playgroud)
此外,您可以将匹配包装在函数中,就像@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!!"
Run Code Online (Sandbox Code Playgroud)
如果您使用BatOption.get
,则需要将其包装在一个中,try/with
因为如果first
是None
,则会引发No_value
异常.
但总的来说,这match
是最标准的方法.正如@ivg所指出的,使用匹配比构造Option对象和运行比较要快一些(特别是在限制类型和生成函数时).如果速度不是一个很大的问题,那么要么是好的.这取决于你和最可读的东西.
此外,作为一个无关的旁注/建议:不要使用双分号main
,例如,
let main () = begin
...
end ;;
main () ;;
Run Code Online (Sandbox Code Playgroud)
你只需要那两个双分号.这种做法可以让你忘记所有奇怪的双分号规则,让你的程序"正常工作".
归档时间: |
|
查看次数: |
2339 次 |
最近记录: |