1

I am trying to create a .NET list of F# functions, but it keeps telling me that it expects a something something, but has a 'a instead. I'm not sure, but I'm guessing it's because I can't create a .NET list of F# functions. Is this true?

For example, when I try:

let listOfFunctions = new List<int -> unit>()

The compiler complains accordingly:

No constructors are available for the type 'List<(int -> unit)>'

EDIT

After much thought, I realized, I forgot to open System.Collections.Generic, which caused the issue. I didn't notice the issue because the compiler thought it was an F# list, which doesn't have a constructor like .NET Lists do. However, it's confusing because the type signatures look the same. Consider the following code:

let FSharpList : List<int> = [1;2;3]
let DotNetList : List<int> = new List<int>()

If you don't use open System.Collections.Generic, the compiler assumes List to be an F# list, and the second line will obviously fail. But if you include it, then the compiler will assume List is a .NET list, and the first line will complain that [1;2;3] is supposed to have type List<int> but instead has type 'a list (aka it's expecting a .NET list).

So actually, it had nothing to do with a list of functions at all. In fact, the following code:

open System.Collections.Generic
let myList = new List<int -> unit>()

works just fine.

user3685285
  • 6,066
  • 13
  • 54
  • 95
  • 5
    Can you post the code you're trying to use? – kemiller2002 Feb 24 '16 at 20:38
  • I think I get what the problem is, but as has been said, you should post the code you're trying to use. – TeaDrivenDev Feb 25 '16 at 02:22
  • 2
    @Guy Coder, I don't think this is a duplicate. The question you posted is asking about an F# list of F# functions. I'm trying to create a mutable .NET list of f# functions that I can add to using List.Add(element). They are totally different kinds of lists. – user3685285 Feb 25 '16 at 12:43
  • 1
    A few things small things: To help avoid exactly this confusion between the types, F# aliases `System.Collections.Generic.List<'T>` to `ResizeArray<'T>`. Also, it is often not necessary to explicitly state generic type parameters in F#. If you just write `ResizeArray<_>`, the compiler will try to figure out the type from how you use it. And thirdly, you don't *need* `new` in F# (the compiler will suggest using it for types implementing `IDisposable`, though). – TeaDrivenDev Feb 25 '16 at 15:51
  • 2
    I think that now this has been clarified it is probably just a duplicate of https://stackoverflow.com/questions/12010316/creating-a-generic-list-t-in-f – John Palmer Feb 25 '16 at 22:24

0 Answers0