nim-lang

Nim program crashes when using recursivity and openarray


The following Nim program crashes and I don't understand why:

proc recursiveExplorer(s: openarray[char]) =
    if s.len == 0: return
    # processing(s[^1])

    recursiveExplorer(s[ 0 ..< (s.len-1)])

var data = readFile("someLargeFile.txt")
var converted = randomData.items.toSeq

recursiveExplorer(data)

The crash occurs when using string or a seq[char] like converted.

I would like to recursively recurse through the string without having to copy the whole string, but in my tests, this approach is way slower than a for loop. Is there a way to cleanly pass string slices without copying the string (or passing indices)?

I am using Nim 2.0.0 on Windows.


Solution

  • Thanks to shirleyquirk for answering this question on the nim forum.

    The crash occurs because the memory consumption of the program is O(n^2), so the program is killed by the OS when the RAM is full.

    To pass a string slice without copying, one can use toOpenArray:

    proc recursiveExplorer(s: openarray[char]) =
        if s.len == 0: return
        # process(s[^1])
        recursiveExplorer(s.toOpenArray(0, s.len-2))
    

    This also works with seq and other array like types.