开发者

Ocaml Int and negative values

开发者 https://www.devze.com 2022-12-09 01:42 出处:网络
Given this snippet of OCaml code: let rec ra开发者_如何学编程nge a b = if a > b then [] else a :: range (a+1) b

Given this snippet of OCaml code:

let rec ra开发者_如何学编程nge a b =
  if a > b then []
  else a :: range (a+1) b
  ;;

The Repl tells me that it's type is:

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

Giving it inputs such as:

range 0 4;;

gives back the list:

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

However providing the input

range -4 2;;

Gives the error:

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

What is this trying to tell me?


when you type,

range -4 2;;

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

To do unary negation you can do one of two things, 1) preceede - sign with a ~, like ~-4, or use parenthesis.


I just realized that I need to wrap the

-4 in parenthesis

ie calling:

range (-4) 0;;

Gives:

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

I'll leave this question up incase anyone else comes across the same issue.

Just to summarize the issue is that - is interpreted as a function and not as the sign of the token 4.

You can see: OCaml language issues for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号