# Search through a monotonic function.

I have just been doing some mental exercises, from the draft book of J. Hickey, *Introduction to Objective Caml* on monotonic functions. These functions maintain their trend. So is either increasing or decreasing as moves from to . For the case when the function is increasing, we have for . Furthermore, for this case, and . We are asked to write a search program such that given a function and , the program returns the smallest argument . One’s initial impression might lead to thinking that the solution is complex but see the code below on how it turned out to be much simpler than expected. The elegance of this language is addicting.

let rec search f n =

if (f (n – 1)) < (f (n)) && f (n) > 0 then

search f (n – 1)

else

n + 1;;

Test functions:

`# let f x = x + 1;;`

# search f 4;;

- : int = 0

# let f x = x * 2;;

# search f 4;;

- : int = 1

# let f x = x * x;;

# search f 4;;

- : int = 1

# let f x = 3 * x + 2;;

# search f 4;;

- : int = 0

If you are not surprised how concise you can be using this language then, my wish is for you to realise one day what I am talking about! 😉