memoizeMonadic seems to be quite restrictive(only accept IdentifyBuilder).

not sure what you want to achieve
By on 1/5/2010 11:29 PM ()
Good point.

I was trying to something like "Monadic Memoization Mixins" (but without the mix-in concept) ([]).

But maybe I need to try it on a monad that does something.

By on 1/5/2010 11:59 PM ()
A bit further reading leads me to believe that if I want my memoization to to be held by the state of the monad and if I also want to support recursion, I want to write continuation and state monad that are compatible. I'll post that when it works.
By on 1/6/2010 1:21 PM ()
Here the stateless monadic memoization code. I based it on the state continuation monad, the code is inspired from this posting []

Trying to understand how this monad works, I found this work on monadic reflection by A. Filinsky ([] It is very interesting.

(By the way, can someone tell me how to post code so that it is readable? )

type  csm<'s,'m,'w> = 's -> ('s -> 'm -> 'w) -> 'w

let ret a  = fun s k -> k s a
let bind a f = fun s k -> a s (fun s2 b -> (f b) s2 k)
let get = fun (s:'s) k -> k s s // ret s
let set v = fun _ k -> k v ()
let runCS m = fun s0 -> m s0 (fun _ v -> v)
let runCS2 m = fun s0 -> m s0 (fun s v -> (s,v))

// I don't know if this is correct
let CallCC f  =
    (fun s0 ka -> f (fun a -> (fun s1 kb -> kb a s1) s0 ka))

type CSBuilder() =
    member b.Bind(m,f)  = bind m f
    member b.Return(x) = ret x

let memoize f x = 
    bind get (fun (omap:Map<_,_> option) ->
        let computeAndAdd (toMap:Map<_,_>) =
            bind (f x) (fun v ->
            bind (set (Some (toMap.Add(x,v)))) (fun() ->
            ret v
        match omap with
        | Some map ->
            let d = map.TryFind x
            match d with
            | None ->
                computeAndAdd map
            | Some v ->
                ret v
        | None ->
            computeAndAdd Map.empty

let csm = new CSBuilder()
let plus1 x = csm { return x+1 }
let mplus1 = memoize2 plus1

let plus x =
    csm {
        let! rs = mplus1 x
        let! r = mplus1 rs
        return r

let plusplus x = 
    csm {
        let! y= plus x
        let! z= plus x
        return z
    let (map, r) = runCS2 (plusplus 4) None
    printf "%A" map
    System.Console.ReadLine() |> ignore
By on 1/12/2010 12:42 AM ()
(By the way, can someone tell me how to post code so that it is readable? )

I've seen this question a bit lately, so I posted this:

By on 1/12/2010 9:25 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us
Built with WebSharper