[英]Feeding tuple into function such as printfn
我想給printf
函數一個元組:
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
函數會是什么樣子?
你要
let tuple = ("Hello", "world")
printfn "%s %s" <|| tuple
注意雙||
在<||
而不是一個|
在<|
見: <||
你也可以這樣做
let tuple = ("Hello", "world")
tuple
||> printfn "%s %s"
還有其他類似的運算符,例如|>
、 ||>
、 |||>
、 <|
, <||
, 和<|||
.
使用fst
和snd
慣用方法是
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.