Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Monoid Instance Question for a newtype

I am trying to define an instance:

newtype Join a = Join { getJoin :: a -> Bool }
   deriving Generic

instance Monoid (Join a) where
   f <> g = ???
   mempty = ???

The goal is that the function foldMap Join should return True if all functions in the list are true, and false if all are not true.

I understand foldMap, and the instances of Sum and Product for Monoid but am otherwise quite new to writting newtype instances of Monoid. Any help in the right direction would be appreciated. Thank you.

like image 491
Thunderbird Avatar asked Jul 19 '20 16:07

Thunderbird


1 Answers

You can make an new function that returns True if both the first and second function return True, by using (&&). Then the mempty is a Join function that is True for all input:

instance Monoid (Join a) where
    Join f <> Join g = Join (\x -> f x && g x)
    mempty = Join (const True)

Since the introduction of the Semigroup, the (<>) function is an instance of the Semigroup however:

import Control.Applicative(liftA2)

instance Semigroup (Join a) where
    Join f <> Join g = Join (liftA2 (&&) f g)

instance Monoid (Join a) where
    mappend = (<>)
    mconcat js = Join (\x -> all (($ x) . getJoin) js)
    mempty = Join (const True)
like image 191
Willem Van Onsem Avatar answered Sep 20 '22 10:09

Willem Van Onsem