The following program is supposed to calculate the average of a list of numbers:
# File: awg.nim import os, strutils, sequtils, sugar
proc main() =
if paramCount() < 1:
quit("Usage: x-sexpr.x 1000")
let
s = readFile(paramStr(1)).split(Whitespace) xs= s.map(x => parseFloat x)
echo "Average= ", xs.foldl(a + b)/float(xs.len)
main()
Here is the list of numbers: eg> cat grad.data ~/nim/tutorial/eg 190 180 170
160 120 100 100 90 eg> _
The program compiles without incidents: eg> nim c -o:awg.x -d:release
--nimcache:lixo awg.nim
However, it does not work:
eg> ./awg.x grad.data strutils.nim(1140) parseFloat Error: unhandled exception:
invalid float: [ValueError]
I discovered that split leaves an empty string "" in the xs seq
Now, let us modify the program a bit:
eg# cat avg.nim # nim c -d:release -o:avg.x avg.nim import os, strutils,
sequtils, sugar
proc main() =
if paramCount() < 1:
quit("Usage: x-sexpr.x 1000")
let
s = readFile(paramStr(1)).splitWhitespace xs= s.map(x => parseFloat x)
echo "Average= ", xs.foldl(a + b)/float(xs.len)
main()
The only difference between avg.nim and awg.nim is that I replaced
.split(Whitespace) with .splitWhitespace. However, the second version works:
eg> ./avg.x grad.data Average= 138.75
The fact is that split(Whitespace) leaves an empty string "" in the sequence,
while splitWhitespace does not.