Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# - How to populate an System.Collections.Generic.List from array

Tags:

f#

I have following code that populates a System.Collections.Generic.List I don't like it so I was wondering if there is a better way to do this.

let getDirectories = 
        Directory.GetDirectories(_baseFolder)
let languagesList = new System.Collections.Generic.List<string>()
Seq.cast getDirectories 
|> Seq.map(fun dir -> (new DirectoryInfo(dir)).Name) 
|> fun range -> languagesList.AddRange(range)
like image 895
Enes Avatar asked Mar 02 '10 19:03

Enes


2 Answers

Have you tried:

let list = new System.Collections.Generic.List<string>(arr)

List<'T> has a constructor that takes an IEnumerable<'T> so it happily takes any seq<'T> you pass to it.

like image 187
mmx Avatar answered Oct 13 '22 10:10

mmx


In addition to Mehrdad's answer

I find it helpful to define helper modules for many standard collections and .Net types to make them more F# friendly. Here I would define the following

module BclListUtil =
  let ofArray (arr: 'T array) = new System.Collections.Generic.List<'T>(arr)
  let ofSeq (arr: 'T seq) = new System.Collections.Generic.List<'T>(arr)

Then you could change your original code to the following

let getDirectories = 
        Directory.GetDirectories(_baseFolder)
let languagesList = 
      getDirectiories
      |> Seq.map (fun dir -> (new DirectoryInfo(dir)).Name)
      |> BclListUtil.ofSeq
like image 25
JaredPar Avatar answered Oct 13 '22 09:10

JaredPar