【问题标题】:F# list folders and filesF# 列出文件夹和文件
【发布时间】:2018-12-10 01:13:32
【问题描述】:

我必须编写一个名为“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)

【问题讨论】:

  • 你的例子不是很清楚。你能试着用不同的方式解释吗?
  • 为什么您发布的功能不起作用?它给出了哪些不正确的结果?在您的示例中,hallodocumente 对象的结构是什么?

标签: list file f# directory names


【解决方案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 []

【讨论】:

  • 嘿,你的回答似乎是正确的。这里唯一的问题是我忘了提到我可以使用的唯一内置函数是 List.fold、List.filter、List.map、List.exists。我不认为我需要它们,但我不确定。函数应该保持不变我不能改变它:让rec find (name: string) (root: Node): string list list =
猜你喜欢
  • 2020-10-10
  • 2016-05-06
  • 1970-01-01
  • 2018-08-06
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多