1

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);;
3
  • 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 Commented Apr 11, 2021 at 15:37
  • @glennsl we are only using numbers 1-100. Also I have already corrected it using advice given below. Thank you though! Commented Apr 11, 2021 at 18:03
  • 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. Commented Apr 11, 2021 at 18:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Even with that modification, it looks like this is still infinitely recursive for any case where n is 0.
@ChrisDutton we are only using numbers 1-100.
@Jeffrey thank you for your reply. I believe that I was confused at first about what needed to be found - remainder or modulo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.