次の URL に記載されている Data.Traversable を使用して、haskell のデータ構造のすべてのメンバーをトラバースしようとしています。
http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Traversable.html http://www.haskell.org/haskellwiki/Foldable_and_Traversable
これまでのところ、Tr.Traversable インスタンス化の適切な実装が欠落していることがわかっている限り、次のコードを思いつきました。
import qualified Data.Traversable as Tr
import qualified Data.Foldable as Fl
import Control.Monad
import Control.Applicative
data Test = Test { desc :: String
, value :: Int
}
data Data t = Data { foo :: t
, bar :: t
}
exampleData = Data { foo = Test "Foo" 1
, bar = Test "Bar" 2
}
instance Show Test where
show f = (desc f) ++ ": " ++ (show $ value f)
instance (Show a) => Show (Data a) where
show f = show (foo f)
instance Functor Data where
fmap = Tr.fmapDefault
instance Fl.Foldable Data where
foldMap = Tr.foldMapDefault
instance Tr.Traversable Data where
traverse f = Data f -- Try to show a Test entry inside the Data structure
--
-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
--
main = do
putStrLn $ show exampleData
Tr.traverse (putStrLn show) exampleData
exampleData のすべての項目をメンバーごとに、show を使用して印刷しようとしています。私は正しい軌道に乗っていますか?また、トラバース可能なインスタンス化をどのように実装する必要がありますか?