Skip to main content

Problem Sheet for LI Functional Programming - Week 2

多态性 Polymorphism

  1. (Requires Section Polymorphism) 找出下列函数的类型。决定它们是否是多态的。

    1. fst
    2. (++)
    3. not
    4. head
    5. tail
    6. id
  2. 用你自己的话解释一下函数 zip 的作用。在表达式zip ['x', 'y'] [False]中,zip :: [a] -> [b] -> [(a, b)] 的类型变量 ab 是什么实例化为?

  3. 在 GHC 标准库中找到一个多态函数,其类型包含 3 个以上的类型变量。

  4. 阅读《Haskell 编程》第 3.7 节。比较那里给出的例子的类型和 ghci 显示的类型。(注意:ghci 显示的一些类型使用了 type classes - 你将在下一课学习这些类型)

Types and Typeclasses

  1. (Requires Section Type classes and instances) 运行并理解以下例子。

    1. False == 'c'
    2. False == True
    3. False == not
    4. False == not True
    5. not == id
    6. [not] == [ (id :: Bool -> Bool) ]
  2. (Requires Section Type classes and instances) 关于 type classes

    1. Find all the basic instances of the type class Bounded that are defined in the GHC Prelude (the libraries that are loaded when starting ghci, without importing any additional libraries). Find out what minBound and maxBound are for each of the instances.
    2. What type classes do the type classes Fractional, Floating, Integral extend? What functions to they provide?
    3. Another type class:
    4. Which type class defines the function enumFromTo?
    5. Evaluate enumFromTo on elements of each instance of that type class.
    6. Explain the different output between :type enumFromTo 4 8 and :type enumFromTo 4 (8 :: Int).

Functions in Haskell

这些练习也包含在讲义中。 为了方便你,我们把它们收集在这里。

  1. Using the functions removeLast and removeElem from Handout - Functions, write a function that removes both the first and the last element of a list.

  2. Using guarded equations, write a function of type Int -> Int -> Bool that returns True if the first argument is greater than the second and less than twice the second.

  3. Write a function to pair each element of a list with its index.

  4. 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.

  5. Write a function orB :: Bool -> Bool -> Bool that returns True if at least one argument is True.

  6. Write a function swap :: (a, b) -> (b, a) that swaps the elements of a pair.

  7. (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, using

    1. head and tail
    2. list indexing !!
    3. pattern matching
  8. (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). Using tail and isEmpty :: [a] -> Bool, define safetail using

    1. a conditional expression
    2. guarded equations
    3. pattern matching