James Parsons
James Parsons

Reputation: 6057

F# - convert Array to list

I am reading a file into an array like follows (note I know this is bad code):

let filename = if argv.[0] != null then argv.[0] else System.Console.ReadLine()
let data = File.ReadAllLines(filename)

I want to perform an F# map onto the data returned in that above line. My problem is that I can only perform map on n F# list, and not the System.String[] that File.ReadAllLines() returns. Can I convert a standard .Net array into an F# list. I'm sure that I could just read the file differently, or labor through manually copying the array contents to a list, but it would be a lot easier if there was a simple way to do this.

Upvotes: 9

Views: 9897

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233135

Since File.ReadAllLines returns an array, you can use Array.map on it. It works the same way as List.map.

Another option is Seq.map, since arrays also implement the seq 'a (IEnumerable<T>) interface.

As others have pointed out, you can also convert the array to a list using Array.toList or List.ofArray, but be aware that this operation traverses the array and copies it to a list (hence there's a small overhead involved in doing so).

Upvotes: 2

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can use Array.toList to do that.

let data2 = data |> Array.toList

Or you can use List.ofArray

let data2 = data |> List.ofArray

You can also do Array.map instead of List.map and in that case you might not need to map to list at all.

Upvotes: 15

Related Questions