Question

Here is what I am trying to do, given z with the signature that 'a -> 'a,

let z(a)=
  if(a=0) then
    0
  else
    a * a;;

if I were to call repeat as, repeat(2, f, 2);; then the answer should be too, since f should be called twice with 2, as in f(f(2) the answer should be 16.

Était-ce utile?

La solution

I think the problem might be that when you are defining a recursive function you need to tell OCaml using the rec keyword.

Try changing the code to:

let f a =
  if a = 0 then
    0
  else
    a * a

let rec repeathelper n f answer accum =
  if n = accum then
    answer
  else
    repeathelper n f (f answer) (accum+1)

let repeat n f x = repeathelper n (f 0) 0 0
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top