F# Memoization Within a Class - functional-programming

I am struggling to make Memoization work in F# when the function I want to Memoize is a member of a class.
The Dictionary appears to be cleared every time - and so nothing is actually memoized, the result is always recomputed. The same code but with the key functions outside of a calls of a class works just fine.
open System
module TestMemo
open System
open System.IO
open System.Collections.Generic
let Memoize f =
let dict = Dictionary<_, _>()
fun c ->
let exists, value = dict.TryGetValue c
match exists with
| true -> value
| _ ->
let value = f c
dict.Add(c, value)
value
type MyClass() as this =
let rec AddToOne(x) = if x <= 1 then 1 else x + AddToOne(x-1)
let rec AddToOneSkip(x) = if x <= 1 then 1 else x + AddToOneSkip(x-2)
member this.MemoAddToOne = Memoize AddToOne
member this.MemoAddToOneSkip = Memoize AddToOneSkip
[<EntryPoint>]
let main args =
let x = new MyClass()
for i in 1..100000 do
Console.WriteLine(x.MemoAddToOneSkip(i))
for i in 1..100000 do
Console.WriteLine(x.MemoAddToOne(i))
0

When you write this:
member this.MemoAddToOne = Memoize AddToOne
That's not a "value", but a property. A property in .NET is a pair of functions (get + set), but there are also read-only properties, which have only "get". And that's what you created here. They're basically functions in disguise.
So every time somebody accesses x.MemoAddToOne, they're basically calling a function, so every time the body is executed anew, thus making a new call to Memoize every time.
To avoid this, create the memoizers once and then return them from the property getter:
let memoAddToOne = Memoize AddToOne
member this.MemoAddToOne = memoAddToOne
Or use a shortcut for the same thing:
member val MemoAddToOne = Memoize AddToOne

Related

F# Subclasses and Memoization

I am struggling to get memoization to work when the memoized function is an abstract function which is overridden/defined within a subclass rather than the parent class.
When the memoized function is defined in the parent class, it works fine.
When I define the signature of the memoized function in the parent class, and then override it in the subclass, I can't figure out the appropriate syntax.
open System
let Memoize f =
let dict = Dictionary<_, _>()
fun c ->
let exists, value = dict.TryGetValue c
match exists with
| true -> value
| _ ->
let value = f c
dict.Add(c, value)
value
[<AbstractClass>]
type ParentClass() as this =
let someparam = DateTime(2022,1,1)
let SlowNumber100InParentClass(t) =
System.Threading.Thread.Sleep(1000)
100.0
member val MemoParentClassSlow100 = Memoize SlowNumber100InParentClass
member this.MultiplyBy2A = (this.MemoParentClassSlow100 someparam) * 2.0
abstract MemoSubClassSlow100: DateTime->float
member this.MultiplyBy2B = (this.MemoSubClassSlow100 someparam) * 2.0
type MyClass() as this =
inherit ParentClass()
let SlowNumber100InSubClass(t) =
System.Threading.Thread.Sleep(1000)
100.0
override this.MemoSubClassSlow100(t) = Memoize SlowNumber100InSubClass t // doesn't "memoize"
//override val MemoSubClassSlow100 = Memoize SlowNumber100InSubClass // This feels intuitive to me, but error is "No abstract property was found that corresponds to this override"
// ??? somehow else ???
[<EntryPoint>]
let main args =
let x = new MyClass()
for i in 1..10 do
Console.WriteLine(x.MultiplyBy2A) // this is fast
for i in 1..10 do
Console.WriteLine(x.MultiplyBy2B) // this is slow
0
You're very close. Just use member val in the subclass to hold the memoized function, since that member doesn't override anything in the parent class:
type MyClass() =
inherit ParentClass()
let SlowNumber100InSubClass(t) =
System.Threading.Thread.Sleep(1000)
100.0
member val MemoSubClassSlow100_ = Memoize SlowNumber100InSubClass
override this.MemoSubClassSlow100(t) = this.MemoSubClassSlow100_ t
Personally, I think let is usually preferable to member val, though:
let memoSubClassSlow100 = Memoize SlowNumber100InSubClass
override _.MemoSubClassSlow100(t) = memoSubClassSlow100 t

F# Memoization - Persist?

What's the best way to persist/save the results of memoization so it can be loaded later?
There's this standard code snippet in F# for implementing memoization:
let memoize f =
let dict = Dictionary<_, _>();
fun c ->
let exist, value = dict.TryGetValue c
match exist with
| true -> value
| _ ->
let value = f c
dict.Add(c, value)
value
let mySlowFunc x=
// something very slow
0
let myFastFunc = memoize mySlowFunc
After calling myFastFunc many times, I will have a dictionary full of results for mySlowFunc for various x's. I want to persist these results so ideally I can do something like:
let saveMemoziationResults myFastFunc "results.file" = ... // saves the dict to a file
let loadMemoziationResults "results.file" // loads the dict from a file
I can't figure out a way to "access" that dict in order to save it.
You could move dict creation to the caller, like
let memoizeBase dict =
let memoize f = …
memoize
And using it like
let dict = new…
let memoize = memoizeBase dict
// use memoize and save/load dict when needed

Moq: How to mock a function in F# without a placeholder interface?

A colleague of mine needed to test whether some F# functions are called or not a given number of times.
In Moq, you can usually do that if you have a class with virtual members or an interface (unless if this has changed, but it doesn't seem to be the case), but afaik you can hardly mock static methods with Moq for example, which in most cases is how F# functions are compiled to, at least from an IL standpoint. Or, would require to use another library to do so like AutoFake or Pose and I'm not sure the F# support is actually properly implemented.
We ended up creating a CallCounter type, which would hold the function to invoke and a variable counting the number of times this function has been invoked (a bit similar to this answer but with an actual type).
module Tests
open Foq
open Xunit
open Swensen.Unquote
type CallCounter<'Input, 'Output>(f: 'Input -> 'Output) =
let mutable count = 0
member this.Count = count
member this.Invoke(input) =
count <- count + 1
f input
type CallOutputs<'Input, 'Output>(f: 'Input -> 'Output) =
let outputs = ResizeArray()
member this.Outputs =
List.ofSeq outputs
member this.Invoke(input) =
let output = f input
outputs.Add(output)
output
let callFunDepTwice (funDep: unit -> int32) =
sprintf "%A|%A" (funDep()) (funDep())
[<Fact>]
let ``callFunDepTwice should work1``() =
let funDep = fun() -> 42
let funDepCounter = CallCounter(funDep)
let actual = callFunDepTwice funDepCounter.Invoke
test <# actual = sprintf "%A|%A" 42 42 #>
test <# funDepCounter.Count = 2 #>
I was wondering if there was something out of the box in Moq to achieve the same sort of thing?
I mean without having to rely on creating a placeholder interface with an impl. using object expressions just for the grand sake to hold the function to invoke, in order to make it compliant with Moq, like below:
type ISurrogate<'Input, 'Output> =
abstract member Invoke: 'Input -> 'Output
[<Fact>]
let ``callFunDepTwice should work2``() =
let mockConf = Mock<ISurrogate<unit, int32>>().Setup(fun x -> <# x.Invoke() #>).Returns(42)
let mock = mockConf.Create()
let actual = callFunDepTwice mock.Invoke
test <# actual = sprintf "%A|%A" 42 42 #>
Mock.Verify(<# mock.Invoke() #>, Times.exactly 2)
Unless I'm missing something, I don't see why you need any objects or interfaces. Since it's all just functions, you could make funDep just increment a locally declared mutable counter as a side effect:
[<Fact>] let ``callFunDepTwice should work1``() =
let mutable count = 0
let funDep = fun() -> count <- count + 1; 42
let actual = callFunDepTwice funDep
test <# actual = sprintf "%A|%A" 42 42 #>
test <# count = 2 #>
Mocking frameworks may be occasionally useful in F# in some corner cases, but in general, I see their whole purpose as compensating for the deficiencies of OOP. Unless you're interacting with some .NET library that uses objects and interfaces, chances are you can do without them.

Handle recursive function within an other function ocaml

If I have one or more recursive functions inside an Ocaml function how can I call them without exit from the main function taking their value as return of the main function?
I'm new in Ocaml so I'll try to explain me better...
If I have :
let function =
let rec recursive1 = ...
...
let rec recursive2 = ...
...
How can I call them inside function to tell it "Hey, do you see this recursive function? Now call it and takes its value."
Because my problem is that Ocaml as return of my functions sees Unit instead of the right return.
I will post the code below :
let change k v list_ =
let rec support k v list_ =
match list_ with
| [] -> []
| (i,value) :: tl -> if i = k
then (k,v) :: tl
else (i,value) :: support k v tl in
let inserted = support k v list_ in inserted
let () =
let k = [ (1,"ciao");(2,"Hola");(3,"Salut") ] in
change 2 "Aufwidersen" k
Change takes as input a key, a value and a (int * string )list and should return the same list of the input but changing the value linked to the key selected ( if in list ).
support, instead, makes the dirty job. It builds a new list and when k is found i = k it changes value and attach the tile, closing the function.
The return of change is unit when it should be (int * string) list. I think because inserted isn't taken as return of the function.
change does not return unit. The error in fact tells you exactly the opposite, that it returns (int * string) list but that it expects unit. And it expects unit because you're assigning it to a () pattern.
I don't know what you actually intend to do with the return value, as right now you don't seem to care about it, but you can fix the error by just assigning it to a name:
let result: (int * string) list =
let k = [ (1,"ciao");(2,"Hola");(3,"Salut") ] in
change 2 "Aufwidersen" k
Since it's not used I've added a type annotation to make sure we're getting what we expect here, as otherwise result could be anything and the compiler wouldn't complain. You don't typically need this if you're going to use result however, as you'd then get an error if the type doesn't unify with its usage.

How to get the name of a higher order function in F#? [duplicate]

How can I create a function called getFuncName that takes a function of type (unit -> 'a) and returns its name.
I was talking to one of the C# devs and they said you could use the .Method property on a Func type as shown in an example here.
I tried to convert this to F# :
for example convert (unit -> 'a) to a type Func<_> then call the property on it but it always returns the string "Invoke".
let getFuncName f =
let fFunc = System.Func<_>(fun _ -> f())
fFunc.Method.Name
let customFunc() = 1.0
// Returns "Invoke" but I want it to return "customFunc"
getFuncName customFunc
A bit of background to this problem is:
I have created an array of functions of type (unit -> Deedle.Frame). I now want to cycle through those functions invoking them and saving them to csv with the csv name having the same name as the function. Some hypothetical code is below:
let generators : (unit -> Frame<int, string>) array = ...
generators
|> Array.iter (fun generator -> generator().SaveCsv(sprintf "%s\%s.csv" __SOURCE_DIRECTORY__ (getFuncName generator)))
This is being used in a scripting sense rather than as application code.
Not sure how you searched for information, but the first query to the search engine gave me this response:
let getFuncName f =
let type' = f.GetType()
let method' = type'.GetMethods() |> Array.find (fun m -> m.Name="Invoke")
let il = method'.GetMethodBody().GetILAsByteArray()
let methodCodes = [byte OpCodes.Call.Value;byte OpCodes.Callvirt.Value]
let position = il |> Array.findIndex(fun x -> methodCodes |> List.exists ((=)x))
let metadataToken = BitConverter.ToInt32(il, position+1)
let actualMethod = type'.Module.ResolveMethod metadataToken
actualMethod.Name
Unfortunately, this code only works when F# compiler does not inline function body into calling method.
Taken from here
Although there may be a more simple way.

Resources