如何从命令行输入两个整数并返回平方和的平方根

杰拉比比汉娜

我正在尝试开始学习Haskell。我想从命令行输入两个数字,然后返回每个数字的平方和的平方根。这是毕达哥拉斯定理

当然,我想我会在某个地方找到一个示例,因此我可以全神贯注地接受一些输入,将输入传递给函数,返回它,然后将结果打印出来。试图通过这个简单的案例。PHP / Javascript程序员,想学习函数式编程,因此就像我现在正在学习Martian一样。抱歉,这个问题被问到还是太简单了。当然,我已经接近了,但是我不明白自己所缺少的。我知道sqrt会返回浮点数。

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

这将返回错误:

没有出现因使用“斜边”第10行第11个字符而导致的(Floating Int)实例

我的Atom编辑器IDE中突出显示了斜边的“ h”。使用ghc-mod插件进行检查。

更新:@peers回答解决了我的问题...

感谢stackoverflow.com,我的第一个haskell程序https://github.com/jackrabbithanna/haskell-pythagorean-theorem

同伴

sqrt期望输入class类,Floating但是您提供了Int不实例化的Floating在ghci中,您可以看到sqrtwith的类型签名:t sqrt是的sqrt :: Floating a => a -> a
Int实现几个类型类,如下所示: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’

Floating不在其中。
尝试read荷兰国际集团作为Double或转换Int为s fromIntegral

代码中的两种方式:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章