F# check if val member is uninitialized - f#

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()

Related

How to define optional parameters in F# modules?

I'm trying to re-write a tiny C# lib in F# and I've encountered an error. I'm trying to define optional parameters for a method in a module but the compiler says "Optional arguments are only permitted on type members".
I've checked why you can't use them in loose functions but when typing static member or member I get another error instead.
module Kingdom =
let Rule (?years : int) =
()
I thought this was going to wor kas it's how I understood you type it, after reading the Microsoft Docs article about it.
By using another way to define the "static class" you can add member to it. And then you can use optional parameters. The class will show up as a normal static class in C#.
[<AbstractClass; Sealed>]
type Kingdom private () =
static member Rule (?years : int) = ()

F# class Explicit Fields and DefaultValue

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.

Class definition with no parameter-list

F# accepts the following:
type Abc =
member this.A = 10
Since no parameter-list was supplied, there is no default constructor. Can a constructor be added to Abc? If not, what can be done with Abc?
I can't think of many uses for this, but two things you can do are
inherit from it, albeit derived types must not be instantiable either
extend it with static members (although this is better achieved with modules, which can also be extended)
type Abc =
member this.A = 10
[<Class>]
type Def =
inherit Abc
type Abc with
static member Foo() = ()
In C#, Code Contracts for an interface or abstract class are defined in a "contract class" which must be marked abstract and have a private constructor (i.e. it's non-instantiable). This, in my opinion, is a better way of accomplishing that. But C# doesn't support constructor-less classes.

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.

Unknown need for type annotation or cast

I know I must be missing something really obvious here. B.GetInstance().Call() generates the error: Lookup on object of indeterminate type based on information prior to this program point. A type annotation may be needed prior to this program point to constrain the type of the object. This may allow the lookup to be resolved.
I'm using v1.9.9.9.
type A() =
member x.Call() = B.GetInstance().Call()
and B() =
static member GetInstance() = new B()
member x.Call() = ()
I just discovered that this works: (B.GetInstance() :> B).Call()
Any idea why the cast is necessary?
Frequently when you've got a recursive set of methods whose types to infer, F# needs help. A more pleasant alternative would be to annotate the definition of B.GetInstance:
type A() =
member x.Call() = B.GetInstance().Call()
and B() =
static member GetInstance() : B = new B()
member x.Call() = ()
I believe that the reason you run into this problem is that F# tries to solve all inferred types on all methods in A and B simultaneously (because they are defined as mutually recursive types), and this leads to problems, but perhaps someone from the F# team will weigh in.
The quick summary is that in a recursive group (e.g. members in one type, or members of recursive types like we have here) F# reads the declarations in left-to-right top-to-bottom order, followed by the definitions in left-to-right top-to-bottom order. So in this instance when it reaches the definition of A.Call, it has not yet read the definition of B.GetInstance and therefore does not (yet!) know that the return type of GetInstance will be B.
Keith's answer nails it for this situation, you can provide a type annotation to specify the return type of GetInstance in its declaration.
See
Forcing F# type inference on generics and interfaces to stay loose
for a deep discussion of what's going on here.
Note also that in your original attempt, you don't need to "cast" (the potentially dynamic operation, using :>), instead you can just "annotate" (statically declare a type, using :) to get it to compile. But makes more sense to put the type annotation in the method declaration for GetInstance (generally, prefer addition annotations to method signatures instead of arbitrary places inside bodies).

Resources