首页 文章

F#列出文件夹和文件

提问于
浏览
1

我必须编写一个名为“find”的函数,我可以在其中输入Name作为输入 . 该函数必须使用给定的Name搜索文件或文件夹,并且必须返回列表中的文件或文件夹 .

这里有一个它应该是什么样子的例子:

find "Hallo" hallo = []
find "Hallo.txt" hallo = [["Hallo.txt"]]
find "Hallo.txt" dokumente = [["Dokumente"; "Hallo.txt"]]
find "Hallo.txt" (Folder ("Test", [hallo; dokumente ])) =
[["Test"; "Hallo.txt"]; ["Test"; "Dokumente"; "Hallo.txt"]]

这就是我到现在为止所尝试的:

type Node =
    | File   of string * Nat          
    | Folder of string * (Node list)

let rec find (name: string) (root: Node): string list list =
        match root with
        | File (N,G)  ->if N=name then [[N]] else find(name)(root)
        | Folder(N,G) ->if N=name then [[N]] else find(name)(root)

1 回答

  • -1
    let find name root =
        let rec loop name node acc =
            [ match node with
              | File (n) -> if n = name then yield List.rev (n::acc)
              | Folder (n, l) -> for x in l do yield! loop name x (n::acc) ]
        loop name root []
    

相关问题