I want to create a type safe recursive function for flattening out tuples. However I can not get below the first recursion level in terms of type safety
type Flatten = Flatten
with
static member inline ($) (Flatten, (a: 'a, b: 'b)) : 'x list =
List.concat [ Flatten.Flat a; Flatten.Flat b]
static member inline($) (Flatten, (a: 'a, b: 'b, c: 'c)) : 'x list =
List.concat [Flatten.Flat a; Flatten.Flat b; Flatten.Flat c]
static member inline Flat(x: obj) : 'x list =
match x with
| :? Tuple<'a, 'b> as t -> Flatten $ (t.Item1, t.Item2)
| :? Tuple<'a, 'b, 'c> as t ->Flatten $ (t.Item1, t.Item2, t.Item3)
| _ -> [x]
let inline flatten x = Flatten $ x
let a1 = flatten (1, (2, 2, 3), (3,3))
//this compiles
let a2 = flatten (1, (2, 2, 3, 4), (3,3))
// ^ but this too
I tried another approach
type Flatten = Flatten
with
static member inline ($) (Flatten, (a: 'a, b: 'b)) = List.concat [ Flat $ a; Flat $ b]
static member inline ($) (Flatten, (a: 'a, b: 'b, c: 'c)) = List.concat [Flat $ a; Flat $ b; Flat $ c]
and Flat = Flat
with
static member inline ($) (Flat, a: 'a) = [a]
static member inline ($) (Flat, x: ('a *'b)) =
let (a, b) = x
List.concat [ Flatten $ a; Flatten $ b]
static member inline($) (Flat, x : ('a * 'b * 'c)) =
let (a, b, c) = x
List.concat [Flatten $ a; Flatten $ b; Flatten $ c]
let inline flatten x = Flatten $ x
let a = flatten (1, 1)
let a1 = flatten (1, 1, 3)
let a2 = flatten (1, 1, (3, 3))
but I cant get that one to type check.
Does anybody have a clue?
One Additional Requirement
The reason I am doing all of this is partly because I want
let a1 = flatten (1, (2, 2, 3), (3,3))
to yield
val a1 : int list
That is because when I feed in a tuple of tuple of int then the only sensible result should be a int list
.
at the moment I get an obj list
int the first example a compile error in the second.
Best regards