开发者

F# - nested pipelines

I'm at the moment reading the book 开发者_开发技巧"Real world functional programming", and wondering how I can write something like:

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

The code I've posted will fail after the First List.iter() with a message that says:

Type mismatch. Expecting a unit -> 'a but given a 'b list -> 'b list The type 'unit' does not match the type ''a list'

How can I do something like above (just where it will work)?


You could use List.map instead of List.iter, and return the elements unchanged. You would be rebuilding the list:

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)

Another way would be, to instead of storing each element separatly, is to store the whole list as a function parameter:

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)

One last variant I can think of, is to completely branch the pipeline:

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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜