4
votes

I'm trying to make a function in OCaml which does the summation function in math. I tried this:

sum n m f =
    if n = 0 then 0
    else if n > m then f
    else f + sum (n + 1) m f;;

However, I get an error - "Characters 41-44: else f * sum(n + 1) m f;; Error: Unbound value sum and sum is underlined (has carrot signs pointing to it)

I looked at this: Simple OCaml exercise It's the same question, but I see a lot of other things that I do not have. For example, for my n = m case, I do not have f n and then in the else case, I do not have f m.

Why do you need f n if you want the function to return an integer? D: What's the problem!? Thanks in advance.

3
on an unrelated note, your function is not tail-recursive. It will use up stack space equal to the range of the numbers. You might want to make it tail-recursive, by having an internal helper function that passes along an accumulator - newacct
(succ n) is more natural than (n + 1) in Ocaml - Valentine Zakharenko

3 Answers

13
votes

You forgot rec.

let rec sum n m f = ...

For recursive functions, you must manually include the "rec" keyword.

4
votes
  1. You must use the keyword let to introduce a new function, and let rec when this function is recursive.

  2. Why is the first argument named f? If it is a function you should apply it to something.

  3. if n = 0 then 0 what a strange convention! Are you sure you want this? Idem for if n > m then f

For now, your code is equivalent to

let sum a b c =
  if a = 0 then 0
  else if a > b then c
  else if a < 0 then min (-a*c) ((b-a+1)*c)
  else (b-a+1)*c
0
votes
# let rec sum c = function
    (0,_)          -> 0
  | (n,m) when n>m -> c
  | (n,m)          -> c + sum c (n+1,m)
        ;;

# sum 2 (3,5);;
- : int = 8