Skip to content

Instantly share code, notes, and snippets.

@maoe
Created July 9, 2011 17:36
Show Gist options
  • Save maoe/1073777 to your computer and use it in GitHub Desktop.
Save maoe/1073777 to your computer and use it in GitHub Desktop.
タプルに対するgenericな加算(mkMとgmapMの使い方)
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)
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