Problem Sheet for LI Functional Programming - Week 2
多态性 Polymorphism
(Requires Section Polymorphism) 找出下列函数的类型。决定它们是否是多态的。
fst(++)notheadtailid
用你自己的话解释一下函数
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 == TrueFalse == notFalse == not Truenot == id[not] == [ (id :: Bool -> Bool) ]
(Requires Section Type classes and instances) 关于 type classes
- Find all the basic instances of the type class
Boundedthat are defined in the GHC Prelude (the libraries that are loaded when startingghci, without importing any additional libraries). Find out whatminBoundandmaxBoundare for each of the instances. - What type classes do the type classes
Fractional,Floating,Integralextend? What functions to they provide? - Another type class:
- Which type class defines the function
enumFromTo? - Evaluate
enumFromToon elements of each instance of that type class. - Explain the different output between
:type enumFromTo 4 8and:type enumFromTo 4 (8 :: Int).
- Find all the basic instances of the type class
Functions in Haskell
这些练习也包含在讲义中。 为了方便你,我们把它们收集在这里。
Using the functions
removeLastandremoveElemfrom 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 -> Boolthat returnsTrueif 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 -> Boolthat returnsTrueif 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] -> athat returns the third element in any list that contains at least this many elements, usingheadandtail- 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). UsingtailandisEmpty :: [a] -> Bool, definesafetailusing- a conditional expression
- guarded equations
- pattern matching