ocaml - Implementing a simple factorial function using continuation passing style -
i'm trying implement function returns factorial in ocaml don't know if i'm using continuation passing style:
let fact n = let rec factorial n cont = match n | 0 -> cont () | _ -> factorial (n-1) (fun () -> cont () * n) in factorial n (fun () -> 1)
it seems me i'm not delaying computation displacing computation in code.
well, code interesting. not usual, tail-recursive, work. show "usual" way of doing cps. usually, returning function using continuation, why idea name continuation return
. also, start identity function initial value continuation. , finally, you're using continuation assembly, build answer.
let factorial n = let rec loop n return = match n | 0 -> return 1 | n -> return (loop (n-1) (fun x -> x * n)) in loop n (fun x -> x)
so in example, pass continuation accumulate and, finally, build answer.
to summarize, 3 simple rules:
- return continuation
- start identity
- update continuation on each step.
but anyway, function interesting solution. aindeed, you're using building lazy list of closures. in each step of computation, you're creating closure, uses previous closure , multiplies n. when reach 0, call chain of closures. so, o(n) in space, instead of stack, you're using heap. of course, solution o(n) in space. i'm clarifying.
Comments
Post a Comment