Re: [q-lang-users] newbie question on io, etc
Brought to you by:
agraef
From: <mip...@ya...> - 2004-02-22 23:29:13
|
--- s swami <do...@ya...> wrote: > Lets say I have a file containing 2 columns like > this: > > john 12 > mary 56 > peter ab > vincent 24 > lisa 34 > ... > etc. > > I would like to read the file and output something like: > > min score == 12 (John) > max score == 56 (Mary) > avg score == 31.5 > > Illegal values: > ab in column 2 on line 3. > > How would I do this in Q? I would especially like to > see an imperative solution if it exists. I have one solution. reviewf Path = review (split "\n" S) where S:String = fget (fopen Path "r"); // replace 'out of band' values to something appropriate -- or maybe // just write a 'firstdata' review Lines = nextdata (Min,Max,Avg,Bad) Lines 1 where Min = (99999,""), Max = (-99999,""), Avg = (0.0,0), Bad = ""; nextdata (Min,Max,Avg,Bad) [] _ = printf "%s\n%s\n%s\n%s\n" (N,X,V,B) where N = sprintf "min score == %d (%s)" Min, X = sprintf "max score == %d (%s)" Max, V = sprintf "avg score == %.1f (from %d)" Avg, B = "\nIllegal values:\n" ++ Bad; nextdata (Min,Max,Avg,Bad) [L|Ls] Ln = nextdata (N,X,V,B) Ls (Ln + 1) where D = split_data L, N = nextmin Min D, X = nextmax Max D, V = nextavg Avg D, B = nextbad Bad D Ln; nextmin (N1,_) [S2,N2:Int] = (N2,S2) if N1 > N2; nextmin Min _ = Min; nextmax (N1,_) [S2,N2:Int] = (N2,S2) if N1 < N2; nextmax Max _ = Max; nextavg (V,N) [_,X:Int] = ((V*N+X)/N2,N2) where N2 = N + 1; nextavg Avg _ = Avg otherwise; nextbad B [_,N:Int] L = B; nextbad B [S,number N] L = sprintf "%s%s on line %d\n" (B,N,L); nextbad B [_,malformed S] L = sprintf "%smalformed line on line %d: %s\n" (B,L,S); split_data S:String = [Name, number Data] // 'number' can fail: see 'nextbad' where [Name, Data] = filter not_empty (split " \t" S); split_data S:String = ["", `malformed S]; number S = val S if alldigits S; alldigits S = true if [true] = regex "" "^[0-9]+$" S true; = false otherwise; not_empty "" = false; not_empty X = true; ________________________________________________________________________ Yahoo! Messenger - Communicate instantly..."Ping" your friends today! Download Messenger Now http://uk.messenger.yahoo.com/download/index.html |