我嘗試使用HList: Heterogeneous lists。
基于我的問題:如何在 HList 上撰寫異構串列?
根據答案:https ://stackoverflow.com/a/71306058/17053359
import Data.HList (HList (HCons, HNil), hBuild, hEnd)
在 HList 上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"
現在,我想遍歷/映射iAiB
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 ----------??
uj5u.com熱心網友回復:
好吧,您可以這樣做:
instance MapToIObool ts => MapToIObool (t : ts) where
mapToIObool (HCons x xs) = io True : mapToIObool xs
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437768.html
標籤:哈斯克尔
