I have list of tuples which I want to convert into data record. Tuple has type (Text, Text) where first item is key and second is a value.
data User = User
{
id :: Text
, name :: Text
}
toUser :: [(Text, Text)] -> User
toUser kvs = ???
Is it possible in Haskell to set field name of data record by its string name, like you usually can do in C# or Java using Reflection?
Also I would like to avoid repetitive lookups through list for every field and populate data record iterating through list once, but not sure what is the best option to do so.
EDIT
Input list will be something like this [("id","foo"),("name","bar")], so field names in User data record match to keys in the list.
If you want to traverse the list only once, I would insert the tuples into a map, then lookup each field name of the ADT in the map:
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
data User = User
{
id :: String
, name :: String
} deriving Show
toUser :: [(String, String)] -> User
toUser xs = User (find "id") (find "name")
where
m = Map.fromList xs
find name = fromMaybe "" $ Map.lookup name m
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With