Feeding tuple into function such as printfn

后端 未结 1 750
一整个雨季
一整个雨季 2021-02-07 19:44

I want to give a tuple to a printf function:

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

This, of course, does n

相关标签:
1条回答
  • 2021-02-07 20:11

    You want

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

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

    See: <||

    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
    
    0 讨论(0)
提交回复
热议问题