danf9272
danf9272

Reputation: 15

How to add a string to a list of lists

I'm new at F# :)

I have a =[[|"hi"|];[|"how";"are"|];[|"you"|];[|"fine";"and";"you"|]]

and i would like to add a value like this:

b = [[|"12345";"hi"|];[|"32443";"how";"are"|];[|"32422";"you"|];[|"23232";"fine";"and";"you"|]]

those numerical string values comes from a string list

c = (["12345";"32443";"32422";23232])

Both a and b have the same length. How can I do this?

Thanks a lot!

Upvotes: 0

Views: 170

Answers (1)

John Reynolds
John Reynolds

Reputation: 5057

You can use the List.map2 function, which takes your 2 lists a and c, and runs a function for each pair of elements from a and c:

let b = List.map2 (fun number array -> Array.append [|number|] array) c a

Note that Array.append will create new arrays. If the elements of a don't have to be an array, but can be a list instead, it will be more efficient. This is because adding an element first in a list is a very fast operation, and it will not create new lists:

let a = [["hi"];["how";"are"];["you"];["fine";"and";"you"]]
let b = List.map2 (fun number ls -> number::ls) c a

Upvotes: 1

Related Questions