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

标签 haskell

我正在尝试开始学习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

这将返回错误:

No instance for (Floating Int) arising from a use of ‘hypotenuse', line 10, character 11



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

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

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

最佳答案

sqrt需要类型为Floating的输入,但是您提供的Int不会实例化Floating
在ghci中,您可以看到sqrt:t sqrt的类型签名。它是sqrt :: Floating a => a -> aInt实现了几种类型类,如: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转换为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)

关于haskell - 如何从命令行输入两个整数并返回平方和的平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56895331/

相关文章:

haskell - 有什么办法可以缩短这些线

haskell - 为什么我的 MaybeT (State <type>) () 忽略状态更改?

haskell - 理解 Haskell 斐波那契数列

haskell - ((->) r) 在实例 Applicative ((->) r) 中意味着什么?

haskell - 了解Haskell的堆栈程序以及解析器和LTS版本

haskell - 类型类挑战 : having both variadic arguments and results

haskell - 如何定义只接受数字的数据类型?

haskell - 函数依赖/类型族 - AST

haskell - 为多态模式同义词编写完整的编译指示?

algorithm - 匹配最长的前导子串