Michael Gabbay
Michael Gabbay

Reputation: 465

f# iterate and use List<List<string>>

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

Upvotes: 0

Views: 57

Answers (2)

Tomas Petricek
Tomas Petricek

Reputation: 243041

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

Upvotes: 1

MrD at KookerellaLtd
MrD at KookerellaLtd

Reputation: 2797

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

Upvotes: 3

Related Questions