[英]OCaml : Simple function with conditionals doesn't work
I am new to OCaml and I am just in process of learning it. 我是OCaml的新手,我正在学习它。 I am trying to execute a simple function that calculates
(a+b)^2
or (ab)^2
based on the values of a
and b
我试图执行一个简单的函数,根据
a
和b
的值计算(a+b)^2
或(ab)^2
I am trying to have a function that is as below 我正在尝试具有如下功能
let a_squared_b a b =
if(a<0 || b<0) then
(a**2 + b**2 + 2*a*b)
else
(a**2 + b**2 - 2*a*b);;
which returns a warning 它会返回一个警告
Error: This expression has type int but
an expression was expected of type float
So I tried the one below : 所以我尝试了以下一个:
let a_squared_b (a:float) (b:float) : float =
if(a<0 || b<0)
then (a**2 + b**2 + 2*a*b)
else (a**2 + b**2 - 2*a*b);;
Which also warns something. 这也警告了一些事情。 Hence I proceeded forward to check if the function at least works but it returns wrong result -
因此,我继续检查该函数是否有效,但它返回错误的结果 -
a_squared_b 2 2;;
- : int = 0
I am not sure what I am doing wrong, any help would be greatly appreciated 我不确定我做错了什么,任何帮助都将不胜感激
In short, OCaml uses different operators for integers and floats, ie ( *. )
instead ( * )
, (+.)
instead (+)
, etc. Also you should use 2.
instead of 2
to get "variable" of float type. 简而言之,OCaml对整数和浮点数使用不同的运算符,即
( *. )
代替( * )
, (+.)
代替(+)
等。另外,你应该使用2.
而不是2
来获得float类型的“变量” 。
# let a_squared_b (a:float) (b:float) : float = if(a<0. || b<0.) then (a**2. +. b**2. +. 2. *. a*. b) else (a**2. +. b**2. -. 2. *. a*. b);; val a_squared_b : float -> float -> float = <fun>
# a_squared_b 2. 2.;;
More information you can get, for example, there 您可以获得更多信息,例如, 那里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.