ابتدای محتوای صفحه
۲۰ - ۱۲تمرینهای فصل
نمونههای Traversable
برای تایپهای داده شده، نمونه ِ Traversable تعریف کنین، هر سوپرکلاسی هم لازم بود بنویسین. نمونههاتون رو با QuickCheck تست کنین.
Identity
برای Identity یه نمونه ِ Traversable بنویسین.
newtype Identity a = Identity a
deriving (Eq, Ord, Show)
instance Traversable Identity where
traverse = undefinedConstant
newtype Constant a b =
Constant { getConstant :: a }Maybe
data Optional a =
Nada
| Yep a List
data List a =
Nil
| Cons a (List a)Three
data Three a b c =
Three a b cPair
data Pair a b =
Pair a bBig
در مواقعی که بیشتر از یک مقدار با تایپِ b داریم، باید به ترتیب برای نمونههای Foldable و Traversable، از Monoid و Applicative استفاده کنیم.
data Big a b =
Big a b bBigger
مثل Big.
data Bigger a b =
Bigger a b b bS
این یکی شاید سخت باشه. برای اینکه آسونتر شه، محدودیتها و نمونههای QuickCheck رو بهتون میدیم:
{-# 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 =
sample' (arbitrary :: Gen (S [] Int))نمونههای Tree
این هم شاید سخت باشه. نمونههای زیر رو برای Tree بنویسین.
data Tree a =
Empty
| Leaf a
| Node (Tree a) a (Tree a)
deriving (Eq, Show)
instance Functor Tree where
fmap = undefined
-- آسونتره و foldMap تابع
-- ،طبیعیتر به نظر میرسه
-- ولی برای امتیاز اضافه
-- .هم بنویسین foldr میتونین
instance Foldable Tree where
foldMap = undefined
instance Traversable Tree where
traverse = undefinedراهنماییها:
۱.
برای foldMap یادِ Functor بیوفتین که یه کم Monoid هم داره.
۲.
برای traverse یادِ Functor بیوفتین که یه کم Functor هم داره.*
*
اشتباهِ تایپی نیست.