[Haskell-beginners] Parsing a file with data divided into sections
Patrick LeBoutillier
patrick.leboutillier at gmail.com
Tue Feb 3 20:58:55 EST 2009
Hi all,
I wanted to parse a file that looks like this:
MONDAY
JOHN
JIM
LINDA
TUESDAY
BILL
BOB
WEDNESDAY
THURSDAY
SAM
TODD
LARRY
LUKE
FRIDAY
TED
in order to count the number of people for each day. After a (very)
long time and a lot of trial and
error, I managed to do it with this program:
import Char (isSpace)
main = interact (unlines . countSections . lines)
where countSections = map (show) . snd . foldr compileSections (0, [])
compileSections line (n, acc) =
if isSection line
then (0, (line, n) : acc)
else (n + 1, acc)
isSection line = not . isSpace . head $ line
which outputs:
("MONDAY",3)
("TUESDAY",2)
("WEDNESDAY",0)
("THURSDAY",4)
("FRIDAY",1)
I had quite a hard time figuring out how to keep count of the number
of records in each sections.
Is there a more obvious way to handle these types of problems? Are
there some builtins that could
of made it easier?
In Perl I would probably have used a hash and a variable to keep count
of the current day, incrementing
the hash value for each person until I got to the next day, but it's
not obvious to me how to transpose this
technique to functional programming.
Thanks a lot,
Patrick
--
=====================
Patrick LeBoutillier
Rosemère, Québec, Canada
More information about the Beginners
mailing list