I’m writing some mysql-simple database code, and I’m making my datatypes members of the QueryResults type class to make it easy to unmartial them.
But I’m ending up with a lot of functions like:
data FullName {
first_name :: String,
middle_name :: String,
last_name :: String
} deriving Show
newtype UID = UID Integer deriving Show
go :: [(String, String)] -> Maybe FullName
go fvs = do
first <- lookup "first_name" fvs
middle <- lookup "middle_name" fvs
last <- lookup "last_name" fvs
return $ FullName first middle last
go :: [(String, String)] -> Maybe UID
go fvs = do
uid <- lookup "uid" fvs
return $ UID (read uid)
where lookup just returns (Maybe a). Some of these data types have a dozen columns in them, so this gets tedious.
So there are a lot of datatypes like this and I would like to be able to write a function I would call like this:
go RealName ["first_name","middle_name","last_name"] fvs
go UID ["uid"] fvs
but I have no idea what the type of such a thing should be, or how I would go about it. Maybe this isn’t even possible.
Using Template Haskell, I suspect you could end up with code like this:
that expands to
An aside: if you
import Control.Applicative,goFullNamecould be written more concisely, like this: