I have a question about how to handle collect.
Is it possible to use collect as an argument of a function, as following?
I don't understand why I get an error in the following source code.
proc toString[T](oa: openArray[T]): seq[string] =
result = @[]
for x in oa:
result.add($x)
var a = @[1,2,3,4,5]
#work fine
var b = toString(a.map(aa => aa*2))
#dosen't work
#Error: type expected
var c = toString(
collect(newSeq):
for aa in a:
aa * 2
)
Please correct any typos on your own brain.Nim thinks toString(collect(newSeq): etc) is an object constructor with toString as the type, collect(newSeq) as the name of one of the fields of that object, and for aa in a: aa * 2 as the value of that field. If you change it to:
var c = toString(
(collect(newSeq):
for aa in a:
aa * 2)
)
Then the expression (collect(newSeq): etc) is a named tuple with collect(newSeq) as one of the field names. You are supposed to do collect(newSeq) do: instead of collect(newSeq): when it's inside other expressions like this. You might argue that Nim shouldn't parse collect(newSeq) as a field name in object or named tuple constructors, but this doesn't fix the issue with calls like:
var c = toString(
collect:
for aa in a:
aa * 2
)
I see.
It means that Nim thought it was a combination of a constructor and a named tuple, not a function call, doesn't it. (I don't know why they don't consider it a function call) I can use collect(newSeq) do: to do what I want to do, so solved my problem.
Thank you very much.