F#-嵌套管道

F#-嵌套管道,f#,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

我现在正在读《真实世界函数式编程》一书,想知道我怎样才能写出这样的东西:

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")
我发布的代码将在第一个List.iter()之后失败,并显示一条消息:

类型不匹配。期待一个单位-> 'a但给定了'b列表->'b 列出“unit”未列出的类型 匹配类型“a列表”


我怎样才能做上面这样的事情(就在它工作的地方)?

您可以使用
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

您可以使用
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

假设isOdd(n)是布尔型的,其他声明是整数。为什么它会喜欢它?@Carnotaurus-我想首先将列表中的所有整数映射到方法
square
-然后它应该再次获取数字列表并获得所有奇数..假设isOdd(n)是布尔值,其他声明是整数。为什么它会喜欢它?@Carnotaurus-我想首先将列表中的所有整数映射到方法
square
-然后它应该再次获取数字列表并获得所有奇数。通过使用一个方法扩展列表模块,您的第一个选项可以变得更漂亮,我将其称为“do”。那么就不需要记住返回值了。'List.map square |>List.do(printfn“%d”)'。您只是在用
|>fun xs->
模拟
let xs=in
,这在提供
let
关键字:-)的语言中不是一个好主意(这在纯lambda演算中是一个很好的技巧)。通过使用一个方法扩展列表模块,您的第一个选项可以变得更漂亮,我称之为“do”。那么就不需要记住返回值了。'List.map square |>List.do(printfn“%d”)'。您只是在用
|>有趣的xs->
模拟
let xs=in
,这在提供
let
关键字:-)的语言中不是一个好主意(但在纯lambda演算中这是一个很好的技巧)