Created
July 7, 2012 08:31
-
-
Save monzou/3065478 to your computer and use it in GitHub Desktop.
Monoid
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.Monoid | |
-- モノイドが便利なのはどんな場合? | |
-- 例えばふたつの文字列を引数に取り, その長さを比較して Ordering を返す。 | |
-- 但し長さが等しい場合は文字列を辞書比較して返す。という関数を作りたい場合。 | |
-- ふつうにつくるとこうなる | |
lengthCompare1 :: String -> String -> Ordering | |
lengthCompare1 x y = let | |
a = length x `compare` length y | |
b = x `compare` y | |
in | |
if a == EQ then b else a | |
-- Ordering が以下の Monoid であることを利用すればこうなる | |
-- instance Monoid Ordering where | |
-- mempty = EQ | |
-- LT `mappend` _ = LT | |
-- EQ `mappend` y = y | |
-- GT `mappend` _ = GT | |
lengthCompare2 :: String -> String -> Ordering | |
lengthCompare2 x y = (length x `compare` length y) `mappend` (x `compare` y) | |
main = do | |
print $ lengthCompare1 "foo" "fooo" -- LT | |
print $ lengthCompare1 "foo" "foo" -- EQ | |
print $ lengthCompare1 "foo" "bar" -- GT | |
print $ lengthCompare2 "foo" "fooo" -- LT | |
print $ lengthCompare2 "foo" "foo" -- EQ | |
print $ lengthCompare2 "foo" "bar" -- GT | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment