我試圖用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,member by member和show中打印所有項目。我在正確的軌道上,應該如何實施可穿越的實例?
謝謝,在添加更多成員時解決了問題,以及我在@rampion回答下面的評論中提問。 – toeplitz