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:

  1. return continuation
  2. start identity
  3. 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

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -