Reputation: 167
I'm trying to start learning Haskell. I want to enter two numbers from the command line and and return the sqrt root of the sum of the square of each number. This is the Pythagorean Theorem
Surely I thought I'd find an example somewhere, so I could wrap my head around taking some input, passing the input to a function, returning it, and printing the result out. Trying to work through this simple case. PHP / Javascript programmer, wanting to learn functional programming, so like I'm learning Martian at this point. Sorry if this question's been asked or is too simple. Surely I'm close, but I don't understand what I'm missing. I understand the sqrt would return a floating point number.
module Main where
hypotenuse a b = sqrt $ a * a + b * b
main :: IO ()
main = do
input1 <- getLine
input2 <- getLine
let a = read input1 :: Int
let b = read input2 :: Int
print $ hypotenuse a b
This returns an error:
No instance for (Floating Int) arising from a use of ‘hypotenuse', line 10, character 11
the 'h' in hypotenuse is highlighted in my Atom editor IDE. with the ghc-mod plugin to check.
UPDATE: @peers answer solved my problem ...
Thanks stackoverflow.com, my first haskell program https://github.com/jackrabbithanna/haskell-pythagorean-theorem
Upvotes: 1
Views: 613
Reputation: 4699
sqrt
expects input of type class Floating
but you provide Int
s which do not instantiate Floating
.
In ghci you can see the type signature of sqrt
with :t sqrt
. It is sqrt :: Floating a => a -> a
.
Int
implements several type classes as can be seen with :info Int
:
instance Eq Int -- Defined in ‘GHC.Classes’
instance Ord Int -- Defined in ‘GHC.Classes’
instance Show Int -- Defined in ‘GHC.Show’
instance Read Int -- Defined in ‘GHC.Read’
instance Enum Int -- Defined in ‘GHC.Enum’
instance Num Int -- Defined in ‘GHC.Num’
instance Real Int -- Defined in ‘GHC.Real’
instance Integral Int -- Defined in ‘GHC.Real’
instance Bounded Int -- Defined in ‘GHC.Enum’
but Floating
is not among them.
Try read
ing as Double
or converting the Int
s with fromIntegral
.
Both ways in the code:
module Main where
hypotenuse a b = sqrt $ a * a + b * b
main :: IO ()
main = do
input1 <- getLine
input2 <- getLine
let a = read input1 :: Double
let b = read input2 :: Int
print $ hypotenuse a (fromIntegral b)
Upvotes: 5