Is there some way to convert between F# List and F# Tuple?
For example:
[1;2;3] -> (1,2,3)
(1,2,3,4) -> [1;2;3;4]
I need
As already pointed out, this is a tricky problem, because tuple isn't a single type - it is a family of types such as int * int * int or int * int and F# doesn't provide any way for taking the whole family of types as an argument. You can either write many similar functions (which is very uncomfortable) or use reflection (which is a bit slow and isn't type-safe).
Alternatively, you could limit the function to tuples with some structure - for example, instead of working with (1, 2, 3, 4), you could use nested tuples like (1, (2, (3, 4))). This is a bit less comfortable, but it keeps the type safety and it isn't as bad.
Then you can easily write combinators for constructing conversion functions on the fly:
// creates function for converting tuple (possibly with a nested
// tuple in the second component to list
let tl f (a, b) = a::(f b)
// converts last element of the tuple to singleton list
let te a = [a]
Then you can combine functions tl and te to create a type-safe function that converts nested tuple containing 4 elements to a list like this:
let l = (1, (2, (3, 4))) |> (tl (tl (tl te)))
Similarly, you can create functions for converting list to tuples - note that this may throw an exception if the list doesn't match the expected format:
let le = function
| [x] -> x
| _ -> failwith "incompatible"
let lt f = function
| [] -> failwith "incompatible"
| x::xs -> (x, f xs)
// convert list to a tuple of four elements
let t = [1; 2; 3; 4] |> lt (lt (lt le))
I guess this is probably as close to typesafe and reusable function for converting between tuples and lists as it can get. It isn't perfect (at all), but that's caused by the fact that you're trying to implement a very rarely used operation. In F#, the distinction between tuples and lists is clearer than for example in Python (which is dynamic, so it doesn't have to deal with static type safety).