I'm trying to write map_csv function, so that if you provide it a CSV file name and a function how to convert row to Object it would return list of such Objects.
import strformat, sugar
proc map_csv[T](
csv_file_path: string,
map: (
row: (key: string) -> string
) -> T
): seq[T] =
for i in 1..3:
result.add map(proc (key: string): string = fmt"{key} {i}")
result
proc load_companies1(): seq[string] =
map_csv("companies.csv", (row) => row("symbol"))
echo load_companies1()
But I can't create multiline proc with sugar
proc load_companies2(): seq[string] =
map_csv("companies.csv", (row) =>
# How to specify multiline?
let v = row("symbol")
v
)
echo load_companies2()
And also exprimental do with sugar and type infer
proc load_companies3(): seq[string] =
map_csv("companies.csv") do row
let v = row("symbol")
v
echo load_companies3()
Is there a way to do that?
P.S.
Also, sugar seems to fail to infer this line result.add map(proc (key: string): string = fmt"{key} {i}") - could it be inferred?
Multiline lambdas: Use a proc or a block:
proc load_companies2(): seq[string] =
map_csv("companies.csv", (row) => block:
let v = row("symbol")
v
)
Or the verbose way
proc load_companies2(): seq[string] =
map_csv("companies.csv", proc(row:(string)->string):string =
let v = row("symbol")
v
)
echo load_companies2()
Thanks, but seems like it's not compiling..., do I miss something?
import strformat, sugar
proc map_csv[T](
csv_file_path: string,
map: (
row: (key: string) -> string
) -> T
): seq[T] =
for i in 1..3:
result.add map(proc (key: string): string = fmt"{key} {i}")
result
proc load_companies2(): seq[string] =
map_csv("companies.csv", (row) => block:
let v = row("symbol")
v
)