Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feeding tuple into function such as printfn

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?

like image 503
Rustam Avatar asked Dec 13 '13 13:12

Rustam


1 Answers

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
like image 162
Guy Coder Avatar answered Sep 23 '22 01:09

Guy Coder