新类型的Haskell Monoid实例问题 [英] 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 = ???
目标是,如果列表中的所有函数均为true,则foldMap Join函数应返回True,否则,则返回false.
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.
我了解foldMap以及Monoid的Sum和Product实例,但在编写Monoid的新类型实例方面还很陌生.任何在正确方向上的帮助将不胜感激.谢谢.
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.
推荐答案
如果第一个和第二个函数都返回True
,则可以使用(&&)
来创建一个返回True
的新函数.那么mempty
是Join
函数,对于所有输入,该函数都是True
:
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)
由于引入了Semigroup
,因此(<>)
函数是Semigroup
的一个实例.
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)
这篇关于新类型的Haskell Monoid实例问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!