Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a data type in Haskell with an undetermined number of fields

Tags:

types

csv

haskell

I'm trying to read in CSV files where the first row has the names of each column. I then have to edit these files appropriately. I have an idea where when I first read in the file and then create a new datatype called Record, and then all the later records are just instances of this type, now obviously if the program only had to deal with one type of CSV file with a set number of columns this would be easy enough but sadly this won't always be the case.

So my question is can you do something like

createRecordClass (x:xs) = data Record {addRecord(x:xs)}
addRecord (x:xs) = x::String, addRecord xs

or am I just talking crazy and it would be easier just to have a list to represent everything?

like image 736
Ian Fitzpatrick Avatar asked Nov 14 '22 14:11

Ian Fitzpatrick


1 Answers

You could use Template Haskell to achieve what you want. This is a powerful technique to generate Haskell code via Haskell (similar in intent to macros in lisp).

Since you mentioned that you'd like the csv file's header to create a custom data type, you would need to read in the file and then generate a Data type in Template Haskell. A solution I've seen coming closest to what you describe is the CRUD system in Yesod. Check out their Persistent package on Hackage.

like image 180
Chetan Avatar answered Dec 31 '22 07:12

Chetan