为什么指数运算符在OCaml中使用浮点变量?
为什么指数运算符在OCaml中使用浮点变量? 它不应该也允许int变量吗为什么指数运算符在OCaml中使用浮点变量?,ocaml,Ocaml,为什么指数运算符在OCaml中使用浮点变量? 它不应该也允许int变量吗 # 3**3;; Error: This expression has type int but an expression was expected of type float 作品: # 3.0**3.0;; - : float = 27. 您可以使用int let int_exp x y = (float_of_int x) ** (float_of_int y) |> int_of_fl
# 3**3;;
Error: This expression has type int but an expression was expected of type
float
作品:
# 3.0**3.0;;
- : float = 27.
您可以使用
int
let int_exp x y = (float_of_int x) ** (float_of_int y) |> int_of_float
因此,现有的答案是关于如何绕过这一点,而不是为什么会这样。主要原因有两个: 1) OCaml没有操作符别名。不能有两个运算符执行“相同的操作”,但类型不同。这意味着只有一种数字、整数或浮点数(或其他表示形式)可以使用标准**接口 2)
pow()
另外,为了解决这个问题,如果您使用的是附带的OCaml电池,那么有一个为整数定义的函数。有一个类似的问题:
下面是一个可能的整数幂运算的尾部递归实现:
let is_even n =
n mod 2 = 0
(* https://en.wikipedia.org/wiki/Exponentiation_by_squaring *)
let pow base exponent =
if exponent < 0 then invalid_arg "exponent can not be negative" else
let rec aux accumulator base = function
| 0 -> accumulator
| 1 -> base * accumulator
| e when is_even e -> aux accumulator (base * base) (e / 2)
| e -> aux (base * accumulator) (base * base) ((e - 1) / 2) in
aux 1 base exponent
设为偶数=
n模2=0
(* https://en.wikipedia.org/wiki/Exponentiation_by_squaring *)
设pow基指数=
如果指数<0,则无效参数“指数不能为负”否则
让rec aux累加器底座=功能
|0->累加器
|1->基础*蓄能器
|e何时为偶数e->辅助累加器(基本*基本)(e/2)
|e->aux(基本*累加器)(基本*基本)((e-1)/2)输入
辅助1基指数
我对Ocaml有点陌生。。。请你解释一下这部分好吗我不知道它为什么在那里,或者它是做什么的。谢谢。哦,好的,我刚拿到。。。但为什么会出现错误呢设int_exp x y=(float_of_int x)**(float_of_int y)|>int_of_float;;设int_exp x y=(float_of_int x)**(float_of_int y)|>int_of_float;;错误:未绑定值|>@SadSeven该|>运算符包含在库(如Core)中。自v。4.01.@Benoît Guédas我很困惑。。。我必须包括图书馆吗?我有旧版本的解释器吗?如何修复错误?@SadServen要了解您的版本,只需键入ocaml-version。您不需要此运算符,只需编写let int_exp x y=int_of_float((float_of_int x)**(float_of_int y)),它不能允许int
变量,即使它想允许,原因与加法中有效地为int
和float
定义的操作相同,float
版本+。
不允许int
参数。为了启用类型推断,这是一种折衷。Hindley-Milner打字系统的扩展是必要的(有些已经设计好了),以允许5.0+5.0
和5+5
。OCaml的最短版本在实践中是可以接受的:在最新版本中,您可以使用类似于Float.(5.0+5.0)
的东西