I am new to OCaml and I am just in process of learning it. I am trying to execute a simple function that calculates (a+b)^2
or (a-b)^2
based on the values of a
and b
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, i.e. ( *. )
instead ( * )
, (+.)
instead (+)
, etc. Also you should use 2.
instead of 2
to get "variable" of float type.
# 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