首页 > 解决方案 > F# 列出文件夹和文件

问题描述

我必须编写一个名为“find”的函数,我可以在其中给出一个名称作为输入。该函数必须搜索具有给定名称的文件或文件夹,并且必须在列表中返回它们。

在这里,您有一个应该是什么样子的示例:

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)

标签: listfilef#directorynames

解决方案


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 []

推荐阅读