《Two Dozen Short Lessons in Haskell》学习(十

《Two Dozen Shortin 》( ? 1995, 1996, 1997 by Rex Page,有人翻译为二十四学时教程,该书如果不用于赢利,可以任意发布,但需要保留他们的)这本书是学习 的一套练习册,共有2本,一本是问题,一本是答案,分为24个章节 。在这个站点有PDF文件 。几年前刚开始学习的时候,感觉前几章还可以看下去,后面的内容越来越难以理解 。现在对函数式编程有了一些了解后,再来看这些题,许多内容变得简单起来了 。
初学之前一定要记住:
把你以前学习面向过程的常规的编程语言,如、C、等等统统忘在脑后,函数式编程完全是不一样的编程模型,用以前的术语和思维来理解函数式编程里的概念,只会让你困惑和迷茫,会严重地影响你的学习进度 。
这个学习材料内容太多,想把整书全面翻译下来非常困难,只有通过练习题将一些知识点串起来,详细学习还是先看其它一些入门书籍吧,这本书配套着学学还是不错的 。
第十二章 The Class of
1 In theclass of , Int and
a arethe same type
b are the same typethatof typecan be up to 100long
c aretypes but x+y is ok, even if x is of type Int and y is of type
d aretypes, but both in the
2 In theclass of , Float and
a arethe same type
b are the same typethatof typecan be up to 100long
c aretypes but x+y is ok, even if x is of type Float and y is of type
d aretypes, but both in the
3 What is the mostclassboth the typeand the type Float?
a Num
b Real
c
d
4 In then/d, theandmust be in the class
a
b

《Two Dozen Short Lessons in Haskell》学习(十

文章插图
c
d
5 What is the type of thef?
? f x y = x / y
a Float -> Float –> Float
b Real num => num -> num –> num
cnum => num -> num –> num
dnum => num -> num –> num
6 What is the type of the( g n 1) ?
? g x y = x + y
? n :: Int
? g n 1
a Int
b
c
d Real
=========================================================





=========================================================
《Two Dozen Short Lessons in Haskell》学习(十

文章插图
1 d
和Int都是整数类型,可以表达的整数范围非常大,我曾经试过几百位的大整数运算,在中一点问题没有 。但如果考虑效率,还需要用Int类型,但数值范围最大只能到2^29 。
下面这张图清晰地表示出了与数值相关的一些类型Type和类Class 。
斜着的黑字是类型Type,常规文字表示的是一些类,Num是所以数值类型的总类 。
2 d
从上面的图可以看出,Float和都属于类,也属于类 。
对类型要求很严格,如果x是Float类型,y是类型,那么x+y会报语法错误 。
3 b
从上面的图可以看出,包围着和Float的椭圆,只有Real类和Num类 。
4 c
在ghci中运行:t (/)
(/) ::a => a -> a –> a
可以看出,除法这个函数,只对属于类的类型才可以进行,也就是说只有, Ratio Int, Float, ,Float,可以进行除法操作 。
5 c
根据除法运算,可以推断出x和y都是中的类型,在ghci中运行:t f
可以得到:
f ::a => a -> a –> a
6 a
(+)的类型是:
(+) :: Num a => a -> a –> a
由于n :: Int
【《Two Dozen Short Lessons in Haskell》学习(十】所以推断出函数g n 1中的所有参数都是Int类型