Type of output and new - I’m probably just stupid

Using F # 2.0 and FSI, I have the following:

let foo = List(xs)//works let bar = new List(xs) //need type parameter 'The type System.Collectsion.Generic<_> expects 1 type argument 0 was given 

now of course i can do:

 let baz = new List<TypeOItemsInXs>(xs)//why? 

Now can I do something reasonable? Why do I have to choose between free working type output or warning code (if "List" is one-time, you get a warning that you must use the "new" to be explicit).

Any workaround? Is this a mistake or something else?

+6
source share
2 answers

You can still use type inference with wildcard _ :

 open System.Collections.Generic let xs = [1;2;3] let bar = new List<_>(xs) 

BTW, to distinguish between the F # list and the .NET List<T> container, F # renamed the .NET List<T> to ResizeArray<T> , which is located in Microsoft.FSharp.Collections , and this namespace is open by default:

 let bar2 = new ResizeArray<_>(xs) 
+13
source

Yin Zhu's answer is correct, I would like to add one detail. In F #, you can call .NET constructors with or without the new keyword. If new omitted, there is no need to add a general parameter, but if you use new , then you must add a general parameter, even if you allow input of type output using the wildcard _ .

So you can say:

 > ResizeArray([1; 2; 3;]);; val it : System.Collections.Generic.List<int> = seq [1; 2; 3] 

or

 > new ResizeArray<_>([1; 2; 3;]);; val it : ResizeArray<int> = seq [1; 2; 3] 

but not:

 > new ResizeArray([1; 2; 3;]);; new ResizeArray([1; 2; 3;]);; ----^^^^^^^^^^^ C:\Temp\stdin(5,5): error FS0033: The type 'Microsoft.FSharp.Collections.ResizeArray<_>' expects 1 type argument(s) but is given 0 
+8
source

Source: https://habr.com/ru/post/890670/


All Articles