Home > Blockchain >  traversing HList - Heterogeneous list manually in Haskell
traversing HList - Heterogeneous list manually in Haskell

Time:03-05

I try to use HList: Heterogeneous lists.

Based on my question: How to write a Heterogeneous list on HList?

Accoding to an answer: https://stackoverflow.com/a/71306058/17053359

import Data.HList (HList (HCons, HNil), hBuild, hEnd)

On a HList of hello

hello :: HList '[Integer, [Char]]
hello = hEnd $ hBuild 1 "2"

I could traverse the list with 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"

Now, I want to traverse/map 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

to [IO Bool]

class MapToIObool ts where
  mapToIObool :: HList ts -> [IO Bool]

instance MapToIObool '[] where
  mapToIObool  HNil = []

instance ----------??

Here, for the simplicity, every element of [IO Bool] will be io True unconditionally.

result :: [IO Bool]
result = mapToIObool iAiB
-- expected result
result' :: [IO Bool]
result' = [io True, io True]

What is the code for instance ----------??

CodePudding user response:

Well, here's how you can do it:

instance MapToIObool ts => MapToIObool (t : ts) where
  mapToIObool (HCons x xs) = io True : mapToIObool xs
  • Related