Simple OCaml program

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

Obviously, you are creating an integer N so that the user enters its value. Create a sum variable of type int . Have a for loop that will add N to sum , and then decrease the value of N by one. The loop will work until N greater than 1. I have no idea how to do this in the OCaml syntax.

Any help would be greatly appreciated.

+4
source share
1 answer

A way to describe your algorithm is how you usually implement it in C ++ or Java. You can write it in OCaml as well, but the idiomatic path will be a recursive function that does not mutate the 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) 

Call with: print_sum 0 11 ;;

To write a recursive function:

  • First think about the base case when there is no need to recursively. This will save you from forgetting (here, this is the case n <= 0 )
  • General case: how can you come one step closer to the basic case already written? Here it calls the function n-1 .
+9
source

All Articles