Feeding tuple into function such as printfn

北战南征 提交于 2019-12-04 17:28:20

问题


I want to give a tuple to a printf function:

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

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

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

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?


回答1:


You want

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

Notice the double || in <|| and not a single | in <|

See: MSDN <||

You can also do

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

There are other similar operators such as |>, ||>, |||>, <|, <||, and <|||.

A idiomatic way to do it using fst and snd is

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.

So for the tuple ("Hello", "world") we can create a destructor which breaks the tuple into two parts.

let (a,b) = tuple

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

or more commonly

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


来源:https://stackoverflow.com/questions/20568309/feeding-tuple-into-function-such-as-printfn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!