Dear miran.
I tried your suggestion, and I keep having problems. As you can guess, my idea
is to parse a comma separated value file, or _csv file_ for short. In practice,
csv files are not separated only by commas. You will find people that combine
commas with spaces, or use only spaces. On the contrary of what araq says, I
never had problems of writing efficient two line programs for such a task in a
straightforward way. As previously mentioned, splitWhitespace works. Then I was
able to write something inefficient and messy, such as:
import os, strutils, sequtils, sugar
proc main() =
if paramCount() < 1:
quit("Usage: x-sexpr.x 1000")
let
s = readFile(paramStr(1)).strip.split(Whitespace+{','}) ns = s.join(" ")
xs= ns.splitWhitespace.map(x => x.parseFloat)
echo "Average= ", xs.foldl(a+b)/float(xs.len)
main()
Another possibility is this:
import os, strutils, sequtils, sugar
proc fil(x:string) : bool = x != ""
proc main() =
if paramCount() < 1:
quit("Usage: x-sexpr.x 1000")
let
s= readFile(paramStr(1)).strip.split(Whitespace+{','}) xs=
s.filter(fil).map(x => x.parseFloat)
echo "Average= ", xs.foldl(a+b)/float(xs.len)
main()
I can also add a new iterator/procedure to the strutils.nim library:
iterator splitit*(s: string, seps: set[char]= Whitespace, m: int = -1): string =
oldSplit(s, seps, m)
proc splitit*(s: string,
seps: set[char]= Whitespace,
m: int = -1): seq[string] {.noSideEffect, rtl.}=
accResult(splitit(s, seps, m))
Although they work, all these solutions are convoluted. Well, splitit* is not
convoluted, but I can hardly share it with my collaborators, since it is not in
the strutils library by default. Here are short examples of files that I would
like to parse:
eg> cat csv.data 190, 180, 170, 160, 120, 100,100, 90
eg> cat nums.data 190 45 23 34 89 96 78 97 14 17 54 345 3 42
eg> cat grad.data 190 180 170 160 120 100 100 90
Of course, I started learning Nim three days ago, and I don't have any
experience with Python at all. Probably, if I knew Python, I would be able to
devise a good solution for Nim. However, my experience is with Common Lisp,
where the _clawk library_ allows me to write very efficient Data Munging
programs. To make a long story short, could you suggest a concise and efficient
solution in Nim?