Pattern matching 'undefined'

Alain Cremieux alcremi@pobox.com
Sun, 25 May 2003 23:28:02 +0200


Hi,

I want to represent a list of (key, values) in Haskell, where key are 
predefined strings

So I define a datatype using field labels :

data UR = MkUR {
                 fieldA :: Int,
                 fieldB :: Int,
                 fieldC :: String
                 }
           deriving (Show)

and, for example, we have

testUR  = MkUR {fieldA = 1}
testUR' = MkUR {fieldA = 2, fieldB = 3, fieldC = "C"}

Now I want to write a function which transforms my datatype in [(String, 
String)] where a (key, value) element exists if the field is present, 
and none if the field does not exist.

attrList :: UR -> [(String, String)]
attrList u =  al "fieldA" (fieldA u)
           ++ al "fieldB" (fieldB u)
           ++ al "fieldC" (fieldC u)
          
al :: (Show a) => String -> a -> [(String, String)]
al fn fv = [(fn, show fv)]


Of course, as written, "attrList testUR'" succeeds and "attrList testUR" 
fails (Missing field in record construction Main.fieldB)
I need to match against undefined, which is impossible.
Is there a solution (probably involving irrefutable patterns, ~) ? Or is 
there a better way than using field labels (they are useful though, 
because I can define types to check the content at compile time, like   
data Location = Top | Bottom, which is far better than defining 
everything to be a String)

Thank you for your help,
Alain