简体   繁体   English

如何在 Nim 中将文件行作为参数传递?

[英]How to pass file lines as argument in Nim?

I'm learning Nim and I have a simple program that reads lines of a file.我正在学习 Nim,我有一个读取文件行的简单程序。 I would like to make it testable by extracting the main code in a function that takes an iterable of lines:我想通过提取带有可迭代行的 function 中的主要代码来使其可测试:

func countLines(lines: iterator): int =
  var n = 0
  for _ in lines:
    n += 1
  return n

if isMainModule:
    echo(countLines(lines "some_file.txt"))

The code above doesn't compile because of the following error: Error: attempting to call routine: 'lines' .上面的代码由于以下错误而无法编译Error: attempting to call routine: 'lines'

If I remove the superfluous code, I still get the same error:如果我删除多余的代码,我仍然会得到同样的错误:

echo(lines "some_file.txt")

Why can't I get the result of lines "some_file.txt" and pass it around?为什么我不能得到lines "some_file.txt"的结果并传递它? Is there some way to make this work?有什么方法可以使这项工作吗?

This should be useful: https://nim-lang.org/docs/manual.html#iterators-and-the-for-statement-firstminusclass-iterators这应该是有用的: https://nim-lang.org/docs/manual.html#iterators-and-the-for-statement-firstminusclass-iterators

We could create an intermediate iterator marked as closure that uses the inline lines :我们可以创建一个标记为使用内联linesclosure的中间迭代器:

iterator lines(f: string): string {.closure.} =
  for line in io.lines(f):
    yield line

func countLines(l: iterator(f: string): string, f: string): int =
  var n = 0
  for _ in ls(f):
    n += 1
  return n

when isMainModule:
  echo countLines(lines, "some_file.txt")

Nim allows you to write countLines in this way: Nim 允许您以这种方式编写countLines

func countLines(l: iterator(f: string): string, f: string): int =
  for _ in ls(f):
    inc result

As result is auto-created and auto-returned. result是自动创建和自动返回的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM