F# class Explicit Fields and DefaultValue - f#

This is an F# language-definition question.
I was wondering why F# can not automatically deduce Explicit Fields in the first place? And then DefaultValue automatically as well ...
Why have another class syntax (so many of them in F#)... where instead a let bound field without a value (but with a type) could be interpreted automatically as (the meaning of) val. Furthermore when a DefaultValue is needed along side a default constructor, why not just deduce it automatically?
let myInt1 : int
interpreted as the meaning of:
val myInt1 : int
or
[<DefaultValue>] val myInt : int
Lastly (could be a different topic, and therefore please consider it as a minor inquiry), why explicit fields (or public fields) require a self identifier reference within member methods? Again the class implementation syntax looses a lot of its simplicity.
Thanks!

I don't claim to understand all of your question.
Explicit fields can naturally not be inferred from the value because there is no value; it is uninitialised. So you need to give a type.
let myInt : int doesn't really make sense, because let needs a value.
I agree with you on the last point, the val could just as easily be in scope and not require this qualifier, subject to normal shadowing rules.

Was curious how you would force initialization of a val mutable field:
type MyClass private () =
[<DefaultValue>] val mutable v:int
new (v:int) as this = MyClass() then this.v <- v
This makes the primary constructor private so that the new (v:int) must be used. The form of new (v:int) as this definition lets you first call the primary constructor and initialize the val mutable using then ... this.v <- ...
The F# language reference on constructors was most helpful.

Related

How can I access static members in a generic context?

I need a workaround or idiomatic way to access the static members defined in some type from a generic context.
Example:
enum E { first, second, third }
// no direct syntax to constrain to enum types
class EnumKeyList<TEnum> {
List<Object> _values;
// unable to access static member
EnumKeyList() : _values = List.filled(TEnum.values.length, Object());
// unable to access instance member
Object operator [](TEnum entry) => _values[entry.index];
}
Usage:
final list = EnumKeyList<E>(); // E.values.length would provide implicit fixed-size list instantiation
list[E.first] = 5; // can use enumeration entries as keys
I want to avoid the overhead of Map (hashing and additional memory). The real use case must index into the list in tight loops.
Having a fixed set of named keys is a useful requirement, but the example EnumKeyList should work with any generic type argument that provides an enumeration like interface.
Using enumerations provides the shortest way to declare valid 0-indexed keys and the count of the amount of entries through an enumeration's static values member.
Swift enumerations and protocols allow for static members. C# has constraints for enumeration types. C++ generics dwarf everything. Is there a simple way to achieve this in Dart?
I realize that I can declare my own class instead of an enumeration, but then I lose the implicitly generated members (having to manually assign a value to each constant in the class (bad for maintenance)) and I still can't provide access to a static member from the generic context.
See here for examples of how unmaintainable this is:
abstract class Enum {
final int rawValue;
const Enum(this.rawValue) : assert(rawValue >= 0);
// don't bother with a static 'values' member
}
class E extends Enum {
const E(int rawValue) : super(rawValue);
static const first = E(0);
static const second = E(1);
static const third = E(1); // repeated values
static const List<E> values = <E>[first, second]; // missed one
}
You cannot access static members through type variables.
Dart static members are really just declared in the namespace of the corresponding class/mixin/extension declaration, they are not part of the type. Type variables hold types, not declarations.
There is no idiomatic workaround.
You have to figure out which operations you need your class to support, then you can introduce a strategy object representing the class, and pass that to the function instead of (or alongside) the type argument.
In this case, you probably want the EnumKeyList constructor to take the list of values as an argument, so:
EnumKeyList(List<T> values) : _values = List.unmodifiable(values);
The workaround, in general, is to pass the values you'd want to read from a static member directly to the function needing them, along with the type.
You can't access them using the type alone.
The "cannot access index" problem could be fixed by the language adding an interface to all enums, like abstract class Enum { int get index; } and make all enum classes implement that interface.
There is no easy way to allow access to the values knowing only the type.
It might be possible to do something magical in the compiler and platform libraries, but it won't extend to user-written enums like this, and no viable way to emulate it.

F# check if val member is uninitialized

I have an F# class that uses the following to declare, but not initialize class members:
[<DefaultValue>] val mutable myVariable : myType
How can I check in the code whether this value has been initialized? I tried:
x.myVariable = null
but that doesn't seem to work.
From your description, it is a bit hard to say what you are actually trying to achieve - using both uninitialized values and inheritance is generally not the preferred way of doing things in F# (but they are both sometimes necessary for interoperability with .NET), so if you follow this direction, you might not be getting that many advantages from using F#.
Wouldn't the following work for you instead? The idea is that we define a base class that takes the value of the private thing through a constructor:
type Base(myThing : Random) =
member x.MyThing = myThing
And an inherited class can then provide a value, but also access it using a member:
type MySubclass() =
inherit Base(new Random(0))
member x.Next() =
x.MyThing.Next()

Mutable reference cells don't work with static members

I think I understand what's happening here, but I'd really appreciate someone throwing some light on why it's happening.
Basically (and I'm coding on the fly here, to give the simplest possible illustration) I have a class S which, among other things, maintains a symbol table relating names to objects of the class. So, inside the class I define:
static member (names:Map<string,S> ref) = ref Map.empty
... and then later on, also in S, I define:
member this.addSymbol (table: Map<string,S> ref) (name:string)
table := (!table).Add(name, this)
this
I call this from elsewhere, thus:
ignore (s.addSymbol S.names "newname")
...
Inside S.addSymbol I can see the new key/value being added to table, but S.names doesn't get updated. If, instead, I call addSymbol like this:
ignore (
let tmp = S.names
s.addSymbol tmp "newName"
)
then I can see tmp being updated with the new key/value pair, but S.names still doesn't get updated.
Here's what I think I know: there's nothing wrong with the ref mechanism - that's updating the referent correctly both inside and outside the function. But there seems to be something odd about the static member - it's like, rather than just handing me the same static ref 'a each time, it's copying the 'a and then creating a new ref for that.
Have I got this right? If so, why is it doing it? And what can I do to make it behave more sensibly?
Thanks in advance.
The static member names is a property, not a static value. It is, internally, a function that creates a new map every time it is called.
If the value has to be in the class, use static let to define it inside the class. That way, the reference cell is only created once.
type S () =
static let names = ref Map.empty : Map<string, S> ref
static member Names = names
S.Names := ["Don", S()] |> Map.ofList
S.Names // gives map with one element
Oftentimes, the class doesn't expose the reference cell itself, but rather members to read, add, or remove names. Then, Names would return !names -- or names would be a plain mutable instead of a reference cell -- and other methods like AddName would alter the value. If there is no need for such encapsulation, see kvb's comment for how to shorten this example to only one member. (Thanks for the hint!)
Alternative: Normally, this is a case in which F# modules are used. Just define
let names = ref Map.empty : Map<string, S> ref
or
let mutable names = Map.empty : Map<string, S>
in a module, with additional access restrictions or encapsulation as required.

Cyclic function/type dependency in F#

I have a question about the best way to go about the following
I Have a class B, I have a combinator on B,
let foo : B -> int.
I want the class B to have the combinator encapsulated as a method, so I add it with a type extension.
I then later on realize that foo is quite expensive and want to cache it's result with lazy evaluation
So I add a huge clutch to the system by passing the combinator as a function to the constructor and then initializing a field with foo = lazy(foo self) in the constructor.
i.e.
type foo =
class
val x : int Lazy
new (comb) as self = {x=lazy(comb self);}
end
let something (x:foo) = 1
type foo with
new() = foo(something)
this obviously feels wrong
the two options I see for fixing this are 1, make an interface and have foo inherit that interface, 2, make everything a static method and then make combinators out of those static methods(sort of the opposite of attaching them to classes...)
Neither of these are hugely appealing and I was wondering if I missed option 3
Oh, and I haven't been able to get let rec and to work quite right with this, nor would i really want to as "something" in the above statement depends on a function that depends on a function that depends on a function(3 deep).
any advice would be appreciated
I don't think there is anything wrong with your current design. The key point is that if you define the type Foo as well as the extension to the type in a same file (and the same module), then F# will combine the two parts of the definition into a single .NET type. So, the fact that it is defined in two separate parts is just an implementation detail.
If you don't want to expose the constructor that takes the combinator, you can mark it as private. Together with a few additional changes (i.e. use implicit constructor syntax), the snippet would look like this:
type Foo private (comb) as self =
let x : Lazy<int> = lazy comb self
let something (x:Foo) = 1
type Foo with
new() = Foo(something)
If you want to keep something as a separate function, then this is a fine solution. Many numeric types in the F# PowerPack follow this pattern (see for example definition of complex numbers)
I don't quite grok what you're after, but I think this may help:
type foo(comb) as self =
let x = lazy(comb self)
static member something (x:foo) = 1
new() = foo(foo.something)
A type can be recursive with its own static member, so this is a simpler way to write your code.

Accessing let bound fields from static members

Is there any way to access let bound fields from a static member? The following gives the indicated error:
type Foo(x) =
let x = x
static member test() =
let foo = Foo(System.DateTime.Now.Month)
printfn "%A" foo.x //the field, constructor or member 'x' is not defined
()
Whereas private explicit fields do allow access from static members:
type Bar =
val private x:int
new(x) = { x=x }
static member test() =
let Bar = Bar(System.DateTime.Now.Month)
printfn "%A" Bar.x
()
The documentation http://msdn.microsoft.com/en-us/library/dd469494.aspx states that "Explicit fields are not intended for routine use," yet accessing private instance fields from static members is certainly a routine scenario. Moreover, I don't believe you can set explicit fields within a primary constructor, which means if even one private instance field needs to be accessed from a static member, all of your fields must be moved over to explicit fields and you can no longer use a primary constructor -- it's all or nothing.
As real world example where you would actually want to access a private instance field from a static member, consider a big integer implementation: a BigInteger class would be immutable, so the internal representation of the big integer would kept as a private instance field (let's call it data). Now, suppose you felt an Add(other) instance method was inappropriate for an immutable data structure and you only wanted to implement a static Add(lhs,rhs) method: in this case, you would need to be able to access lhs.data and rhs.data.
I don't think you can do that... in fact, you can't access let-bound values from other instances either:
type Foo() =
let x = 3
member this.Test(f:Foo) =
f.x // same error
In general, if you need to access such a value from outside of the instance it belongs to, you should probably either create a private property to get the value or use a private field instead.
UPDATE
This is covered by section 8.6.2 of the spec. In particular:
Instance “let” bindings are lexically scoped (and thus implicitly private) to the object being defined.
Perhaps someone from the F# team will weigh in with a definitive answer as to why the language behaves this way. However, I can think of a couple of potential reasons:
let-bound values may not even be present as fields (e.g. again from the spec, a let binding will be represented by a local to the constructor "if the value is not a syntactic function, is not mutable and is not used in any function or member")
This seems consistent with the behavior of let bindings elsewhere in the language. See the examples of a roughly equivalent class and record definitions which I've included further down (because I can't seem to properly format code blocks within an ordered list...)
This provides a finer-grained level of encapsulation than is possible in many other languages - bindings which are local to the object being defined. Often, other instances will not need access to these bindings, in which case it's nice not to expose them.
If you want something which is accessible by other instances of your class (or from within static methods), there's an easy way to do that - create a private field or property, which has the benefit of explicitly expressing your intention that the value be accessible from outside of the instance that you are in.
As mentioned earlier, here are a roughly equivalent class definition and method to create a record:
type MyClass(i:int) =
let j = i * i
member this.IsSameAs(other:MyClass) =
false // can't access other.j here
type myRecord = { isSameAs : myRecord -> bool }
let makeMyRecord(i:int) =
let j = i * i
{ isSameAs = (fun r -> false) } //obviously, no way to access r.j here
Since constructors in F# are conceptually similar to any other function which returns an instance of a type (e.g. they can be called without using new), calling MyClass 5 is conceptually similar to calling makeMyRecord 5. In the latter case, we clearly don't expect that there is any way to access the local let binding for j from another instance of the record. Therefore, it's consistent that in the former case we also don't have any access to the binding.
yet, accessing let bound fields from
static members is certainly a routine
scenario
What do you mean here? What is the corresponding C# scenario (with an example)?
Note that this is legal:
type Foo() =
let x = 4
member this.Blah = x + 1
member private this.X = x
static member Test(foo:Foo) =
foo.X
That is, you can expose the let-bound value as a private member, which a static can read/use.

Resources