如何输入两个元素

时间:2018-03-25 05:39:50

标签: haskell

这是我在Haskell上的代码

module Q5Degrees where

-- The relationship between temperature c in degrees Celsius and temperature f in degrees Q5Degrees
-- is defined by the function
--   c = (f - 32) * 5 / 9
-- Data types to represent temperature values in Q5Degrees and Celsius
data Fahrenheit =
  F Double
  deriving (Show)

data Celsius =
  C Double
  deriving (Show)

-- | convert
-- Takes a value representing temperature in degrees Fahrenheit and converts   it to degrees Celsius
--
-- Examples:
--
-- >>> convert (F 50)
-- C 10.0
-- >>> convert (F 14)
-- C (-10.0)
convert :: Double -> Double
convert f = (f - 32) * 5 / 9

-- | equals
-- Takes values representing temperature in degrees Celsius and degrees Fahrenheit and returns True
-- if they are equal (to within 0.5 degrees Fahrenheit), and False otherwise
--
-- Examples:
--
-- >>> equals (F 34) (C 1)
-- True
-- >>> equals (F 33) (C 0)
-- False
-- >>> equals (F 32) (C 0)
-- True
equals :: Double -> Double -> Bool
equals ("F" y) ("C" x)
 | (y-32)*5/9 == x = True
 | (y-32)*5/9 /= x = False
 | otherwise = False

doctest需要输入两个值(F 34)(C 1)。任何人都可以教我如何修复这一行,以通过doctest。我试过放     等于x y 如果输入(F 34)(C 1)

,则会出错

1 个答案:

答案 0 :(得分:1)

首先要编译代码,你需要两件事:

equals :: Fahrenheit -> Celsius -> Bool
equals (F y) (C x)
 | (y-32)*5/9 == x = True
 | (y-32)*5/9 /= x = False
 | otherwise = False
  1. 不要将构造函数名称放在引号中(引号仅用于字符串)
  2. 参数类型必须为FahrenheitCelsius,而不是DoubleDouble
  3. 要修复convert上失败的doctest,您还需要更改其类型,以便它们不会Double

    convert :: Fahrenheit -> Celsius
    convert (F f) = C ((f - 32) * 5 / 9)
    

    equals doctest失败了。首先,让我们简化您的代码。

    equals :: Fahrenheit -> Celsius -> Bool
    equals (F y) (C x) = (y - 32) * 5 / 9 == x
    

    我不知道如何处理这个doctest,因为测试本身看起来不对。 34华氏度不等于1摄氏度;它应该是10/9 C.但是你不会在这里进行同等性测试,因为你正在使用Double,因此你会得到浮点舍入错误。也许您想将您的陈述从Double更改为Rational