Similar to this question about clojure, is it possible to list the contents of a namespace or module in F#? When I open a namespace for a loaded DLL I'm not receiving an error that the namespace doesn't exist, but then when I try to use the documented functions I'm seeing errors that the namespace doesn't exist.
I'm looking for a programatic way of listing values and methods and not relying on the IDE. For example if I loaded up the F# repl I'm looking for something similar to:
> #r "mylib.DLL"
> open MyLib.Math
> list-namespace-content MyLib.Math;;
val it : string = """
MyLib.Math.Add : int -> int -> int
MyLib.Math.TryDivide : int -> int -> int option
MyLib.Math.Pi : float
"""
As far as I know, there's no such function that does exactly that (I had a glance at the FSharpReflectionExtensions module), but you can write one yourself. All the building blocks are there.
As strange as it may seem, namespaces aren't part of the .NET platform that both F#, C#, and Visual Basic .NET use. At the IL level, types are simply identified by name, culture, assembly, etc. Namespaces simply appear as the first part of the string that makes up a type's name.
However, given an assembly, you can list all its types, or all its public types. Here's an example of the latter, given an F# assembly I recently wrote doing the Tennis kata:
By looking at the strings to the left of the last
.
, you can find the namespace(s) in use - in this casePloeh.Katas.PropertyBased
.However, you should be aware that namespaces can span multiple assemblies. As an example,
System.Collections.Generic.List<'T>
is defined inmscorlib
, whileSystem.Collections.Generic.Stack<'T>
is defined inSystem
. Thus, using Reflection as above will only give you the members defined in a namespace in that particular assembly.As far as I know, F# modules are compiled to static classes with the
[<CompilationMapping(SourceConstructFlags.Module)>]
attribute. This means that you can list the modules like this:If you want to list all the functions in the
Tennis
module, you can do that like this:You may want to filter out some of the inherited methods, like
ToString
andGetHashCode
.