PlsWork
PlsWork

Reputation: 2158

Ocaml "longest match" rule : "minus" operator parsed as binary or unary

The function I have:

let increment n = n+1;;

My call to the function:

let x = increment -5;;

The error I get:

let x = increment -5;;
        ^^^^^^^^^
Error: This expression has type int -> int
       but an expression was expected of type int`

Why doesn't x = -4 after the function call?

I tried finding the answer myself and I ended up here: http://caml.inria.fr/pub/docs/manual-ocaml-4.00/lex.html#prefix-symbol

The term "longest match rule" is used in the section Ambiguities, I assume that a clarification of that term would solve my issue?

Upvotes: 0

Views: 226

Answers (2)

Reimer Behrends
Reimer Behrends

Reputation: 8720

An alternative to using parentheses, as suggested in the other answer, is to use the @@ application operator, e.g.:

let increment n = n + 1
let x = increment @@ -5

Briefly, f @@ x is the same as f x, but the @@ operator has lower precdence than arithmetic operations, while function application has higher precedence. Thus, using the application operator allows you to omit parentheses.

Sometimes, the reverse application operator |> can be more idiomatic; it is typically used to "pipe" an expression through one or more function applications.

Example:

let increment n = n + 1
let x = -5 |> increment
let clamp x low high = x |> min high |> max low

Upvotes: 1

Lhooq
Lhooq

Reputation: 4441

The problem is easy, - is considered here as the binary operator minus so OCaml is reading it as increment minus 5 (increment and 5 are the two operands) when what you'd want is increment the number (minus 5) (increment being a function).

Just write increment (-5) and the job's done.

Upvotes: 2

Related Questions