Given a list of tuples, where each tuple consists of 3 integers, transpose the list recursively so that the "rows" and "columns" are swapped. The result will be a list of lists.
So for example: transpose [ (1, 2, 3); (11, 12, 13) ] => [ [1; 11]; [2; 12]; [3; 13] ]
So I tried:
let rec transpose LT =
match LT with
| [] -> [[], [], []]
| (a, b, c) :: tail ->
let rest = transpose tail
match rest with
| [d; e; f] -> [a::d; b::e; c::f]
but is getting the error:
All elements of a list must be implicitly convertible to the type of the first element, which here is ''a list * 'b list * 'c list'. This element has type ''d list'.
at the list of lists [a::d; b::e; c::f]
Can anyone tell me what I'm missing or what I'm doing wrong?
1 Answer 1
The first branch of the match returns [[], [], []]
which is of type (list * list * list) list
- that is, a list of triples, where each element of the triples is also a list.
But the second branch returns [a::d; b::e; c::f]
, which is of type list list
, which is a list of lists.
So your function returns two different types, which cannot happen. You need to bring them into sync.
Either return a list of lists from the first branch:
| [] -> [[]; []; []]
Or return a list of triples form the second:
| [d, e, f] -> [a::d, b::e, c::f]
Note that this only explains your immediate error and how to get rid of it. Your solution to the problem you're stating is still very much incorrect for multiple reasons. For one, you're only handling matrices with three rows.
[]
case, I think you want to use semicolons to separate elements, not commas, so the result is[[]; []; []]
. That should at least get your program to compile, and you can work on the logic from there.