【问题标题】:How to input two integers from command line and return square root of sum of squares如何从命令行输入两个整数并返回平方和的平方根
【发布时间】:2019-07-05 00:36:55
【问题描述】:

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

这会返回一个错误:

没有因使用“斜边”而产生的 (Floating Int) 实例, 第 10 行,第 11 个字符

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

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

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

【问题讨论】:

  • 你的方法的函数类型声明在哪里?
  • 没有。应该有吗?从最简单的开始,然后逐步向上。
  • Iirc 应该有一个。喜欢hypothenuse :: Floating -&gt; Floating -&gt; Floating
  • 使用这个 Atom 编辑器,带有几个 haskell 插件。当我仔细检查它时,它向我显示: hypotenuse :: Floating a => a -> a -> a now hypotenuse :: Floating x => x -> x -> x 也可以,但是 hypothenuse :: Floating - > 浮动 -> 浮动显示错误
  • 可能存在一些语法问题。无论如何,如果你想学习函数式编程,调用内置函数并不是最好的方法。你想使用模式匹配、递归、折叠等等。祝你好运!

标签: haskell


【解决方案1】:

sqrt 需要类型为 Floating 的输入,但您提供的 Ints 不会实例化 Floating。 在 ghci 中,您可以看到 sqrt:t sqrt 的类型签名。它是sqrt :: Floating a =&gt; a -&gt; 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不在其中。
尝试将reading 为Double 或将Ints 转换为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 程序!在高中时,我用 C 语言编写了一个带有运算顺序和括号的数值表达式求值器,带有递归,有 100 行代码之类的。我的目标是在 Haskell 中找出最短的代码方法来作为一种学习方式。
  • @jackrabbithanna 如果这是你的目标,那么看看megaparsec 库以及its tutorials 可能对你有用。 Haskell 为这类事情提供了很多库——您几乎可以肯定能够在 Haskell 中用
猜你喜欢
  • 2015-03-04
  • 2021-02-09
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 2018-07-31
  • 2012-10-24
  • 1970-01-01
相关资源
最近更新 更多