Reputation: 2734
Short-and-sweet, I have a text file that looks like this:
ID1|ID2|DATE|SUM
0|0|20/03/2014|100.00
0|1|20/04/2014|99.00
I have a custom data type that looks like this:
data DBData = DBData { id1 :: Int
, id2 :: Int
, date :: String
, sum :: Int
} deriving (Eq, Read, Show)
How do I get this into that?
What I have been toying with so far is using something like this:
parseRow :: [String] -> DBData
parseRow = let (id1:id2:date:sum) = (splitWhen (=='|')) s
i = read id1
in DBData {id1 = i}
But I can't seem to get the syntax right ...
related to my other post: https://stackoverflow.com/questions/25477554/using-splitwhen-to-split-string-by-delimiter-and-trying-to-figure-out-how-to-sto
Upvotes: 1
Views: 1172
Reputation: 10793
In Haskell, all data constructors and concrete types must begin with a capital letter:
data DbData = DbData ...
Also, if you want to use the read
method to read in something in a custom format like that, you must make a the data type an instance of Read
:
instance Read DbData where
read s = ...
Inside the instance definition you can define read
as you would any other Haskell function.
Also, the proper let
syntax (outside a do
block) is
let binding = val
in
... body ...
When you create a data type, you (usually) make one or more constructors that you can use to make values of that type. Here is an example that is sort of similar to yours
data Example = Example { a :: Int
, b :: Char
, c :: String
}
We can make a value of type Example
using the Example
constructor (note that these don't need to have the same name):
exampleValue :: Example
example = Example 1 'z' "abcdef"
Upvotes: 4