2013-12-13 28 views
9

我想給一個元組作爲printf功能:餵食元組到功能等printfn

let tuple = ("Hello", "world") 
do printfn "%s %s" tuple 

這當然不行,編譯器首先說,它需要string,而不是string*string。我把它寫成如下:

let tuple = ("Hello", "world") 
do printfn "%s %s" <| fst tuple 

然後編譯合理注意到,現在我有string -> unit類型的函數值。說得通。我可以寫

let tuple = ("Hello", "world") 
do printfn "%s %s" <| fst tuple <| snd tuple 

它適用於我。但我想知道,如果有可能是沒有辦法做到這一點更好,就像

let tuple = ("Hello", "world") 
do printfn "%s %s" <| magic tuple 

我的問題是,我不能讓這類型不printf的需要,因此印製兩個參數。 magic功能可能是什麼樣子?

回答

19

你想

let tuple = ("Hello", "world") 
printfn "%s %s" <|| tuple 

注意在<||||而不是一個單一|<|

參見:MSDN <||

你也可以做

let tuple = ("Hello", "world") 
tuple 
||> printfn "%s %s" 

還有其他類似的operators,例如|>,||>, |||>,<|, <||<|||

一個慣用的方式使用fstsnd做是

let tuple = ("Hello", "world") 
printfn "%s %s" (fst tuple) (snd tuple) 

你通常不會看到傳遞給函數的一個元組的一個||>或<原因||運營商是因爲所謂的解構

一個析構表達式採用一個複合類型並將其解構爲多個部分。

因此,對於tuple ("Hello", "world"),我們可以創建一個析構函數,將元組分解爲兩部分。

let (a,b) = tuple 

我知道這可能看起來像一個元組構造以人新的F#,或者是因爲我們有被綁定到兩個值可能看起來更奇怪,(注意我說的約束,未分配),但它需要的具有兩個值的元組並將其解構爲兩個單獨的值。

所以在這裏我們使用解構表達式來做到這一點。

let tuple = ("Hello", "world") 
let (a,b) = tuple 
printfn "%s %s" a b 

或更常見

let (a,b) = ("Hello", "world") 
printfn "%s %s" a b 
+0

哇!感謝你,我現在明白了!我的'magic'應該看起來像 – Rustam

+0

'let magic op tuple = op <| fst元組<| snd元組' – Rustam

+0

和印刷會像'magic(printfn「%s%s」)元組' – Rustam