Folding without lists?

In a recent assignment, I was asked to define fold functions for some types of non-list. I am still not quite able to get around this concept. So far, I have understood foldhow doing on subsequent elements in list. foldons Treestill have intuitive meaning, since everyone can use some function recursively over root subtrees.

However, in a data type such as:

Maybe a :: Nothing | Just a

No list(it seems to me) to perform the fold action.

I am sure that I have a problem understanding the basic concepts here, and I would really appreciate a clarification.

+4
source share
2 answers

Foldable - , , , Foldable . , , Foldable , Traversable type — .

class (Functor t, Foldable t) => Traversable t where
  traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

Traversable , , traverse Identity = Identity. , Maybe:

traverse :: Applicative f => (a -> f b) -> Maybe a -> f (Maybe b)
traverse g Nothing = _none
traverse g (Just a) = _some

f (Maybe b), , , - g :: a -> f b. f, a, , , pure Nothing.

f (Maybe b), g :: a -> f b a. , - g a, g a :: f b. : Nothing, Just.

traverse Identity (Just a) = Identity (Just a). Nothing. -

traverse _ Nothing = pure Nothing
traverse g (Just a) = Just <$> g a

Traversable Maybe Traversable.

traverse:

foldMapDefault :: (Traversable t, Monoid m)
               => (a -> m) -> t a -> m
foldMapDefault f xs =
  getConst (traverse (Const . f) xs)

Maybe,

foldMapDefault f Nothing =
  getConst (traverse (Const . f) Nothing)
foldMapDefault f (Just a) =
  getConst (traverse (Const . f) (Just a))

,

foldMapDefault f Nothing = getConst (pure Nothing)
foldMapDefault f (Just a) = getConst (Just <$> (Const (f a)))

pure <$> Const

foldMapDefault f Nothing = getConst (Const mempty)
foldMapDefault f (Just a) = getConst (Const (f a))

,

foldMapDefault f Nothing = mempty
foldMapDefault f (Just a) = f a

, foldMap Maybe.

+6

" " , , .

, , , ( foldr), Maybe. List a [a], , foldr :

foldr :: (a -> b -> b) -> b -> List a -> b

, Maybe :

foldrMaybe :: (a -> b -> b) -> b -> Maybe a -> b

, , , a b, . , , , Data.Maybe, - (-), .

+3

Source: https://habr.com/ru/post/1662093/


All Articles