Recursion 如何改进这个递归函数?

Recursion 如何改进这个递归函数?,recursion,pattern-matching,ocaml,Recursion,Pattern Matching,Ocaml,walkTree中的代码遍历fileTree节点列表中表示的文件树。它实现了我想要的功能,即递归地打印树中的每个条目。但我觉得可以大大改进。我还认为我在Patrn匹配的末尾运行2`visit语句是在破坏尾部递归 type 'a fileTree = | File of 'a | Folder of 'a * ('a fileTree list) let fileTreeStructure = [ File "file1.txt" ; Folder ("testFolder1",

walkTree
中的代码遍历
fileTree
节点列表中表示的文件树。它实现了我想要的功能,即递归地打印树中的每个条目。但我觉得可以大大改进。我还认为我在Patrn匹配的末尾运行2`visit语句是在破坏尾部递归

type 'a fileTree =
  | File of 'a
  | Folder of 'a * ('a fileTree list)

let fileTreeStructure = [
  File "file1.txt" ;
  Folder ("testFolder1", [Folder ("nestedFolder1", [])]) ;
  File "test1.txt";
  Folder ("testFolder2", [Folder ("nestedFolder2", [])]) ;
  File "test2.txt";
]

let walkTree tree =
  let rec visit = function
    | [] -> print_string "\n"
    | File f :: t ->
      Printf.printf "file: %s\n" f ;
      visit t
    | Folder (name, contents) :: t ->
      Printf.printf "name: %s\n" name ;
      visit contents ;
      visit t in
  visit tree;;

walkTree fileTreeStructure

有什么更好的方法可以做到这一点呢?

至少,我要将
列表
文件树
匹配分开:

let walkTree tree =
  let rec visit = function
    | File f -> Printf.printf "file: %s\n" f
    | Folder (name, contents) ->
        Printf.printf "name: %s\n" name;
        List.iter visit contents
  in visit tree

let _ = List.iter walkTree fileTreeStructure
编辑(使用@nlucaroni建议;我还替换了
List.iter
函数进行说明):

如果希望
walkTree
函数按字面意思接受
string fileTree列表
(而不是第一个示例中的
string fileTree
):


您可以使用文件夹分支上的相互递归调用列表上的outer List.iter(一旦命名)。
let walkTree tree =
  let rec iter = function
    | [] -> ()
    | a::l -> visit a; iter l
  and visit = function
    | File f -> Printf.printf "file: %s\n" f
    | Folder (name, contents) ->
        Printf.printf "name: %s\n" name;
        iter contents
  in iter tree