Haskell中的简单算术

时间:2015-03-24 08:20:21

标签: haskell

我是Haskell的新手,为了熟悉它,我做了一些基本的代码katas。目前,我正在进行Kata Potter,我有以下代码片段,我不知道其中有什么错误。

import Test.Hspec

priceOf :: [Int] -> Int
priceOf xs = 8 * (length xs) 

main :: IO ()
main = hspec $ do
  describe "Harry Potter book prices" $ do
    context "Simple discounts" $ do
      it "should apply a discount to two different books" $ do
        priceOf [0, 1] `shouldBe` 0.95 * 8 * 2

当尝试使用cabal运行它时,它最终会抛出以下错误

No instance for (Fractional Int) arising from the literal '0.95'
In the first argument of '(*)', namely '0.95'
In the first argument of '(*)', namely '0.95 * 8'
In the second argument of 'shouldBe', namely '0.95 * 8 * 2'

在这里进一步阅读类似主题以及关于Haskell wiki上Converting numbers的章节,我发现了fromIntegral功能,但仍然没有得到它,我不会&#39 ;知道在Haskell中应该如何在不同类型之间应用基本算术的正确方法。

有人可以帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:7)

此处的问题是(从错误消息中推断)priceOf会返回Int,而0.95 * 8 * 2的多态类型为Fractional a => ashouldBe为迫使这些类型相同。但是Int不是Fractional类型,因此您获得了Fractional Int"没有实例。

解决这个问题的方法:

  1. priceOf返回Fractional类型,例如Double
  2. 根据您的要求,使用0.95 * 8 * 2Intround之一将floor转换为ceiling
相关问题