Home > Software design >  f# iterate and use List<List<string>>
f# iterate and use List<List<string>>

Time:01-25

I have simple list that contains inside list

let ftss = [
  ["a","aData"],["b","bData"]
] 

I want to iterate and access the elements "a" and "aData" etc.

I tried

List.iter (fun item ->
    for i in 0..1 do 
        printfn "%s" item[i])

how do i access the elements inside the internal list? Thanks

CodePudding user response:

So, 1st thing is a comma isnt a delimter in a list, but in a tuple ',' so

let ftss = [
  ["a","aData"],["b","bData"]
] 

is actually of type

val ftss: ((string * string) list * (string * string) list) list =

i.e. its a list of 1 entry of a tuple of a list of 1 entry each of a tuple. which I THINK isnt what you intended?

I THINK you want (a ';' or new line delimits each entry)

let ftss3 = [
  ["a";"aData"]
  ["b";"bData"]
] 

which is

val ftss3: string list list = [["a"; "aData"]; ["b"; "bData"]]

i.e. a list of a list of strings.

(I'd try to use FSI to enter these things in, and see what the types are)

so to iterate this list of lists you would go

List.iter (fun xs -> 
    List.iter  (fun x -> 
        printfn "%s" x)
        xs)
    ftss3

CodePudding user response:

As pointed out in the existing answer, you probably want to represent your data as a list of lists, for which you need to use the ; delimiter (to make a list) rather than , to construct a singleton containing a tuple.

I would just add that if you want to perform an imperative action with each of the items, such as printing, then it is perfectly reasonable to use an ordinary for loop:

let ftss = [
  ["a"; "aData"]; ["b"; "bData"]
] 

for nested in ftss do 
  for item in nested do 
    printfn "%s" item
  • Related