-
Notifications
You must be signed in to change notification settings - Fork 832
-
nowadays is often needed to cast to |> ResizeArray
or to upcast to :> ICollection
to have interop between F# collections and C# collections,
would it make sense to add new LIST CEs for those 2 types?
mutable [ ...... ]C# list (shorthand for resize array) as it's a mutable list List?col { ...... }ICollection (Col module) as alternative to Seq module (IEnumerable) ?mutable dict { ("KEY",1) }to allow mutable keyword, or some similar solution to allow C# Dictionary<A,B>
https://stackoverflow.com/questions/14912548/f-return-icollection
6 votes ·
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments 1 reply
-
Until fsharp/fslang-suggestions#1086 happens, you can give https://github.com/brianrourkeboll/FSharp.Collections.Builders/ a try.
It offers builders for a number of F# and BCL collections, including resizeArray { ... } and dictionary { ... } (corresponding to System.Collections.Generic.List<'T> and System.Collections.Generic.Dictionary<'TKey, 'TValue>):
let xs = resizeArray { 1; 2; 3 }
let d = dictionary { 1, "a" 2, "b" 3, "c" }
It even has target-typed collection { ... } and dict' { ... } builders if you want:
let xs: ResizeArray<int> = collection { 1; 2; 3 } let ys: HashSet<int> = collection { 1; 2; 3 }
let xs: Dictionary<int, string> = dict' { 1, "a"; 2, "b"; 3, "c" } let ys: SortedDictionary<int, string> = dict' { 1, "a"; 2, "b"; 3, "c" }
And it can be extended pretty easily to additional collection types as well:
[<Sealed>] type SomeOtherCollectionBuilder<'T> () = inherit CollectionBuilder () static member val Instance = SomeOtherCollectionBuilder<'T> () member inline _.Run([<InlineIfLambda>] f : CollectionBuilderCode<_>) = let mutable sm = SomeOtherCollection<'T> () f.Invoke &sm sm let someOtherCollection<'T> = SomeOtherCollectionBuilder<'T>.Instance
You could do something like this for your ICollection<_> usage scenario:
[<Sealed>] type ICollectionBuilder<'T> () = inherit CollectionBuilder () static member val Instance = ICollectionBuilder<'T> () member inline _.Run([<InlineIfLambda>] f : CollectionBuilderCode<_>) = let mutable sm = ResizeArray<'T> () f.Invoke &sm sm :> System.Collections.Generic.ICollection<'T> let icollection<'T> = ICollectionBuilder<'T>.Instance let f xs = icollection { 1; 2; 3; yield! xs } // Returns an ICollection<_>.
Beta Was this translation helpful? Give feedback.
All reactions
-
👍 1 -
❤️ 2
-
That's great stuff! I never considered writing such builders myself, glad to see something like this made available :).
Beta Was this translation helpful? Give feedback.
All reactions
-
❤️ 1
-
I usually use linked list, or simply use any c# list I wanted by specifying dotnet namespace (System.Collection.Generic...)
for any collection I treat them as IEnumerable and use Seq module for now
Beta Was this translation helpful? Give feedback.