OCaml:模式匹配与If / else语句 [英] OCaml: Pattern matching vs If/else statements

查看:152
本文介绍了OCaml:模式匹配与If / else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我对OCaml完全陌生,并且在实现我的第一个功能方面进展缓慢。有一点我很难理解的是何时使用模式匹配功能,比如

  let foo = 
[] - >真
| _ - >假;;

vs使用if else结构,比如

  let foo a = 
if a = [] then true else false ;;

何时使用每个?

解决方案

我不认为这个问题有明确的答案。首先,模式匹配的明显例子是当你需要破坏时,例如:

  let rec sum = function 
| [] - > 0
| head :: tail - >头+尾巴;;

另一个明显的例子是当你定义一个递归函数时,模式匹配使边缘条件更清晰,例如:

  let rec factorial = function 
| 0 - > 1
| n - > n * factorial(n - 1);;

而不是:

  let rec factorial = function n  - >> 
如果n = 0,则
1
else
n * factorial(n-1);;

这可能不是一个很好的例子,只是用你的想象力找出更复杂的边缘条件! ; - )



就常规(比如C语言)而言,我可以说你应该使用模式匹配而不是 switch / case if 来代替三元运算符。对于其他所有情况,这是一种灰色区域,但在ML系列语言中通常首选模式匹配。


So, I'm totally new to OCaml and am moving pretty slowly in getting my first functions implemented. One thing I'm having trouble understanding is when to use pattern matching abilities like

let foo = 
[] -> true
| _  -> false;;

vs using the if else structure like

let foo a = 
if a = [] then true else false;;

When should I use each?

解决方案

I don't think there's a clear cut answer to that question. First, the obvious case of pattern matching is when you need destructing, e.g.:

let rec sum = function
    | [] -> 0
    | head :: tail -> head + sum tail;;

Another obvious case is when you're defining a recursive function, pattern matching make the edge condition clearer, e.g.:

let rec factorial = function
    | 0 -> 1
    | n -> n * factorial(n - 1);;

instead of:

let rec factorial = function n -> 
  if n = 0 then 
    1 
  else
    n * factorial(n-1);;

That might not be a great example, just use your imagination to figure out more complex edge conditions! ;-)

In term of regular (say C like) languages, I could say that you should use pattern matching instead of switch/case and if in place of the ternary operator. For everything else it's kind of a grey zone but pattern matching is usually preferred in the ML family of languages.

这篇关于OCaml:模式匹配与If / else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆