Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A simple OCaml program

Tags:

ocaml

I want to learn a bit of OCaml, just to get a taste of a programming language other than C++ and Java. I will be very greatful if you help me with the following program: basically the user inputs a positive integer. The sum of all integers from N to 0 is printed.

Obviously you create an integer N, let the user enter its value. Create a variable sum of type int. Have a for loop which will add N to sum and then decrement N's value by one. The loop will run while N is greater than 1. I have no idea how to do this in OCaml's syntax though.

Any help would be highly appreciated.

like image 401
Stanimirovv Avatar asked Jan 15 '23 14:01

Stanimirovv


1 Answers

The way you describe your algorithm is how you would typically implement it in C++ or in Java. You can write it the same way in OCaml, but the idiomatic way would be a recursive function that does not mutate variables, as follows:

let rec print_sum acc n =
  if n <= 0
  then Printf.printf "Sum: %d\n" acc
  else print_sum (acc + n) (n - 1)

Invoke with: print_sum 0 11 ;;

To write a recursive function:

  1. First think of the base case when it is not necessary to recurse. This will save you from forgetting it (here, it's the case n <= 0)
  2. The general case: how can you get one step closer to the base case already written? Here it's by invoking the function with n-1.
like image 67
Pascal Cuoq Avatar answered Jan 22 '23 04:01

Pascal Cuoq