peteofce
peteofce

Reputation: 185

Trying to convert a list of data records to a hashmap

Here is the code:

import Data.HashMap.Lazy as H

data Connections = Connections { connectionName :: String
                    , cfgProperty  :: !Object
                   } deriving (Show, Generic)

loadConn :: [Connections] -> HashMap k v
loadConn c = H.fromList $ j c
  where j cn = do
              let h = foldl (\l -> [(connectionName l, cfgProperty l)]) cn
              return h

OK, I know that "loadConn" is probably not even close. I've fiddled with some different ideas, but none of them worked out.

Any ideas? Is there more info needed?

Thanks

Upvotes: 0

Views: 719

Answers (1)

duplode
duplode

Reputation: 34398

Firstly, the do-block is out of place, as you aren't sequencing IO actions or writing any other kind of monadic code.

Secondly, if you want the hashmap to have connection names as keys and connection properties as values, the type of your function should reflect that (see also crokeea's comment to the question):

loadConn :: [Connections] -> HashMap String Object

Thridly, the general idea of building a list that you can give to H.fromList is sound, but you want map rather than a fold:

loadConn :: [Connections] -> HashMap String Object
loadConn cs = H.fromList $ map (\c -> (connectionName c, cfgProperty l)) cs

Or, using . for function composition and not mentioning the cs parameter:

loadConn :: [Connections] -> HashMap String Object
loadConn = H.fromList . map (\c -> (connectionName c, cfgProperty c))

Note that the function given to map converts a single connection into a single key-value pair. By the way, you'll probably want to change the name of your type from Connections to Connection, as each of its values appears to amounts to a single connection.

Upvotes: 2

Related Questions