Doh!! Still don't quite understand

Hannah Schroeter uk1o@rz.uni-karlsruhe.de
Tue, 10 Oct 2000 23:45:32 +0200


Hello!

On Tue, Oct 10, 2000 at 08:11:08PM +0100, Graeme Turner wrote:

> I have a file of the following format :-

> Surname , Forename , Age , Height e.g.
> <String>, <String>, <Int> , <Int>

> I have a tuple called Person which is defined as (String,String,Int,Int) as
> you would expect.

> What I want to do is to create a function which will
>  1 take a line from the file
>  2 create a Person tuple from the read information

Don't think TOO imperatively.

type Record = (String {- surname -}, String {- forename -}, Int {- age -},
    Int {- height -}

Now write a function that parses one line into that record.

First a helper: Remove leading and trailing whitespace from a string:

import Char (isSpace)
cleanup :: String -> String
cleanup = reverse . dropWhile isSpace . reverse . dropWhile isSpace
-- Think about it!

parseLine :: String -> Record
parseLine s = (surName, foreName, age, height)
  where
    isComma = (',' ==)
    (surname', rest0) = break isComma s
    surname = cleanup surname'
    -- the tail removes the ,
    (foreName', rest1) = break isComma $ tail rest0
    foreName = cleanup foreName'
    (ageString, rest2) = break isComma $ tail rest1
    age = read ageString
    heightString = tail rest2 -- remove ,
    height = read heightString

Then, use that together with my previous mail:

import List(sort)

showRecord :: Record -> String
-- please do at least that for yourself. Mind ++ for string (in fact any list)
-- concatenation, and show to convert the integers into strings

main = do
    input <- readFile "inputfile"
    let ilines = lines input
    let iRecords = map parseLine iLines
    let oRecords = sort iRecords
    -- comparison on tuples is automatically defined if all element types
    -- are comparable (typeclass Ord)
    let olines = map showRecord oRecords
    let output = unlines olines
    putStr output
    -- or writeFile "outputfile" output

> I have defined functions to perform an insertion sort given a tuple of the
> above specification.

Why not import List(sort) or import List(sortBy), if you need your own
comparison?

> Thanks for your time in explaining this to me

> Graeme Turner

Regards, Hannah.