Regarding the style of the recursive solution: you will want to separate the caching from the function logic and then compose the cached function from a generic caching function and your logic solution. Assuming you have a proper function memoize, your function p could look like:

1
2
3
4
5
6
7
8
9
10
let p =
      let ps ps x y =
            match x, y with
            | 0, _ -> 0.0
            | _, 0 -> 1.0
            | _ ->
                  let px = float(x)/float(x+y)
                  let py = float(y)/float(x+y)
                  (py+1.0) * px * (ps (x-1) y) + py**2.0 * (ps x (y-1))
      memoize ps
By on 2/3/2009 3:13 AM ()

Just out of curiosity, how would you write such a definition of memoize?

By on 2/3/2009 8:11 AM ()

Just out of curiosity, how would you write such a definition of memoize?

Like this [:)]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#light
#nowarn "40"

open System.Collections.Generic

module Memo=
    let Cached f=
      let cache=new Dictionary<_,_>()
        fun a -> match cache.TryGetValue a with
                          | true, result -> result
                          | _ -> let result=f a
                                        lock cache (fun () -> cache.[ a ] <- result)
                                        result
    let Cached2 f=
        fun a b -> Cached (fun (a,b) -> f a b) (a,b)

    let CachedRec f=
        let rec r=f (fun a->r a) |> Cached in r
    let CachedRec2 f=
        let rec r=f (fun a b->r a b) |> Cached2 in r
let memoize = Memo.CachedRec2
By on 2/3/2009 11:14 AM ()

It's possible without recursion as well:

1
2
3
4
5
#light

let p x y = x / ((y+1.) * (x+y))

print_any (p 90. 10.)
By on 2/3/2009 3:04 AM ()

The only thing I can see is, that you can calc "py" by "let py = 1.0 - px"

the rest looks fine for me - of course there is not much functional programming going on...

By on 2/3/2009 2:22 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper