F# - 嵌套管道

时间:2011-03-12 11:03:59

标签: f#

我正在阅读“真实世界函数式编程”一书,并想知道如何编写类似的内容:

let numbers = [ 1 .. 10 ]
let isOdd(n) = (n%2 = 1)
let square(n) = n * n

let myList = 
    numbers 
    |> List.map square 
        |> List.iter(printfn "%d")
    |> List.filter isOdd 
        |> List.iter(printfn "%d")

我发布的代码在First List.iter()之后会失败,并显示一条消息:

  

类型不匹配。期待一个单位 - >   'a但是给出'b列表 - > “b   list“单位”类型没有   匹配类型''列表'

我怎样才能做上面的事情(只是在哪里工作)?

1 个答案:

答案 0 :(得分:3)

您可以使用List.map代替List.iter,并返回不变的元素。您将重建列表:

let myList =
    numbers
    |> List.map square
    |> List.map (fun x -> printfn "%d" x; x)
    |> List.filter isOdd
    |> List.map (fun x -> printfn "%d" x; x)

另一种方法是,不是分别存储每个元素,而是将整个列表存储为函数参数:

let myList =
    numbers
    |> List.map square
    |> (fun xs -> List.iter (printfn "%d") xs; xs)
    |> List.filter isOdd
    |> (fun xs -> List.iter (printfn "%d") xs; xs)

我能想到的最后一个变体是完全分支管道:

let myList =
    numbers
    |> List.map square
    |> fun xs ->
          xs |> List.iter (printfn "%d")
          xs
          |> List.filter isOdd
          |> fun xs ->
                xs |> List.iter (printfn "%d")
                xs