0

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

Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
g0c00l.g33k
  • 2,458
  • 2
  • 31
  • 41

1 Answers1

2

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

nlucaroni
  • 47,556
  • 6
  • 64
  • 86
Kakadu
  • 2,837
  • 19
  • 29
  • Thanks for your answer, even after this correction I am still having the issue when I execute a_square_b 2. 2.;; returns me float 0. Not sure why that is... – g0c00l.g33k Mar 10 '14 at 22:42
  • 1
    a_squared_b 2.0 2.0 = 0.0 is clear from the definition, since from the condition you are calculating (a-b)^2 when a and b are greather than or equal to 0.0. – camlspotter Mar 11 '14 at 01:28