'How to write a Heterogeneous list on HList?

I want to use HList: Heterogeneous lists.

Installed the library then import Data.HList (HList) has been done so far.

Now investigating https://bitbucket.org/HList/hlist/src/master/examples/HListExample/ does not help me to start writing the code.

What I want to do is,

  1. create a hello-world Heterogeneous lists such as H[1, "2"] (not sure about the syntax at all)

  2. map the Heterogeneous lists to print each.

Is there anyone familiar to how to use HList?



Solution 1:[1]

You can construct an HList by using the hEnd and hBuild functions, e.g.:

hello = hEnd (hBuild 1 "2")

Mapping print over this list is much more difficult. I think there is no easy way to write a higher order function that is able to map print over the HList, but you can manually traverse the HList like this:

{-# LANGUAGE DataKinds #-}

import Data.HList

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

hello = hEnd (hBuild 1 "2")

main = printEach hello
-- This prints:
-- 1
-- "2"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1