Summation OCaml

I am trying to make a function in OCaml that performs the function of summing in math. I tried this:

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

However, I get an error message - "Characters 41-44: else f * sum (n + 1) mf ;; Error: the sum of the unrelated value and the sum is underlined (has pointers to carrots pointing to it)

I looked at this: OCaml Simple Actions This is the same question, but I see many other things that I don’t have. For example, for my n = m case, I don't have fn, and then otherwise I don't have f m.

Why do you need fn if you want the function to return an integer? D: What is the problem !? Thanks in advance.

+4
source share
3 answers

You forgot rec .

let rec sum nmf = ...

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

+13
source
  • You must use the let keyword to introduce a new function and let rec when this function is recursive.

  • Why is the first argument called f ? If this is a function, you must apply it to something.

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

At the moment your code is equivalent

 let sum abc = 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 
+4
source
 # 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 
0
source

All Articles