Ocaml Int and Negative Values

Given this piece of OCaml code:

let rec range a b =
  if a > b then []
  else a :: range (a+1) b
  ;;

The Repl tells me what this type is:

val range : int -> int -> int list = <fun>

Introducing it, for example:

range 0 4;;

returns a list:

- : int list = [0; 1; 2; 3; 4]

However, subject to input

range -4 2;;

Gives an error:

Characters 0-5:
  range -4 1;;
 ^^^^^
This expression has type int -> int -> int list but is here used with type int.

What am I trying to say?

+5
source share
2 answers

when you type

range -4 2;;

you need to remember that it -is a function, an infix function, not a unary negation.

To make unary negation, you can do one of two things: 1) preceede - sign with ~, for example ~ -4 or use brackets.

+7
source

I just realized what I need to wrap

-4 in parenthesis

those. call:

range (-4) 0;;

gives:

- : int list = [-4; -3; -2; -1; 0]

I will leave this question if someone else runs into the same problem.

, , , - , 4.

: OCaml .

+5

All Articles