Problem Sheet for LI Functional Programming - Week 2
多态性 Polymorphism
(Requires Section Polymorphism) 找出下列函数的类型。决定它们是否是多态的。
fst
(++)
not
head
tail
id
用你自己的话解释一下函数
zip
的作用。在表达式zip ['x', 'y'] [False]
中,zip :: [a] -> [b] -> [(a, b)]
的类型变量a
和b
是什么实例化为?在 GHC 标准库中找到一个多态函数,其类型包含 3 个以上的类型变量。
阅读《Haskell 编程》第 3.7 节。比较那里给出的例子的类型和
ghci
显示的类型。(注意:ghci
显示的一些类型使用了type classes
- 你将在下一课学习这些类型)
Types and Typeclasses
(Requires Section Type classes and instances) 运行并理解以下例子。
False == 'c'
False == True
False == not
False == not True
not == id
[not] == [ (id :: Bool -> Bool) ]
(Requires Section Type classes and instances) 关于 type classes
- Find all the basic instances of the type class
Bounded
that are defined in the GHC Prelude (the libraries that are loaded when startingghci
, without importing any additional libraries). Find out whatminBound
andmaxBound
are for each of the instances. - What type classes do the type classes
Fractional
,Floating
,Integral
extend? What functions to they provide? - Another type class:
- Which type class defines the function
enumFromTo
? - Evaluate
enumFromTo
on elements of each instance of that type class. - Explain the different output between
:type enumFromTo 4 8
and:type enumFromTo 4 (8 :: Int)
.
- Find all the basic instances of the type class
Functions in Haskell
这些练习也包含在讲义中。 为了方便你,我们把它们收集在这里。
Using the functions
removeLast
andremoveElem
from Handout - Functions, write a function that removes both the first and the last element of a list.Using guarded equations, write a function of type
Int -> Int -> Bool
that returnsTrue
if the first argument is greater than the second and less than twice the second.Write a function to pair each element of a list with its index.
Write a function which returns the reverse of a list if its length is greater than 7. Now modify the function so that the cutoff length is a parameter.
Write a function
orB :: Bool -> Bool -> Bool
that returnsTrue
if at least one argument isTrue
.Write a function
swap :: (a, b) -> (b, a)
that swaps the elements of a pair.(Adapted and expanded from the book "Programming in Haskell) Define three variants of a function
third :: [a] -> a
that returns the third element in any list that contains at least this many elements, usinghead
andtail
- list indexing
!!
- pattern matching
(Adapted and expanded from the book "Programming in Haskell) Define a function
safetail :: [a] -> [a]
that behaves like tail except that it maps[]
to[]
(instead of throwing an error). Usingtail
andisEmpty :: [a] -> Bool
, definesafetail
using- a conditional expression
- guarded equations
- pattern matching