Hi, I\'m writing a program in Ocaml which is a tail recursive version of the pow
ID: 3744395 • Letter: H
Question
Hi,
I'm writing a program in Ocaml which is a tail recursive version of the power function. The function is pow_tl : int -> int -> int -> int and takes as input a base n, and exponent k, and an accumulator to build up the result. I have written this code:
let pow_tl n k =
let rec aux n k acc =
if k == 0 then 1 else
if k == 1 then n else
n * aux n (k - 1)
in
aux n k 1
But I get the error, "This expression has type 'a -> int but an expression was expected of type int" and I'm not sure why. Any help would be appreciated!
Thanks!
Explanation / Answer
OCaml has no statements. It only has expressions. For an if expression to make sense, the then and else parts have to be the same type. In your code the then part is 1. I.e., it has type int. In the else part you have a if condition, which is invalid for OCAML. That is what the compiler is saying that the else part is also expected to be of type int since then part is containing int.
Refer to this link for better understanding:- https://stackoverflow.com/questions/19340661/this-expression-has-type-unit-but-an-expression-was-expected-of-type-int
Refer to the link how power function is computed (you need to modify the power function slightly as per your requirements, but am definitely sure, it will help you):- https://ocaml.org/learn/taste.html#The-power-of-functions.
Please let me know in case of any clarifications required. Thanks!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.