1
votes

I have rewritten Scheme code that computes integer log, base 2 in OCaml. Upon compilation, I repeatedly get an error that says "Stack overflow during evaluation (looping recursion?).".

I am a beginner with both of these languages as this is an assignment for one of my classes.

Scheme code:

(define log2
  (lambda (n)
    (if (= n 1) 1 (+ 1 (log2 (quotient n 2))))))

OCaml code:

let rec log2 n = 
  match n with 
  | 1 -> 1 
  | n -> 1 + log2 (n mod 2);;
1
Can you explain steb-by-step how you think each function should work? I don't know scheme. but it's pretty obvious to me that the OCaml code will get stuck on 0 mod 2 = 0 - glennsl
@glennsl we are only using numbers 1-100. Also I have already corrected it using advice given below. Thank you though! - aleathom
It's recursion., so0 isn't required as initial input. 2 mod 2 = 0, which leads to 0 mod 0 = 0, and then around you go ad infinitum. Any input that eventually goes through 2 will therefore recurse infinitely. - glennsl

1 Answers

1
votes

The scheme code has quotient and you have rendered this in OCaml with mod. This seems wrong. You want integer division, I would assume, which is / in OCaml.