Created
July 9, 2011 17:36
-
-
Save maoe/1073777 to your computer and use it in GitHub Desktop.
タプルに対するgenericな加算(mkMとgmapMの使い方)
This file contains 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
module Main where | |
import Control.Monad.Writer (Writer, execWriter, tell) | |
import Data.Monoid (Sum(..)) | |
import Data.Generics (Typeable, Data, gmapM, mkM) | |
import Data.Ratio (Ratio, (%)) | |
main :: IO () | |
main = do | |
-- このタプルに対してgenericな加算を行う | |
let tuple = ( 1 :: Int | |
, 2 :: Integer | |
, 3 :: Double | |
, 4 :: Ratio Integer | |
, 5 :: Int | |
, 6 :: Integer | |
, 7 :: Double | |
) | |
genericSum :: (Num b, Typeable b, Data a) => a -> Writer (Sum b) a | |
genericSum = gmapM (mkM $ \x -> tell (Sum x) >> return x) | |
print (getSum $ execWriter $ genericSum tuple :: Int) | |
print (getSum $ execWriter $ genericSum tuple :: Integer) | |
print (getSum $ execWriter $ genericSum tuple :: Double) | |
print (getSum $ execWriter $ genericSum tuple :: Ratio Integer) |
This file contains 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
Prelude> :main | |
6 | |
8 | |
10.0 | |
4 % 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment