使用F#中的函数声明函数

时间:2019-01-08 05:59:46

标签: ocaml

我试图理解以下代码来声明一个函数:

let string_of_int = function
    | 0 -> "zero"
    | 1 -> "one"
    | 2 -> "two"
    | _ -> "many"

相同
let string_of_int2 x = match x with
    |0 -> "zero"
    |1 -> "one"
    | 2-> "two"
    _ -> "many

我理解声明函数with的第二种方法是尝试将输入x与可能存在的几种可能性进行匹配。但是我不明白第一种方法。函数关键字有什么作用?

另外, 在以下代码中“ a” ..“ z”是做什么的?

let is_capital = function
    | 'a'..'z' -> false
    | 'A'..'Z' -> true
    |_  -> failwith "Not a valid letter"

为什么我不能有这样的功能:

let examplefunc = function
    |"string"-> Printf.printf "a string"
    |3 -> Printf.print "an integer"
    |true-> Printf.printf "a boolean"
    |- -> Printf.printf "whatever"

1 个答案:

答案 0 :(得分:0)

function关键字是fun的变体,它考虑到函数的行为通常直接取决于参数的值。例如,如果我们从阶乘函数的以下定义开始:

 For a positive integer n, n! is 1 if n = 0, and n * (n-1)! otherwise

然后自然翻译为OCaml是

let factorial = function
| 0 (* if n = 0 *) -> 1
| n (* otherwise *) -> n * factorial (n-1)

就像您所说的,这完全等同于

let factorial = fun n -> match n with
| 0 (* if n = 0 *) -> 1
| n (* otherwise *) -> n * factorial (n-1)

但是当在模式匹配中立即解构函数的参数时,直接使用function可能更具可读性。

关于'0'..'9',它们是与所有字符(即,范围的上下限(包括)之间的'0'|'1'|'2'|'3'|'4'|..| '9'(按照字符的ascii顺序)匹配的范围模式

  let is_digit = function '0'..'9' -> true | _ -> false
  is_digit '0' (* returns true *);;
  is_digit 'a' (* returns false *);;
相关问题