Parameterized Modules
It would be great if you could provide some parameters to a module, even if it was just at compile time. Something like:
open Module1(p = 100)
This would make a lot of use cases much simpler to deal with while letting the code keep it's functional feel. This is especially true for math related stuff.
6 comments
-
Ryan Riley
commented
Does IL allow for pulbic static ctors? If so, would it be possible to generate a static type definition with public, mutable properties that could be exposed within the "module" ctor?
module Foo(Bar = "rickasaurus") =
...translates to:
public static class Foo {
public static Foo() { }
public static string Bar { get; set; }
}with some protection around the mutable member so that it could be prevented from being changed?
Might this be possible via Type Providers? I sadly don't have the time to try it now, nor have I ever done any IL generation for static types, though I remember seeing several posts in the past noting the use of generated assemblies using IL not available through C#.
-
Rickasaurus
commented
@Noldorin: Right now you have two choices for writing functional code in F# when you have a module of functions that all need the name input.
1) You can make everything take an additional parameter, which is just a pain to manage
2) You can made global mutables, which is great for messing around but is awful in production code.This would eliminate that problem.
-
Noldorin
commented
I'm not sure this added complexity is worth it. I personally think it just confuses the semantics of modules. What usage cases do you have in mind?
-
Ryan Riley
commented
Generics in modules doesn't seem so hard -- though I'm sure I'm wrong -- since modules compile down to static classes. Parameterizing modules seems a little more complicated. Since modules are static classes, they can't take parameters in their constructors. Doing a syntactic sugar combining generics with initializing fields/properties could probably work, though the compiler would probably need to set an additional, hidden and random generic to force unique module instances for different parameter values.
-
Rickasaurus
commented
Having thought about it more I think it really would have to be a runtime thing, and generics would really be nice here too.
-
Rickasaurus
commented
Just to go a bit further, one way to provide backwards compatibility would be attributes on module-level variables.
ex.
[ModuleParameter] // gt and lt aren't preserved in this forum.
let p = 50"open Module1" would then just use the value of 50, but the above example would use 100.
This would maintain local immutability, which I think is very desirable.