|
|
1
4
, ,和 k 如果你是理性的,你可以走无限精确的路线:
符号可能需要一些时间来适应: ghci> f (0%1, 1%1) (1%10) [0 % 1,1 % 10,1 % 5,3 % 10,2 % 5,1 % 2,3 % 5,7 % 10,4 % 5,9 % 10,1 % 1]
想想
上面的代码是以命令式风格编写的,带有完整的类型注释。将其类型理解为将有理数列表转换为某些I/O操作。这个
通过
上面的Haskell代码在结构上是相似的。Haskell的类型
比如说
我们可以问问
ghci> :info Fractional
class (Num a) => Fractional a where
(/) :: a -> a -> a
recip :: a -> a
fromRational :: Rational -> a
-- Defined in GHC.Real
instance Fractional Float -- Defined in GHC.Float
instance Fractional Double -- Defined in GHC.Float
注意
ghci> (22::Float) / (7::Float) 3.142857 或 ghci> (22::Double) / (7::Double) 3.142857142857143 但不是 ghci> (22::Double) / (7::Float)
<interactive>:1:16:
Couldn't match expected type `Double' against inferred type `Float'
In the second argument of `(/)', namely `(7 :: Float)'
In the expression: (22 :: Double) / (7 :: Float)
In the definition of `it': it = (22 :: Double) / (7 :: Float)
当然不是 ghci> (22::Integer) / (7::Integer)
<interactive>:1:0:
No instance for (Fractional Integer)
arising from a use of `/' at :1:0-27
Possible fix: add an instance declaration for (Fractional Integer)
In the expression: (22 :: Integer) / (7 :: Integer)
In the definition of `it': it = (22 :: Integer) / (7 :: Integer)
即使在阅读之后 A Gentle Introduction to Haskell: Numbers ,您仍然可能会发现Haskell对混合数字类型的挑剔令人沮丧。对于我们这些在头脑中或纸上执行无限精度运算的人来说,忘记计算机只有有限精度,必须处理近似值是太容易了。类型安全是一个有用的现实检查。 样本输出: *Main> printApprox $ f (0%1, 1%1) (1%10) 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
功能性 在 point-free style ,争论消失了 计算的结果。学习阅读和这种风格确实需要练习,但您会发现它有助于编写更清晰的代码。
我们看到一些熟悉的片段:我们的新朋友
在你尝试之前,它可能不会显得非常有用 Prelude> show 1.0 / 2.0
<interactive>:1:0:
No instance for (Fractional String)
arising from a use of `/' at :1:0-13
Possible fix: add an instance declaration for (Fractional String)
In the expression: show 1.0 / 2.0
In the definition of `it': it = show 1.0 / 2.0
你可以把这句话写成
或
所以你能想到
然后是
我们也可以写为
如您所见,我们应用右手函数,然后将结果输入左手函数。你可能还记得数学课本上的定义,比如
因此,对于一系列的函数组合,通过前后阅读通常是最容易理解的。
ghci> (numerator &&& denominator) $ 1%3 (1,3)
所以它将两个函数应用于同一个值,并返回一个包含结果的元组。记住我们需要申请
最后是
哪里
但是从功能上考虑!如果我们能改变
你和哈斯克尔迈出了伟大的第一步。旅途愉快! |
|
|
2
9
由于IEEE浮点算法一般不能精确地表示十进制数。二进制表示法中总是存在舍入错误,有时在显示数字时会渗入到表面。
根据GHC将浮点数转换为十进制表示的方式,您可能会发现在Windows上它会按预期的方式显示结果
编辑:情况可能并非如此。号码
|
|
|
3
2
|