简体   繁体   中英

OCaml : Simple function with conditionals doesn't work

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 (ab)^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, ie ( *. ) 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM