Grabbing the result from stdout(echo) is a bit of a detour. You usually want to
seperate the calculation of something from the I/O. So for example if you later
want to use that function in a GUI application you wouldn't need any
modifications to the function itself, you would fetch the inputs from the GUI
and then put the calculated values back into the GUI.
As a small note, your `output_lcs` proc has the return type `string`, but never
writes to it, so it always returns an empty string when using echo.
Now let's come back to the question. One solution would be always return the
concatenated results of the recursive calls, like so:
proc output_lcs(backtrack: seq[seq[int]], v: string, i: int, j: int):
string =
if i == 0 or j == 0:
return
if backtrack[i][j] == 1:
result.add output_lcs(backtrack, v, i-1, j)
elif backtrack[i][j] == 2:
result.add output_lcs(backtrack, v, i, j-1)
else:
result.add output_lcs(backtrack, v, i-1, j-1)
result.add v[i-1]
Run
The only thing left to do, is to remove the `result = ""` in the calling proc,
so the last statement can count as an implicit return(we could also prepend the
call by a return, but this way it's cleaner)
Alternatively we could also pass a `string` as a var parameter, so we can
modify the passed variable:
proc output_lcs(backtrack: seq[seq[int]], v: string, i: int, j: int,
result: var string)=
if i == 0 or j == 0:
return
if backtrack[i][j] == 1:
output_lcs(backtrack, v, i-1, j)
elif backtrack[i][j] == 2:
output_lcs(backtrack, v, i, j-1)
else:
output_lcs(backtrack, v, i-1, j-1)
result.add v[i-1]
Run
Note that this result variable is not the implicitely defined one from a proc
with return type. Here the name result is just choosen arbitrarily and doesn't
bear any special meaning.
In case we use this method, we also have to change the initial call, so that
the recursive proc writes into the result variable of `lcs_backtrack`:
output_lcs(backtrack, v, vlen, wlen, result)
Run
The latter solution is more efficient, since it only modifies the output the
`string` when needed, though it doesn't really matter in this situation,
because the bottlenecks lie in other places.