Skip to content

Latest commit

 

History

History
133 lines (95 loc) · 2.89 KB

File metadata and controls

133 lines (95 loc) · 2.89 KB

Solutions to problems of chapter 20

Chapter Exercises

Traversable instances

Write a Traversable instance for the datatype provided, filling in any required superclasses. Use QuickCheck to validate your instances.

  1. Identity

Write a Traversable instance for Identity.

newtype Identity a = Identity a deriving (Eq, Ord, Show)

instance Traversable Identity where
  traverse = undefined

Solution file (can be run as a script)

  1. Constant
newtype Constant a b = Constant {getConstant :: a}

Solution file (can be run as a script)

  1. Maybe
data Optional a = Nada | Yep a

Solution file (can be run as a script)

  1. List
data List a = Nil | Cons a (List a)

Solution file (can be run as a script)

  1. Three
data Three a b c = Three a b c

Solution file (can be run as a script)

  1. Pair
data Pair a b = Pair a b

Solution file (can be run as a script)

  1. Big

When you have more than one value of type b, you'll want to use Monoid and Applicative for the Foldable and Traversable instances respectively.

data Big a b = Big a b b

Solution file (can be run as a script)

  1. Bigger
data Bigger a b = Bigger a b b b

Solution file (can be run as a script)

  1. S
{-# LANGUAGE FlexibleContexts #-}

module SkiFree where

import Test.QuickCheck
import Test.QuickCheck.Checkers

data S n a = S (n a) a deriving (Eq, Show)

instance (Functor n
        , Arbitrary (n a)
        , Arbitrary a )
      => Arbitrary (S n a) where
  arbitrary = S <$> arbitrary <*> arbitrary

instance (Applicative n
        , Testable (n Property)
        , EqProp a)
      =>  EqProp (S n a) where
  (S x y) =-= (S p q) =
      (property $ (=-=) <$> x <*> p)
    .&. (y =-= q)

instance Traversable n => Traversable (S n) where
  traverse = undefined

main = sampl' (arbitrary :: Gen (S [] Int))

Solution file (can be run as a standalone script)

Instances for Tree

Write the following instances for Tree.

data Tree a =
    Empty
  | Leaf a
  | Node (Tree a) a (Tree a)
  deriving (Eq, Show)

instance Functor Tree where
  fmap = undefined


-- foldMap is a bit easier
-- and looks more natural,
-- but you can do foldr too
-- for extra credit.
instance Foldable Tree where
  foldMap = undefined

instance Traversable Tree where
  traverse = undefined

Hints:

  1. For foldMap, think Functor but with some Monoid thrown in.
  2. For traverse, think Functor but with some Functor thrown in. Solution file (can be run as a standalone script)