I’m attempting a few minor tasks in F# to help get a handle on the language.
I would like to write a function that takes a n-dimensional list and returns a 1-dimensional list containing all the elements from each dimension.
For example, if the input was the following 3-dimensional list: [[[1;2];[3;4]];[[5;6];[7;8]]], the output would be: [1;2;3;4;5;6;7;8]
For 2-dimensions -> 1-dimension the function is pretty straightforward:
let coalesce list= List.collect(fun item -> item) list
Here is my attempt to generalize this to n-dimensions:
let rec coalesce (list, dimension) =
if dimension = 1 then list
else coalesce (List.collect(fun item -> item) list, dimension - 1)
I get the following error when I try to compile:
error FS0001: Type mismatch. Expecting a
‘a list list
but given a
‘a list
The resulting type would be infinite when unifying ”a’ and ”a list’
The issue is here:
List.collect(fun item -> item) list
There’s obviously something wrong with my thinking. What’s the proper way to write this sort of function?
This operation is not well-typed, but here’s a sample that works on
IEnumerables and returns alist<obj>:You can also write
which is more general, e.g.
EDIT
@Jon Harrop suggested another strategy – create a new type for nested lists: