۲۰ - ۹نمونه‌های Traversable

وقتشه.

‏‎Either‎‏

تعریفی که برای نمونه ِ ‏‎Traversable‎‏ نوشتیم دقیقاً عین تعریف‌ش در ماژول ِ ‏‎Data.Traversable‎‏ در ‏‎base‎‏ ِه، فقط اینجا ‏‎Functor‎‏، ‏‎Foldable‎‏، و ‏‎Applicative‎‏ هم اضافه کردیم تا یه جور تصاعد رو ببینین:

data Either a b =
    Left a
  | Right b
  deriving (Eq, Ord, Show)

instance Functor (Either a) where
  fmap _ (Left x) = Left x
  fmap f (Right y) = Right (f y) 

instance Applicative (Either e) where
  pure          = Right
  Left e <*> _  = Left e
  Right f <*> r = fmap f r

instance Foldable (Either a) where
  foldMap _ (Left _) = mempty
  foldMap f (Right y) = f y

  foldr _ z (Left _) = z
  foldr f z (Right y) = f y z

instance Traversable (Either a) where
  traverse _ (Left x) = pure (Left x)
  traverse f (Right y) = Right <$> f y

فکر نمی‌کنیم چیزی جدید بوده باشه. فقط در بافت ِ ‏‎Either‎‏ اعمال تابع و جابجایی ِ تایپ انجام دادیم.

توپل

کاری که بالا کردیم رو اینجا برای توپل ِ دوتایی (یا ضربِ بی‌نام) انجام میدیم.

instance Functor ((,) a) where
  fmap f (x,y) = (x, f y)

instance Monoid e 
      => Applictive ((,) a) where
  pure x = (mempty, x)
  (u, f) <*> (v, x) =
    (u `mappend` v, f x)

instance Foldable ((,) a) where
  foldMap f (_, y) = f y
  foldr f z (_, y) = f y z

instance Traversable (Either a) where
  traverse f (x, y) = (,) x <$> f y z

بیشترش مثلِ قبل‌ه، فقط برای بافت ِ توپل.