What on earth is this?
 Thomas Fischbacher
[
Home
]
[ Index:
by date

by threads
]
[ Message by date: previous  next ] [ Message in thread: previous  next ] [ Thread: previous  next ]
[ Message by date: previous  next ] [ Message in thread: previous  next ] [ Thread: previous  next ]
Date:   (:) 
From:  Thomas Fischbacher <Thomas.Fischbacher@P...> 
Subject:  What on earth is this? 
Maybe I just need a good night of sleep, maybe I overlooked something really dumb and rather should have asked on the beginner's list. Anyway, I find the behaviour demonstrated below quite confusing. Why don't the definitions ###_v1 and ###_v2 work? Any idea, anyone? ===> (* (C) T. Fischbacher, 2005  Demonstrating a simple form of memoizing... *) #load "unix.cma";; let timing ?(tagfun= fun _ > "Time passed: ") ?(channel=stdout) f x = let tag = tagfun x in let t0 = Unix.gettimeofday () in let result = f x in let t1 = Unix.gettimeofday () in let () = Printf.fprintf channel "%s%f sec\n%!" tag (t1.t0) in result ;; let rec fibonacci n = if n < 2 then 1 else fibonacci (n1) + fibonacci (n2) ;; (* # timing fibonacci 35;; Time passed: 4.254157 sec  : int = 14930352 *) let memoized ht f arg = try Hashtbl.find ht arg with  Not_found > let result = f arg in let () = Hashtbl.add ht arg result in result ;; let rec mem_fibonacci_v1 = let mem = Hashtbl.create 10 in memoized mem (fun n > if n < 2 then 1 else mem_fibonacci_v1 (n1) + mem_fibonacci_v1 (n2)) ;; (* Error: "This kind of expression is not allowed as righthand side of `let rec'" *) let mem_fibonacci_v2 = let mem = Hashtbl.create 10 in let rec mf = memoized mem (fun n > if n < 2 then 1 else (mf (n1)) + (mf (n2))) in mf ;; (* Error: "This kind of expression is not allowed as righthand side of `let rec'" *) let mem_fibonacci_v3 = let mem = Hashtbl.create 10 in let mf yfp = memoized mem (fun n > if n < 2 then 1 else yfp () (n1) + yfp () (n2)) in let rec yc x = x (fun () > (yc x)) in yc mf ;; (* This definition worked. And indeed: # timing mem_fibonacci_v3 35;; Time passed: 0.000149 sec  : int = 14930352 # timing mem_fibonacci_v3 35;; Time passed: 0.000005 sec  : int = 14930352 # *) <===  regards, tf@cip.physik.unimuenchen.de (o_ Thomas Fischbacher  http://www.cip.physik.unimuenchen.de/~tf //\ (lambda (n) ((lambda (p q r) (p p q r)) (lambda (g x y) V_/_ (if (= x 0) y (g g ( x 1) (* x y)))) n 1)) (Debian GNU)