《Two Dozen Short Lessons in Haskell》学习(十二) 数值相关的类

《Two Dozen Short Lessons in Haskell》(Copyright © 1995, 1996, 1997 by Rex Page,有人翻译为Haskell二十四学时教程,该书如果不用于赢利,可以任意发布,但需要保留他们的copyright)这本书是学习 Haskell的一套练习册,共有2本,一本是问题,一本是答案,分为24个章节。在这个站点有PDF文件。几年前刚开始学习Haskell的时候,感觉前几章还可以看下去,后面的内容越来越难以理解。现在对函数式编程有了一些了解后,再来看这些题,许多内容变得简单起来了。

初学Haskell之前一定要记住:

把你以前学习面向过程的常规的编程语言,如Pascal、C、Fortran等等统统忘在脑后,函数式编程完全是不一样的编程模型,用以前的术语和思维来理解函数式编程里的概念,只会让你困惑和迷茫,会严重地影响你的学习进度。

这个学习材料内容太多,想把整书全面翻译下来非常困难,只有通过练习题将一些知识点串起来,详细学习Haskell还是先看其它一些入门书籍吧,这本书配套着学学还是不错的。

第十二章 The Class of Numbers

 

1 In the Haskell class of numbers, Int and Integer

a are basically the same type

b are the same type except that numbers of type Integer can be up to 100 digits long

c are different types but x+y is ok, even if x is of type Int and y is of type Integer

d are different types, but both in the Integral subclass

 

2 In the Haskell class of numbers, Float and Double

a are basically the same type

b are the same type except that numbers of type Double can be up to 100 digits long

c are different types but x+y is ok, even if x is of type Float and y is of type Double

d are different types, but both in the RealFrac subclass

 

3 What is the most restrictive class containing both the type Integer and the type Float?

a Num

b Real

c RealFrac

d Fractional

 

4 In the Haskell formula n/d, the numerator and denominator must be in the class

a Integral

b RealFrac

c Fractional

d Floating

 

5 What is the type of the function f?

HASKELL DEFINITION • f x y = x / y

a Float -> Float –> Float

b Real num => num -> num –> num

c Fractional num => num -> num –> num

d Floating num => num -> num –> num

 

6 What is the type of the formula ( g n 1) ?

HASKELL DEFINITION • g x y = x + y

HASKELL DEFINITION • n :: Int

HASKELL COMMAND • g n 1

a Int

b Integer

c Integral

d Real

 

 

=========================================================

=========================================================

 

1 d

Integer和Int都是整数类型,Integer可以表达的整数范围非常大,我曾经试过几百位的大整数运算,在Haskell中一点问题没有。但如果考虑效率,还需要用Int类型,但数值范围最大只能到2^29。

下面这张图清晰地表示出了与数值相关的一些类型Type和类Class。

斜着的黑字是类型Type,常规文字表示的是一些类,Num是所以数值类型的总类。

haskell-number-type

 

2 d

从上面的图可以看出,Float和Double都属于RealFloat类,也属于RealFrac类。

Haskell对类型要求很严格,如果x是Float类型,y是Double类型,那么x+y会报语法错误。

 

3 b

从上面的图可以看出,包围着Integer和Float的椭圆,只有Real类和Num类。

 

4 c

在ghci中运行:t (/)

(/) :: Fractional a => a -> a –> a

可以看出,除法这个函数,只对属于Fractional类的类型才可以进行,也就是说只有Rational, Ratio Int, Float, Double, Complex Float, Complex Double可以进行除法操作。

 

5 c

根据除法运算,可以推断出x和y都是Frational中的类型,在ghci中运行:t f

可以得到:

f :: Fractional a => a -> a –> a

 

6 a

(+)的类型是:

(+) :: Num a => a -> a –> a

由于n :: Int

所以推断出函数g n 1中的所有参数都是Int类型

posted @ 2012-12-28 08:42  申龙斌的程序人生  阅读(768)  评论(0编辑  收藏  举报