HList : String to Label

91 views Asked by At

I am trying to get started with HList. Is there a way (a function?) to produce a label from a string in the following way :

{-# LANGUAGE DataKinds #-}

import Data.HList

lb1 = Label :: Label "myLabel1"
lb2 = Label :: Label "myLabel2"
lb3 = Label :: Label "myLabel3"

myRec = lb1 .=. 'a' .*.
        lb2 .=. (True, 42 :: Int)  .*. 
        lb3 .=. 3.14  .*. 
        emptyRecord

main = do putStrLn "what's the label?"
          lb <- getLine -- does not work
          putStrLn $ "the value for this label is: " ++ show (myRec .!. lb)
          return ()

This code as-is would not compile since lb is a String, not a Label. Is there a proper way to achieve this? Thanks.

2

There are 2 answers

0
Yuriosity On

That would be semantically equivalent to depedent types (the result type of your getter function would depend on the value of string), so I guess it's impossible in Haskell type system.

0
aavogt On

I'd convert myRec to an association list, so you can use lookup lb (toAssocList myRec)

  toAssocList (Record a) = hMapOut ShowFn a :: [(String, String)]

  -- unfortunately a bit ugly:    
  data ShowFn = ShowFn

  instance (lv ~ Tagged l v, ShowLabel l, Show v, r ~ (String,String))
        => ApplyAB ShowFn lv r where
    applyAB _ (Tagged v) = (showLabel (Label :: Label l), show v)