Nathan
Nathan

Reputation: 3165

ocamlc is failing when I don't use double semicolons

I'm attempting to get into OCaml and I'm having an issue compiling code.

let area_of_ring inner_radius outer_radius =
    let pi = acos (-1.) in
    let area_of_circle r = pi *. r *. r in
    area_of_circle outer_radius -. area_of_circle inner_radius

Printf.printf "Area of ring: %f\n" (area_of_ring 1. 3.)

Attempting to compile that code with ocamlc -o all all.ml gives me the following error:

File "all.ml", line 4, characters 35-49:
Error: This function has type float -> float
   It is applied to too many arguments; maybe you forgot a `;'.

However, if I type it out in top-level or add double semicolons, the code runs just fine...

# let area_of_ring inner_radius outer_radius =
      let pi = acos (-1.) in
      let area_of_circle r = pi *. r *. r in
      area_of_circle outer_radius -. area_of_circle inner_radius;;
val area_of_ring : float -> float -> float = <fun>

# Printf.printf "Area of ring: %f\n" (area_of_ring 1. 3.);;
Area of ring: 25.132741
- : unit = ()

Can someone explain what's going on? It's not crucial, but I would like to be able to write my program without double semicolons everywhere.

Upvotes: 3

Views: 58

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

Without the two semicolons, you have several expressions next to each other. The first is the call to area_of_circle in your function area_of_ring, the second is inner_radius, the third is Printf.printf, and so on. This isn't meaningful, for reasons the compiler is trying to explain.

As in many languages, spaces and newlines aren't meaningful to OCaml syntax. So the compiler sees it as one large expression.

A good idiom for writing top-level expressions like your Printf.printf is like this:

let () = Printf.printf "Area of ring: %f\n" (area_of_ring 1. 3.)

(This is how I write my code.)

Upvotes: 5

Related Questions