【问题标题】:What's wrong with this F# code?这个 F# 代码有什么问题?
【发布时间】:2009-11-21 22:19:02
【问题描述】:

我想使用有区别的联合来表示文件和目录。 然后给定一个目录,我想列出其中的所有文件(递归)。

但是在List.iter makeFileList行内

我明白了:

类型不匹配。期待一个 FileOrDir -> 单元,但给定一个 FileOrDir -> 字符串列表。 “单位”类型不 匹配类型“字符串列表”

type FileOrDir = 
| File of string
| Directory of string * FileOrDir list

let example = Directory("Directory1",[File("file1.txt"); File("file2.txt"); Directory("EmptyDir",[])])

let rec makeFileList fad =
    [     
    match fad with 
    | File(name) -> yield name
    | Directory(name,listOfFiles) 
        ->  listOfFiles |> List.iter  makeFileList                          
    ]            

我将不胜感激解释和解决方案。

【问题讨论】:

    标签: f#


    【解决方案1】:

    List.iter 接受一个没有返回值的函数 ('unit') 并运行它以获得它的副作用。

    我认为您想要 List.map,并且想要“屈服!”结果。

    哦,实际上你想要 List.collect,它类似于 map,但连接所有结果(每个结果都是一个列表)。

    请注意,'yield' 会将单个结果生成到一个序列中,而 'yield!'将结果序列生成到序列中。

    编辑:

    代码:

    type FileOrDir = 
    | File of string
    | Directory of string * FileOrDir list
    
    let example = 
        Directory("Directory1",
            [File("file1.txt"); 
             File("file2.txt"); 
             Directory("EmptyDir",[])])
    
    let rec makeFileList fad =
        [     
        match fad with 
        | File(name) -> yield name
        | Directory(name,listOfFiles) 
            ->  yield! listOfFiles |> List.collect makeFileList
        ]            
    
    printfn "%A" (makeFileList example)
    

    【讨论】:

    • Tx,这解释了为什么打印这与此处的列表理解相比没有问题。你能给我提供一个代码示例吗?我才刚刚开始学习。
    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 2014-08-29
    • 2013-06-05
    • 2014-06-04
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多