Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this imperative version of factorial function in ocaml?

Tags:

ocaml

let impfac i = 
  let l = ref i in
  let result = ref 1 in
  let k = ref 2 in
  while !k < !l do
    result := !result * !k
      k:=!k+1
  done;
  !result

The error message is:

let impfac i = 
  let l = ref i in
  let result = ref 1 in
  let k = ref 2 in
  while !k < !l do
    result := !result * !k
      k:=!k+1
  done;
  !result;;
                Characters 121-123:
      result := !result * !k
                          ^^
Error: This expression is not a function; it cannot be applied
#
like image 656
lkahtz Avatar asked Dec 14 '25 16:12

lkahtz


1 Answers

result := !result * !k
  k:=!k+1

You're missing a semicolon at the end of the first line. Because of this it is read as:

result := !result * (!k k:=!k+1)

i.e. it thinks you're trying to call !k with k:=!k+1 as its argument.

This is also why your editor indented the line with k := !k+1 farther to the right than the line above it. That should have been the first sign that something's wrong with the syntax.

like image 187
sepp2k Avatar answered Dec 16 '25 06:12

sepp2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!