Haskell Concat-Typeclass

I was wondering if there is a specific type in Haskell that declares concatenation.

For lists, there are ++

and concat

. But of course there are other types that are concatable as well.

Example:

type Valuater = A -> [Int]
concatValuater :: [Valuater] -> Valuater
concatValuater vs = \a -> concat [v a | v <- vs]

      

Is there no class for concat

?

+3


source to share


2 answers


As @JAbrahamson said, Monoid

this is exactly the type you are looking for. For your case, you should be able to implement it like this:

newtype Valuater = Valuater {
    evalValuater :: A -> [Int]
    }

instance Monoid Valuater where
    mempty = Valuater (const [])
    mappend (Valuater f) (Valuater g) = Valuater (\a -> f a ++ g a)
    mconcat vs = Valuater (\a -> concatMap (`evalValuater` a) vs)

      

Then you can use all related functions Monoid

on Valuaters

.



In fact, you can make it a little more general:

newtype Valuater' m = Valuater {
    evalValuater :: A -> m
    }

instance Monoid m => Monoid (Valuater' m) where
    mempty = Valuater (const mempty)
    mappend (Valuater f) (Valuater g) = Valuater (\a -> f a <> g a)
    mconcat vs = Valuater (\a -> mconcat $ map (`evalValuater` a) vs)

type Valuater = Valuater' [Int]

      

And now you can easily work with Valuater'

for different monoids, but I don't know if this is especially suitable for your specific problem.

+7


source


Chances are you would like to take a look at Monoid



class Monoid a where
  mempty :: a
  mappend :: a -> a -> a
  mconcat :: [a] -> a

      

+9


source







All Articles