ocaml

Solving OCaml Problems


Define a function sign which given an integer returns 1 if it is positive, -1 if it is negative and 0 if it is zero.

my solutions

solution 1

let sign i = if i!=0 then (if i<0 then -1 else 1) else 0;;

solution 2

let sign x =
  if x = 0 then 0 else
    if x<0 then -1 else 1;;

It doesn't work for negative numbers but it works for positive numbers and zero.

I receive the following error

Error: This expression has type int -> int
       but an expression was expected of type int

Solution

  • As noted in comments, your functions look correct.

    You are most likely calling it as: sign -1 which is parsed as (sign) - (1). Thus the compiler complaint that a function was encountered where an expression of type int was expected.

    This can be overcome in two ways. Using parens to disambiguate, or using the ~- prefix.

    sign (-1)
    
    sign ~-1
    

    As an additional note, this can also be implemented in terms of a comparison to 0.

    let sign n = compare n 0
    

    Or if you're of a slightly more Haskell-y mindset.

    let sign = Fun.flip compare 0
    

    As a further aside, I would suggest the following style:

    let sign x =
      if x = 0 then 0 
      else if x < 0 then -1 
      else 1
    

    As opposed to:

    let sign x =
      if x = 0 then 0 else
        if x<0 then -1 else 1