Is there a library function or operator for creating a tuple?

Given a string of numbers, I would like to have a sequence of tuples displaying non-zero characters with their position in the string. Example:

IN: "000140201" OUT: { (3, '1'); (4, '4'); (6, '2'); (8, '1') } 

Decision:

 let tuples = source |> Seq.mapi (fun i -> fun c -> (i, c)) |> Seq.filter (snd >> (<>) '0') 

It seems that (fun i -> fun c -> (i, c)) is much more typed than it should be for such a simple and supposedly general operation. It is easy to declare the desired function:

 let makeTuple ab = (a, b) let tuples2 = source |> Seq.mapi makeTuple |> Seq.filter (snd >> (<>) '0') 

But it seems to me that if the library provides the snd function, it should also provide the makeTuple function (and probably a shorter name), or at least it should be relatively easy to create. I could not find him; Am I missing something? I tried to create something with a Tuple.Create framework, but I couldn't figure out how to get anything other than one-factor overload.

+9
source share
2 answers

But it seems to me that if the library provides the snd function, it should also provide the makeTuple function.

F # assumes that you decompose tuples (using fst , snd ) much more often than you compose them. The functional design of a library often follows a minimal principle. Just provide functions for general use cases, other functions should be easily defined.

I could not find it; Did I miss something?

No no. For the same reason that FSharpPlus defined tuple2 , tuple3 , etc. Here are useful functions directly from the operators :

 /// Creates a pair let inline tuple2 ab = a,b /// Creates a 3-tuple let inline tuple3 abc = a,b,c /// Creates a 4-tuple let inline tuple4 abcd = a,b,c,d /// Creates a 5-tuple let inline tuple5 abcde = a,b,c,d,e /// Creates a 6-tuple let inline tuple6 abcdef = a,b,c,d,e,f 

I tried to build something using the Tuple.Create framework, but I could not figure out how to get something other than a single argument overload.

The F # compiler hides the properties of System.Tuple<'T1, 'T2> to ensure that pattern idioms match for tuples. See the Extension methods for F # tuples for more information.

However, a dotless style is not always recommended in F #. If you like without glasses, you have to raise yourself a little.

+8
source

The answer to @pad is great, just add my 2 cents: I use a similar operator

 let inline (-&-) ab = (a, b) 

and it is very convenient to write let x = a -&- b

You may also find this operator useful.

+4
source

All Articles