Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memoize a function of type () -> 'a

Tags:

f#

unit-type

This memoize function fails on any functions of type () -> 'a at runtime with a Null-Argument-Exception.

let memoize f =
    let cache = System.Collections.Generic.Dictionary()
    fun x ->
        if cache.ContainsKey(x) then 
            cache.[x]
        else 
            let res = f x
            cache.[x] <- res
            res

Is there a way to write a memoize function that also works for a () -> 'a ?

(My only alternative for now is using a Lazy type. calling x.Force() to get the value.)

like image 784
Goswin Rothenthal Avatar asked Dec 12 '13 16:12

Goswin Rothenthal


1 Answers

I just found that the last memoize function on the same website using Map instead of Dictionary works for 'a Option -> 'b and () -> 'a too:

let memoize1 f =
    let cache = ref Map.empty

    fun x ->
        match cache.Value.TryFind(x) with
        | Some res -> res
        | None ->
            let res = f x
            cache.Value <- cache.Value.Add(x, res)
            res
like image 55
Goswin Rothenthal Avatar answered Oct 31 '22 02:10

Goswin Rothenthal