Search code examples
haskellcsvalgebraic-data-types

constructing data-type instances from CSV


I have CSV data (inherited - no choice here) which I need to use to create data type instances in Haskell. parsing CSV is no problem - tutorials and APIs abound.

Here's what 'show' generates for my simplified trimmed-down test-case:

JField {fname = "cardNo", ftype = "str"} (string representation)

I am able to do a read to convert this string into a JField data record. My CSV data is just the values of the fields, so the CSV row corresponding to JField above is:

cardNo, str

and I am reading these in as List of string ["cardNo", "str"]

So - it's easy enough to brute-force the exact format of "string representation" (but writing Java or python-style string-formatting in Haskell isn't my goal here).

I thought of doing something like this (the first List is static, and the second list would be read file CSV) :

let stp1 = zip ["fname = ", "ftype ="] ["cardNo", "str"]

resulting in

[("fname = ","cardNo"),("ftype =","str")]

and then concatenating the tuples - either explicitly with ++ or in some more clever way yet to be determined.

This is my first simple piece of code outside of tutorials, so I'd like to know if this seems a reasonably Haskellian way of doing this, or what clearly better ways there are to build just this piece: fname = "cardNo", ftype = "str"

Not expecting solutions (this is not homework, it's a learning exercise), but rather critique or guidelines for better ways to do this. Brute-forcing it would be easy but would defeat my objective, which is to learn


Solution

  • I might be way off, but wouldn't a map be better here? I guess I'm assuming that you read the file in with each row as a [String] i.e.

    field11, field12
    field21, field22
    

    etc.

    You could write

    map (\[x,y] -> JField {fname = x, ftype = y}) data
    

    where data is your input. I think that would do it.