Reputation: 5
I'm an OCaml beginner using OCaml 4.12.0 on MacOS. This let
expression:
let gg x y = (x -. y) < 5.0
at the toplevel results in:
Error: This expression has type float but an expression was expected of type
int
Explicitly adding type information, etc., did not fix the problem. In frustration, I visited the online REPL TryOCaml, and the expression was accepted without error, returning the type signature of:
val f : float -> float -> bool = <fun>
as expected. But I'd like utop
to work on the Mac - what am I missing?
Upvotes: 0
Views: 303
Reputation: 35210
When you use Base
(or Core
, or Core_kernel
and other Janestreet standard libraries) the comparison operator and its friends (like various equality operators) work only on values of type int. For all other values you have to use specialized comparison operators provided by the module that implements that type, e.g., to compare two floats,
Float.(3.14 < 4.14)
to compare strings,
String.("hello" <> "world")
And, using your example,
let gg x y = Float.(x -. y < 5.0)
or even
let gg x y = Float.(x - y < 5.0)
Notice that we don't need to use the ugly -.
operators anymore and can use -
(and other arithmetic operators) as they are all defined specifically for float in module Float.
Besides, the notation Foo.(<expr>)
is a short-hand for let open Foo in <expr>
and is called local open.
Upvotes: 0
Reputation: 66808
Very possibly you're using a library that overrides the built-in meaning of <
in OCaml. Some people (not me) think the polymorphic comparison operators are a problem.
One problem with this (IMHO) is that it causes confusing results like this.
For example, the Jane Street Base library is documented as overriding the polymorphic comparison operators: https://ocaml.janestreet.com/ocaml-core/latest/doc/base/index.html
Upvotes: 1