将元组输入到诸如printfn之类的函数中 [英] Feeding tuple into function such as printfn
问题描述
我想给一个元组一个printf
函数:
I want to give a tuple to a printf
function:
let tuple = ("Hello", "world")
do printfn "%s %s" tuple
这当然是行不通的,编译器首先说,它需要string
而不是string*string
.我将其编写如下:
This, of course, does not work, compiler first says, that it needs string
instead of string*string
. I write it as follows:
let tuple = ("Hello", "world")
do printfn "%s %s" <| fst tuple
然后编译器合理地指出,现在我具有类型为string -> unit
的函数值.说得通.我会写
Then compiler reasonably notes that now I have function value of type string -> unit
. Makes sense. I can write
let tuple = ("Hello", "world")
do printfn "%s %s" <| fst tuple <| snd tuple
它对我有用.但我想知道,是否有什么办法可以做到更好,例如
And it works for me. But I'm wondering, if there might be any way to do it nicer, like
let tuple = ("Hello", "world")
do printfn "%s %s" <| magic tuple
我的问题是我无法获得printf需要哪种类型来打印两个参数.
magic
函数是什么样的?
My problem is that I can't get which type does printf need so that to print two arguments.
What could magic
function look like?
推荐答案
您要
let tuple = ("Hello", "world")
printfn "%s %s" <|| tuple
请注意<||
中的双||
,而不是<|
Notice the double ||
in <||
and not a single |
in <|
请参阅: MSDN <||
您也可以
let tuple = ("Hello", "world")
tuple
||> printfn "%s %s"
还有其他类似的运算符,例如|>
,||>
,|||>
,<|
,<||
和<|||
.
There are other similar operators such as |>
, ||>
, |||>
, <|
, <||
, and <|||
.
使用fst
和snd
的惯用方式是
let tuple = ("Hello", "world")
printfn "%s %s" (fst tuple) (snd tuple)
通常看不到使用||>或< ||传递给函数的元组的原因运营商的原因是解构.
The reason you don't usually see a tuple passed to a function with one of the ||> or <|| operators is because of what is known as a destructuring.
破坏性表达式采用复合类型并将其分解为多个部分.
A destructing expression takes a compound type and destructs it into parts.
因此对于tuple ("Hello", "world")
,我们可以创建一个析构函数,将元组分为两部分.
So for the tuple ("Hello", "world")
we can create a destructor which breaks the tuple into two parts.
let (a,b) = tuple
我知道对于F#刚接触的人来说,这看起来像一个元组构造函数,或者看起来更奇怪,因为我们绑定了两个值(注意,我说是绑定且未分配),但是它使用具有两个值的元组并将其分解为两个单独的值.
I know this may look like a tuple constructor to someone new to F#, or may look even odder because we have two values being bound to, (noticed I said bound and not assigned), but it takes the tuple with two values and destructured it into two separate values.
所以在这里,我们使用解构表达式来实现它.
So here we do it using a destructuring expression.
let tuple = ("Hello", "world")
let (a,b) = tuple
printfn "%s %s" a b
或更常见的
let (a,b) = ("Hello", "world")
printfn "%s %s" a b
这篇关于将元组输入到诸如printfn之类的函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!