Haskell Language
모노 노이드
수색…
목록을위한 Monoid의 인스턴스
instance Monoid [a] where
mempty = []
mappend = (++)
이 인스턴스의 Monoid 법칙 확인 :
mempty `mappend` x = x <-> [] ++ xs = xs -- prepending an empty list is a no-op
x `mappend` mempty = x <-> xs ++ [] = xs -- appending an empty list is a no-op
x `mappend` (y `mappend` z) = (x `mappend` y) `mappend` z
<->
xs ++ (ys ++ zs) = (xs ++ ys) ++ zs -- appending lists is associative
Monoids 목록을 단일 값으로 축소
mconcat :: [a] -> a 다른 것이다 의 방법 Monoid typeclass :
ghci> mconcat [Sum 1, Sum 2, Sum 3]
Sum {getSum = 6}
ghci> mconcat ["concat", "enate"]
"concatenate"
기본 정의는 mconcat = foldr mappend mempty 입니다.
숫자 Monoids
번호는 두 가지 monoidal있다 : 단위로 1 단위와 승산 0으로서 첨가. 둘 다 똑같이 유효하고 다른 상황에서 유용합니다. 그래서 숫자에 대한 선호 인스턴스를 선택하기보다는 두가 newtypes , Sum 및 Product 다른 기능을 위해 그들에 태그가.
newtype Sum n = Sum { getSum :: n }
instance Num n => Monoid (Sum n) where
mempty = Sum 0
Sum x `mappend` Sum y = Sum (x + y)
newtype Product n = Product { getProduct :: n }
instance Num n => Monoid (Product n) where
mempty = Product 1
Product x `mappend` Product y = Product (x * y)
이를 통해 개발자는 해당 newtype 값을 래핑하여 사용할 기능을 효과적으로 선택할 수 있습니다.
Sum 3 <> Sum 5 == Sum 8
Product 3 <> Product 5 == Product 15
Monoid for ()의 인스턴스
() 는 Monoid 입니다. type () 값이 하나뿐이므로 mempty 와 mappend 가 할 수있는 것은 하나뿐입니다.
instance Monoid () where
mempty = ()
() `mappend` () = ()
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow