开发者

What's wrong with this F# code?

I would like to use a discriminated union to represent a files and directories. Then given a directory I would like to make a list of all files in it (recursively).

But in the line List.iter makeFileList

I get :

Type mismatch. Expecting a FileOrDir -> unit but given a FileOrDir -> string list. The type 'unit' does not match the ty开发者_开发百科pe 'string list'

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                          
    ]            

I would appreciate both the explanation and the solution.


List.iter takes a function with no return value ('unit') and runs it for its side-effects.

I think you want List.map, and you want to "yield!" that result.

Oh, actually you want List.collect, which is like map but concatenates all the results (each of which is a list).

Note that 'yield' will yield a single result into a sequence, whereas 'yield!' yields a sequence of results into the sequence.

EDIT:

The code:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜