假设我们想要更小的值。它将转到Node (insert x left, k, right)
当函数insert被声明为只接受一个参数时,我不明白我们如何能够insert x left
。怎么还可以传递插入功能?
type 'a bst_t =
| Leaf
| Node of 'a bst_t * 'a * 'a bst_t
let rec insert x = function
| Leaf -> Node (Leaf, x, Leaf)
| Node (left, k, right) ->
if x < k then Node (insert x left, k, right)
else Node (left, k, insert x right)
答案 0 :(得分:1)
Ocaml有一个REPL,即一个对实验和与ocaml 进行对话的交互式环境。
$ ocaml
OCaml version 4.02.3
# type 'a bst_t =
| Leaf
| Node of 'a bst_t * 'a * 'a bst_t ;;
type 'a bst_t = Leaf | Node of 'a bst_t * 'a * 'a bst_t
# let rec insert x = function
| Leaf -> Node (Leaf, x, Leaf)
| Node (left, k, right) ->
if x < k then Node (insert x left, k, right)
else Node (left, k, insert x right) ;;
val insert : 'a -> 'a bst_t -> 'a bst_t = <fun>
read-eval-print-loop不仅显示已计算表达式的值,还显示其类型。在这里,您可以看到符号insert
绑定到一个函数,该函数的值为&#34;某些类型为'a
&#34;并返回另一个函数,该函数取值为#34;该类型的二叉树'a
&#34;并返回'a
类型的同一二叉树的值。
我强烈建议您随时使用REPL,因为它们会告诉您很多关于系统的信息。
答案 1 :(得分:0)
function
关键字将函数定义为一系列模式,并且几乎总是在不给参数赋予名称的情况下使用它。所以insert
函数实际上有两个参数。
没有function
的定义是等效的:
let rec insert x node =
match node with
| Leaf -> Node (Leaf, x, Leaf)
| Node (left, k, right) ->
if x < k then Node (insert x left, k, right)
else Node (left, k, insert x right)
答案 2 :(得分:0)
虽然初看起来似乎如此,但是函数function getValueByKey(array $a, $key)
{
$keyList = explode('.', $key);
$returnValue = $a;
do {
$currentKey = array_shift($keyList);
// Found the value
if ($currentKey === null) {
break;
}
// No more depth to traverse or no such key
if (!is_array($returnValue) || !array_key_exists($currentKey, $returnValue)) {
return null;
}
$returnValue = $returnValue[$currentKey];
} while (true);
return $returnValue;
}
var_dump(getValueByKey($a, $key)); // outputs: int(16418)
只有两个参数 - 一个是你所说的插入键,第二个是要插入的bst_t键。
在OCaml中,强烈建议使用Point-free programming的概念,因为它可以应用它,而这正是插入函数所发生的情况。您的函数版本只是以下函数的简写符号(用正常,详细的语法编写):
insert
其中bst是执行插入的树,即函数与let rec insert x bst = match bst with
| Leaf -> Node (Leaf, x, Leaf)
| Node (left, k, right) ->
if x < k then Node (insert x left, k, right)
else Node (left, k, insert x right)
模式匹配的树。