Haskell 手动遍历 HList - 异构列表
traversing HList - Heterogeneous list manually in Haskell
我尝试使用HList: Heterogeneous lists。
根据我的问题:
根据回答:
import Data.HList (HList (HCons, HNil), hBuild, hEnd)
在 hello
的 HList 上
hello :: HList '[Integer, [Char]]
hello = hEnd $ hBuild 1 "2"
我可以用 print
遍历列表
class PrintEach ts where
printEach :: HList ts -> IO ()
instance PrintEach '[] where
printEach HNil = pure ()
instance (Show t, PrintEach ts) => PrintEach (t : ts) where
printEach (HCons x xs) = print x *> printEach xs
main :: IO ()
main = printEach hello
-- 1 "2"
现在,我想traverse/mapiAiB
io :: a -> IO a
io = pure
iA :: IO Int
iA = io (1 :: Int)
iB :: IO [Char]
iB = io ("foo" :: [Char])
iAiB :: HList '[IO Int, IO [Char]]
iAiB = hEnd $ hBuild iA iB
到[IO Bool]
class MapToIObool ts where
mapToIObool :: HList ts -> [IO Bool]
instance MapToIObool '[] where
mapToIObool HNil = []
instance ----------??
在这里,为了简单起见,[IO Bool]
的每个元素都将无条件地io True
。
result :: [IO Bool]
result = mapToIObool iAiB
-- expected result
result' :: [IO Bool]
result' = [io True, io True]
instance ----------??
的代码是什么
好吧,你可以这样做:
instance MapToIObool ts => MapToIObool (t : ts) where
mapToIObool (HCons x xs) = io True : mapToIObool xs
我尝试使用HList: Heterogeneous lists。
根据我的问题:
根据回答:
import Data.HList (HList (HCons, HNil), hBuild, hEnd)
在 hello
hello :: HList '[Integer, [Char]]
hello = hEnd $ hBuild 1 "2"
我可以用 print
class PrintEach ts where
printEach :: HList ts -> IO ()
instance PrintEach '[] where
printEach HNil = pure ()
instance (Show t, PrintEach ts) => PrintEach (t : ts) where
printEach (HCons x xs) = print x *> printEach xs
main :: IO ()
main = printEach hello
-- 1 "2"
现在,我想traverse/mapiAiB
io :: a -> IO a
io = pure
iA :: IO Int
iA = io (1 :: Int)
iB :: IO [Char]
iB = io ("foo" :: [Char])
iAiB :: HList '[IO Int, IO [Char]]
iAiB = hEnd $ hBuild iA iB
到[IO Bool]
class MapToIObool ts where
mapToIObool :: HList ts -> [IO Bool]
instance MapToIObool '[] where
mapToIObool HNil = []
instance ----------??
在这里,为了简单起见,[IO Bool]
的每个元素都将无条件地io True
。
result :: [IO Bool]
result = mapToIObool iAiB
-- expected result
result' :: [IO Bool]
result' = [io True, io True]
instance ----------??
好吧,你可以这样做:
instance MapToIObool ts => MapToIObool (t : ts) where
mapToIObool (HCons x xs) = io True : mapToIObool xs