Hasklet #3

Due: Mon, May 3

Read the general information on Hasklets!

Submit your solution through Canvas.

Description

Haskell template

Consider the following two list-like data types. The first defines a data structure that is isomorphic (i.e. structurally equivalent) to [(a,b)]. The second defines a data structure that is isomorphic to [Either a b].

-- | A list of pairs of elements of type a AND b.
data ListP a b = NilP
               | ConsP a b (ListP a b)

-- | A list of elements of either type a OR b.
data ListE a b = NilE
               | ConsL a (ListE a b)
               | ConsR b (ListE a b)

Tasks

The template file contains cursory test cases for each of the tasks. As always, feel free to extend these with additional tests.

  1. Instantiate the following Bifunctor type class for both ListP and ListE. The bimap method allows you to map one function over all of the values of type a and another function over all of the values of type b.

    class Bifunctor t where
      bimap :: (a -> c) -> (b -> d) -> t a b -> t c d
  2. Implement two functions mapL and mapR that work on both kinds of lists. These functions should map a single function over values of either the left type variable or the right type variable, respectively. Make sure to write the type of each function.

  3. Instantiate the following Bifoldable type class for both ListP and ListE. The bifoldr method allows you to accumulate values of type a and of type b to the same accumulator type c.

    class Bifoldable t where
      bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> t a b -> c
  4. Implement two functions foldrL and foldrR that work on both kinds of lists. These functions should map a single accumulator function over values of either the left type variable or the right type variable, respectively. Make sure to write the type of each function.

  5. Implement the function bifoldMap that maps each element in a Bifoldable instance to a common monoid and combine the results using mappend. This function is used by the checkAll and toEitherList functions in the template.

    You’ll need to use the Monoid type class in your solution, which you can look up in the Haskell Prelude. If you get stuck, consider looking at the related foldMap method from the Foldable type class.


Back to course home page