I am learning Jason Hickey's Introduction to Objective Caml.
After I learned Chapter 3, I seem to understand how the let
and fun
work. But still, I have troubles to write my own fun
.
Here is an example problem I am facing.
Write a function sum that, given two integer bounds n and m and a function
f, computes a summation (no for loop allowed). i.e., sum n m f = f(n) + f(n+1) + ... + f(m)
So, how should I start to think about producing this function sum?
In Java or normal programming language, it is easy.
Since here for loop is not allowed, so I guess I should do it in let rec
way?
Something like this:
let rec sum n m f = fun i -> ....
I need an i
to be a cursor?
Whatever, I can't continue to think out.
Can anyone point a road for me to produce a OCaml fun?
This is my final solution:
let rec sum n m f = if n <= m then (f n)+(sum n+1 m f) else 0;;
but of course, it is wrong. The error is Error: This expression has type 'a -> ('a -> int) -> 'b
but an expression was expected of type int
Why? and what is 'a?