管道前進和後退
管道運算子用於以簡單而優雅的方式將引數傳遞給函式。它允許消除中間值並使函式呼叫更容易閱讀。
在 F#中,有兩個管道運算子:
-
前進 (
|>
):從左到右傳遞引數let print message = printf "%s" message // "Hello World" will be passed as a parameter to the print function "Hello World" |> print
-
向後 (
<|
):從右到左傳遞引數let print message = printf "%s" message // "Hello World" will be passed as a parameter to the print function print <| "Hello World"
這是一個沒有管道運算子的示例:
// We want to create a sequence from 0 to 10 then:
// 1 Keep only even numbers
// 2 Multiply them by 2
// 3 Print the number
let mySeq = seq { 0..10 }
let filteredSeq = Seq.filter (fun c -> (c % 2) = 0) mySeq
let mappedSeq = Seq.map ((*) 2) filteredSeq
let finalSeq = Seq.map (sprintf "The value is %i.") mappedSeq
printfn "%A" finalSeq
我們可以縮短前面的示例,並使用正向管道運算子使其更清晰:
// Using forward pipe, we can eliminate intermediate let binding
let finalSeq =
seq { 0..10 }
|> Seq.filter (fun c -> (c % 2) = 0)
|> Seq.map ((*) 2)
|> Seq.map (sprintf "The value is %i.")
printfn "%A" finalSeq
每個函式結果作為引數傳遞給下一個函式。
如果要將多個引數傳遞給管道運算子,則必須為每個附加引數新增|
,並使用引數建立元組。原生 F#管道運算子最多支援三個引數(|||>或<|||)。
let printPerson name age =
printf "My name is %s, I'm %i years old" name age
("Foo", 20) ||> printPerson