Jose Maria de la Torre
Jose Maria de la Torre

Reputation: 265

Create a list from many other lists f#

First of all im VERY VERY noob in f# so I need your help :)

I have a library with 50 lists that each have around 10 entries

What I need to do is join all 50 lists into one big list. The things is that I cant use "for" or mutable variables. what I have done (which I think is horribly done) is:

 let rec finalList x =

    if x < wallID.Length then  List.append [interfaz.hola(wallID.Item(x)).[0].[1]] [finalList]

    else listaFinal (x+1)

printfn "list %A" (listaFinal 10 )

WallID represents one of the 50 lists and interfaz.GetMuroHumano(wallID.Item(x)).[0].[1] gets me one of the entries that I need. (for now if a can just get one of the data for each wallID im ok)

again im verrrrry noob and I hope you guys can help me

thanks

EDIT:

So now its partially working..

 let rec finalList x y =
      if x < wallID.Length then 
         if y < [interfaz.GetMuroHumano(wallID.Item(x)).[y]].Length then 
            let current = [interfaz.GetMuroHumano(wallID.Item(x)).[y].[1]]
            let rest = finalList (x y+1)
            List.append current rest
          else finalList (x+1 y) 
      else []

vut im getting errors calling the function finalList it says that "y" is not an int but a string

Upvotes: 0

Views: 101

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243041

It is hard to say what is wrong with your code without seeing a complete version. As Daniel points out, there is a built-in library function for doing that - in fact, you do not even need List.collect, because there is List.concat that takes a list of lists.

However, you might still try to get your original code to work - this is useful for understanding functional concepts! I added some comments that can help you understand how it should work:

let rec finalList x =
    if x < wallIDLength then  
      // Get the list at the index 'x'
      let current = interfaz.GetMuroHumano(wallID.Item(x))
      // Recursively process the rest of the lists
      let rest = finalList (x + 1)
      // Check that both 'current' and 'rest' are variables 
      // of type list<'T> where 'T is the element type
      List.append current rest
    else 
      // Return empty list if we got too far
      []

// Start from the first index: 0
printfn "list %A" (finalList 0)

Upvotes: 2

Daniel
Daniel

Reputation: 47904

let flatten xs = List.collect id xs

Upvotes: 0

Related Questions