Reputation: 1001
import Data.Complex
realPart :: (RealFloat a) => Complex a -> a
realPart (x :+ _) = x
imagPart :: (RealFloat a) => Complex a -> a
imagPart (_ :+ x) = x
this is the code I have but when I execute realPart 2:+3
it gives 2.0 :+ 3.0 as output where I just need 2 as output. Is there any way out there to get it?
also when I execute imagPart 2:+3
it gives 0.0 :+ 3.0
as output where I need 3 only.
Upvotes: 2
Views: 283
Reputation: 48664
Putting parenthesis should solve:
ghci> realPart (2:+3)
2.0
ghci> imagPart (2:+3)
3.0
When you don't put parenthesis, it behaves like this:
ghci> (realPart 2) :+ 3
2.0 :+ 3.0
Upvotes: 6
Reputation: 120711
Function application binds more tightly than any infix, including :+
. Therefore, what you have is parsed as (realPart 2) :+ 3
, which is simply 2 :+ 3
(in realPart 2
, the 2
is interpreted as a complex Num
literal, i.e. as 2 :+ 0
).
To prevent this, use either parens or $
for manual grouping: realPart $ 2 :+ 3
will give 2.
Upvotes: 11