How to implement a monoid interface for this tree in haskell?

Sorry for the terminology, my mind is still bending.

Wood:

data Ftree a = Empty | Leaf a | Branch ( Ftree a ) ( Ftree a )
    deriving ( Show )

I have a few questions:

  • If Ftreeit cannot be Empty, then it will no longer be Monoid, since there is no identification value.

  • How would you implement mappendthis tree? Can you just arbitrarily plant two trees together willy-nilly?

  • For binary search trees, would you need to examine some elements in both trees to make sure the result mappendis still BST?

For the record, the following material can be used here Ftree:

instance Functor Ftree where
    fmap g Empty             = Empty
    fmap g ( Leaf a )        = Leaf ( g a )
    fmap g ( Branch tl tr )  = Branch ( fmap g tl ) ( fmap g tr )

instance Monad Ftree where 
    return             = Leaf
    Empty        >>= g = Empty
    Leaf a       >>= g = g a
    Branch lt rt >>= g = Branch ( lt >>= g ) ( rt >>= g )
+5
source share
1 answer

, :

instance Monoid (Ftree a) where
    mempty = Empty
    mappend = Branch

Monoid, .

? - , . (, ), (, (), ). , .

BTW: , , ...

Monad (Ftree a), Monoid:

instance (Monoid a, Monad f) => Monoid (f a) where
    mempty = return mempty
    mappend f g = f >>= (\x -> (mappend x) `fmap` g)

, . <> = mappend. , Monad ( ). , do-notation.

mappend, do-Notation, :

mappend f g = do
  x <- f
  y <- g
  return (f <> g)

, :

mappend mempty g
 -- Definition of mappend
do 
  x <- mempty
  y <- g
  return (x <> y)
 -- Definition of mempty
do 
  x <- return mempty
  y <- g
  return (x <> y)
 -- Monad law
do 
  y <- g
  return (mempty <> y)
 -- Underlying monoid laws
do 
  y <- g
  return y
 -- Monad law
g

mappend f mempty -- Definition of mappend
do
  x <- f
  y <- mempty
  return (x <> y)-- Monad law
do
  x <- f
  return (x <> mempty)-- Underlying monoid laws
do 
  x <- f
  return x-- Monad law
f

,

mappend f (mappend g h)-- Definition of mappend
do
  x <- f
  y <- do
    x' <- g
    y' <- h
    return (x' <> y')
  return (x <> y)-- Monad law
do
  x <- f
  x' <- g
  y' <- h
  y <- return (x' <> y')
  return (x <> y)-- Monad law
do
  x <- f
  x' <- g
  y' <- h
  return (x <> (x' <> y'))-- Underlying monoid law
do
  x <- f
  x' <- g
  y' <- h
  return ((x <> x') <> y')-- Monad law
do
  x <- f
  x' <- g
  z <- return (x <> x')
  y' <- h
  return (z <> y')-- Monad law
do
  z <- do
    x <- f
    x' <- g
    return (x <> x')
  y' <- h
  return (z <> y')-- Definition of mappend
mappend (mappend f g) h

, () Monad ( , #haskell), Monoid. , .

+10

All Articles