lkahtz
lkahtz

Reputation: 4796

What is wrong with this imperative version of factorial function in 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
#

Upvotes: 3

Views: 436

Answers (1)

sepp2k
sepp2k

Reputation: 370455

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.

Upvotes: 7

Related Questions