I am trying to create an OCaml function rv that will go through a list of lists and reorganize the elements into another list of lists such that the first list is comprised of the first element of each of the original lists, the second list is comprised of the second element of each list etc.
An example:
[["a"; "b"; "c"]; ["d"; "e"; "f"]] becomes
[["a"; "d"]; ["b"; "e"]; ["c"; "f"]]
I already have a function gather that will take a list of lists and extract the elements of a certain index from each list. So basically using the previous example I could say gather(list, 1) and get ["b"; "e"] back. I need a way to go through List.length times and use gather for each element index.
The reason this is causing me so much trouble is because of the limitations applied (yes, this is for school). I am not allowed to use loops or local/global variables. I am also not allowed to use ‘let’ within the body of a function. Is there another way to recursively use gather for each element index? Is there another function I should make that will recursively use gather and then re-use that function in rv? If so, how would you go about that?
To overcome the restriction against loops, use recursive functions.
The restriction about using
letis a little silly. You can work around it by passing arguments to a function, to some extent, writing(function x -> e) vinstead oflet x = v in e. But think of it as a hint that you’re supposed to leverage functions such asList.mapandList.fold_leftand so on.Generally speaking, lists are not arrays; they’re not meant to be accessed with the index of an element. Sure, you can do it, but it’s cumbersome and inefficient. The natural way to access a list is to use pattern matching or the
List.hdandList.tlfunctions to split out the first element and the remainder of the list, or to use functions such asList.mapto traverse the whole list.For example, if all you needed was the first element of each list, then you could use
And
List.map List.tl listsgives the remainder of each list. This suggests a recursive method: the head of the result isList.map List.hd lists, and the tail of the result is the transposition ofList.map List.tl lists.Now, obviously, we need to terminate at some point. Assuming all lists have the same length, we need to stop when the lists are empty, which we can test by looking at the first list. I will leave this as an exercise.
To understand what this code is doing, I recommend typing it in the Ocaml toplevel, using the
#tracedirective and watching the operation on a few examples. For this, it will help if you make thetransposefunction monomorphic.