[Haskell-cafe] How to convert records into Haskell structure in Haskell way?

Evan Laforge qdunkan at gmail.com
Mon Nov 2 21:38:33 EST 2009


On Mon, Nov 2, 2009 at 5:29 PM, Magicloud Magiclouds
<magicloud.magiclouds at gmail.com> wrote:
> Hi,
>  Say I have something like this:
> [ Record { item = "A1", value = "0" }
> , Record { item = "B1", value = "13" }
> , Record { item = "A2", value = "2" }
> , Record { item = "B2", value = "10" } ]
>  How to convert it into:
> [ XXInfo { name = "A", value1 = "0", value2 = "2" }
> , XXInfo { name = "B", value1 = "13", value2 = "10" } ]
>  If XXInfo has a lot of members. And sometimes the original data
> might be not integrity.

This is a function from my library that I use a lot:

-- | Group the unsorted list into @(key x, xs)@ where all @xs@ compare equal
-- after @key@ is applied to them.  List is returned in sorted order.
keyed_group_with :: (Ord b) => (a -> b) -> [a] -> [(b, [a])]
keyed_group_with key = map (\gs -> (key (head gs), gs))
    . groupBy ((==) `on` key) . sortBy (compare `on` key)

-- You can use it thus, Left for errors of course:

to_xx records = map convert (keyed_group_with item records)
  where
  convert (name, [Record _ v1, Record _ v2]]) = Right (XXInfo name v1 v2)
  convert (name, records) = Left (name, records)


More information about the Haskell-Cafe mailing list