简体   繁体   English

OCaml中的递归:与Concat反向

[英]Recursion in OCaml: Reverse with Concat

I have a question regarding the execution flow in recursive functions in OCaml. 我有一个关于OCaml中递归函数的执行流程的问题。 This is scenario: 这是场景:

I have two recursive functions, Concat and Reverse . 我有两个递归函数, ConcatReverse Reverse calls Concat. 反向调用Concat。 Would anyone be able to explain what happens when I, for example, submits the list [1; 任何人都能够解释当我提交列表时会发生什么[1; 2; 2; 3]? 3]?

let rec concat (l1,l2) =
match l1 with
[] -> l2
| (h::t) -> h::(concat (t,l2));;

let rec reverse (l: int list) =
match l with
[] -> []
| (h :: t) -> concat (reverse t, [h]);;

// Call
let list1 = [1; 2; 3] ;;
reverse list1 ;;

I know this is not the optimal way to reverse a list, but right now I only interested in how two recursive functions work with each other. 我知道这不是反转列表的最佳方法,但是现在我只对两个递归函数如何相互作用感兴趣。

Thanks! 谢谢!

If you annotate concat as taking two lists of ints: 如果您将concat注释为包含两个整数列表:

let rec concat (l1, l2 : int list * int list) =
. . .

You can ask the toplevel (OCaml REPL) to trace the function calls and return values. 您可以要求toplevel(OCaml REPL)跟踪函数调用和返回值。 This might tell you exactly what you want to know. 这可能会告诉您确切的内容。

$ rlwrap ocaml
        OCaml version 4.06.1
. . .
# trace concat;;
concat is now traced.
# trace reverse;;
reverse is now traced.

# reverse [1; 2; 3];;
reverse <-- [1; 2; 3]
reverse <-- [2; 3]
reverse <-- [3]
reverse <-- []
reverse --> []
concat <-- ([], [3])
concat --> [3]
reverse --> [3]
concat <-- ([3], [2])
concat <-- ([], [2])
concat --> [2]
concat --> [3; 2]
reverse --> [3; 2]
concat <-- ([3; 2], [1])
concat <-- ([2], [1])
concat <-- ([], [1])
concat --> [1]
concat --> [2; 1]
concat --> [3; 2; 1]
reverse --> [3; 2; 1]
- : int list = [3; 2; 1]

Functions, recursive or not, are evaluated by first evaluating all it's arguments in an unspecified order and then calling the function with them. 函数,递归与否,通过首先以未指定的顺序评估所有参数然后用它们调用函数来评估。

So for example concat (reverse t, [h]) will first evaluate reverse and then call concat. 因此,例如concat (reverse t, [h])将首先评估反向,然后调用concat。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM