0

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?

asked Mar 19 at 14:43
2
  • To start with, in the [] 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. Commented Mar 19 at 15:07
  • @Brian Berns Thank you, it compiles now. Commented Mar 19 at 15:19

1 Answer 1

2

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.

answered Mar 19 at 15:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.