f# adding non interface functions to object expressions - f#

Say I have an interface ICache which defines two functions, Function1 and Function2 and I use an object expression to implement it, but I also want to add a helper function:
let WebCache =
{ new ICache with
member __.HelperFunction = //this doesn't work!
member __.Function1 = foo
member __.Function2 = bar
}
F# seems to not allow you to add any methods that are not part of the interface. Is there a workaround? If I want to do this, should I not be using an object expression in the first place?

You can define the helper function as an ordinary (local) function outside of the object expression:
let WebCache =
let helper n =
printfn "Helping %" n
{ new ICache with
member __.Function1 = helper 1
member __.Function2 = helper 2 }

Related

Observable from callback method

Let say I have a class which iherits legacy API and overrides a virtual method which is called when something happens
type MyClass() as this =
let somethingObservable: IObservable<Something> = ...
override _.OnSomething(s: Something) = ...
How can I translate each invokation of OnSomething to a notification of somethingObservable?
That's probably a simple question, but I could not find a way to do it properly (should I use not advised ISubject?). Appreciate your help.
Using a subject like this is fine, and ensures correctness in the implementation.
Here's an example using FSharp.Control.Reactive, which gets you the idiomatic way of writing this.
type MyClass() =
inherit Legacy()
let somethingObservable =
Subject.broadcast
override _.OnSomething s =
somethingObservable |> Subject.onNext s |> ignore
member _.AsObservable =
somethingObservable |> Observable.asObservable
You can also use new Subject<_> and its methods, same thing.
In some assembly if you'd prefer not to take on the System.Reactive dependency, F# also natively supports IObservable through events.
type MyClassEvt() =
inherit Legacy()
let event = new Event<_>()
override _.OnSomething s =
event.Trigger s
member _.AsObservable =
event.Publish :> IObservable<_>

let vs member for private functions, in F#

Let's consider this code:
type TransactionTypes =
| TransactionType1
| TransactionType2
type Test() =
let mutable lastTransactionType1 = DateTime.MinValue
let mutable lastTransactionType2 = DateTime.MinValue
let getLastTransaction transaction =
match transaction with
| TransactionType1 -> lastTransactionType1
| TransactionType2 -> lastTransactionType2
let updateLastTransaction transaction =
match transaction with
| TransactionType1 -> lastTransactionType1 <- DateTime.UtcNow
| TransactionType2 -> lastTransactionType2 <- DateTime.UtcNow
Now (with the understanding that I'm still learning F#), I would like to clarify a couple things:
Something like:
let a = DateTime.Now
does a permanent binding, so 'a' will always be the same time on subsequent uses.
But, my understanding is that if there is a parameter, like:
let a anyParameter = DateTime.Now
will be re-evaluated every time due to the presence of the parameter. Is that correct?
In the code above, the two let statements (getLastTransaction and updateLastTransaction) are private to the type (Test)
I could also have implemented them as:
member private this.getLastTransaction = ...
member private this.updateLastTransaction = ...
Is there any reason, for private functions to prefer let vs. member private this?
"let mutable" already implies the this. so the fields are accessible by both forms.
So, what is the advantage of one form vs. the other?
When you are working with members, F# inherits a lot of things from the .NET object model. A .NET object can have a couple of different things:
Fields - those are storing a value (just like fields of a record). They can be mutable or immutable.
Methods - those can be invoked with zero or more arguments (like functions)
Properties - those have no arguments (like fields); they can be read or written, but when this happens, some code is invoked. A property is basically a pair of getter and setter methods.
In F#, some of this is less visible. However, let corresponds to a field and member with arguments corresponds to a method. Your tricky case is a member without arguments. For example:
type A() =
member x.Foo = printfn "Hi"; 42
Will Hi be printed only once, or will it be printed each time you access Foo? To answer, it's useful to know that Foo is a property with a getter. The above is actually a syntactic sugar for the full version:
type A() =
member x.Foo
with get() = printfn "Hi"; 42
Now you can see that there is a method behind the Foo property! Each time you access Foo, the compiler will generate a call to the get() method, so Hi will be printed repeatedly.
In addition to Tomas' answer:
let mutable lastTransactionType1 = DateTime.MinValue
is equivalent in C# to:
internal DateTime lastTransactionType1 = DateTime.MinValue;
and
member private this.getLastTransaction ...
is the same IL as far as IL is concerned with
let getLastTransaction ...
In equivalent C#, both are
internal DateTime getLastTransactionMember(TransactionTypes transaction)
{
if (transaction.Tag != 1)
{
return lastTransactionType1;
}
return lastTransactionType2;
}
But for using F# in an idiomatic way, you would want to go with let.
There's also a difference in that member does let you use the methods in bindings before their declaration, which might be useful in some cases (read: hacks)
let getType1 = this.getLastTransactionMember TransactionType1 //this compiles
member private this.getLastTransactionMember transaction =
match transaction with
| TransactionType1 -> lastTransactionType1
| TransactionType2 -> lastTransactionType2

Idiomatic way to declare static and instance member at once?

When I extend a type with a new function, I usually want it to be available from both dot-notation and free form. Either can be more readable depending on the situation, and the former helps with IntelliSense while the latter helps with currying.
In C#/VB.net, extension methods do this (although I cannot restrict the function to a static method of the extended static class, as in F#). I can write the function once and then invoke it both ways:
<Extension>
public function bounded(s as string, min as UShort, max as UShort) as string
if min > max then throw new ArgumentOutOfRangeException
if string.IsNullOrEmpty(s) then return new string(" ", min)
if s.Length < min then return s.PadRight(min, " ")
if s.Length > max then return s.Substring(0, max)
return s
end function
' usage
dim b1 = bounded("foo", 10, 15)
dim b2 = "foo".bounded(0, 2)
(That's not quite perfect yet, as I'd like bounded to be a static method of String, but C#/VB.Net can't do that. Point to F# in that regard.)
In F#, on the other side, I have to declare the function separatedly from the method:
// works fine
[<AutoOpen>]
module Utilities =
type List<'T> with
member this.tryHead = if this.IsEmpty then None else Some this.Head
module List =
let tryHead (l : List<'T>) = l.tryHead
Question: Is there a more elegant way to declare both methods at once?
I tried to use:
// doesn't quite work
type List<'T> with
member this.tryHead = if this.IsEmpty then None else Some this.Head
static member tryHead(l : List<'T>) = l.tryHead
which at least would let me skip the module declaration, but while the definition compiles, it doesn't quite work - someList.tryHead is OK, but List.tryHead someList results in a Property tryHead is not static error.
Bonus question: As you can see, the static member definition requires a type annotation. However, no other type could have access to the method that was just defined. Why, then, can't the type be inferred?
I don't know of a way to declare both APIs in a single line of code, but you can get rid of the type annotations by making the function the implementation, and then defining the method it terms of the function:
[<AutoOpen>]
module Utilities =
module List =
let tryHead l = if List.isEmpty l then None else Some (List.head l)
type List<'a> with
member this.tryHead = List.tryHead this

Setting base member values in F#

I am messing about trying to implement my own basic view engine in F# at the moment. Essentially I am inheriting from the VirtualPathProviderViewEngine.
To do this I need to set two view locations so the engine knows where to look for the views. In my F# type I inherit from the above and try to set the two view locations as below...
type FSharpViewEngine() =
inherit VirtualPathProviderViewEngine()
let viewLocations = [| "~/Views/{1}/{0}.fshtml"; "~/Views/Shared/{0}.fshtml" |]
member this.ViewLocationFormats = viewLocations
member this.PartialViewLocationFormats = viewLocations
The code above omits the overrides that are needed for the VirtualPathProviderViewEngine.
I run the project and I get an error message to say
The property 'ViewLocationFormats' cannot be null or empty.
Which I am assuming means that I am not setting the two base members correctly above. Am I just assigning the above incorrectly or do you suspect I am doing something else wrong?
As extra info, I have added the ViewEngine at start up time in the Global.fs (global.asax) like so...
ViewEngines.Engines.Add(new FSharpViewEngine())
If you just want to set properties of a base class, then you do not need member or override, but instead you need to use the assignment operator <- in the constructor. To implement the engine, you'll need to override two abstract methods that it defines, so you'll need something like this:
type FSharpViewEngine() =
inherit VirtualPathProviderViewEngine()
let viewLocations = [| "~/Views/{1}/{0}.fshtml"; "~/Views/Shared/{0}.fshtml" |]
do base.ViewLocationFormats <- viewLocations
base.PartialViewLocationFormats <- viewLocations
override x.CreatePartialView(ctx, path) = failwith "TODO!"
override x.CreateView(ctx, viewPath, masterPath) = failwith "TODO!"

creating IEnumerable from enumerators in fsharp using anonymous classes

From a class which does not implement Enumerator I can now create one (thks Daniel)
type Bloomberglp.Blpapi.Element with
member this.GetEnumerator() =
(seq { for i in 0 .. this.NumElements - 1 -> this.GetElement(i) }).GetEnumerator()
I am looking to create an IEnumerable wrapper from it
The following works, but is there a better way?
(for instance, a way to not have to specify IEnumerable interface whose implementation can derives from IEnumerable)
member this.ToEnumerableElements():IEnumerable<Element> = {
new IEnumerable<Element> with
member anon.GetEnumerator() :IEnumerator<Element> = this.GetEnumerator()
member anon.GetEnumerator() :IEnumerator = this.GetEnumerator() :> IEnumerator
}
If you want a ToEnumerable method you shouldn't create a GetEnumerator method too. Generally, calling GetEnumerator directly is a code smell anyway.
type Bloomberglp.Blpapi.Element with
member this.ToEnumerable() = Seq.init this.NumElements this.GetElement
With this method in place, you can use the Seq module for most operations and should never have to call GetEnumerator directly.
For example:
elmt.ToEnumerable() |> Seq.iter (printfn "%O")

Resources