Found couple of problems with the code below, not sure if it's a bug or I'm doing something wrong
1 That code would produce SIGSEGV: Illegal storage access. (Attempt to read from nil?) play
import strutils, sugar, nre
proc my_replace*(s: string, r: Regex, by: string | (proc (match: string): string)): string =
nre.replace(s, r, by)
echo my_replace("abcde", re"[bcd]", (match) => match.to_upper) == "aBCDe"
2 This slight variation of the code won't compile play
import strutils, sugar, nre
proc my_replace*(s: string, r: Regex, by: string | (proc (match: string): string)): string =
nre.replace(s, r, by)
echo my_replace("abcde", re"[bcd]", proc (match: string): string = match.to_upper) == "aBCDe"
3 But if you add one more function call - it will compile, but throws SIGSEV runtime error, play
import strutils, sugar, nre
proc my_replace*(s: string, r: Regex, by: string | (proc (match: string): string)): string =
nre.replace(s, r, by)
echo my_replace("abcde", re"[bcd]", (match) => match.to_upper) == "aBCDe"
echo my_replace("abcde", re"[bcd]", proc (match: string): string = match.to_upper) == "aBCDe"
The problem would go avay if single proc with the union type ... by: string | (proc (match: string): string) ... declared as 2 procs.
Thanks for the solution, it compiles with {.closure.}
import strutils, sugar, nre
proc my_replace*(s: string, r: Regex, by: string or (proc (match: string): string)): string =
nre.replace(s, r, by)
echo my_replace("abcde", re"[bcd]", proc(match: string): string {.closure.} = match.to_upper) == "aBCDe"
Although I'm strongly against that solution and believe that such simple code as replace("abc", re"b", (s) => s.to_upper) should just work and not require any annotations.
Although I'm strongly against that solution and believe that such simple code as ...
Compiler crashes are bad of course and will be fixed. But in general: We moved away from the "I think this should compile" style of language development. There is a spec, closures cause conversions, conversions are not lifted to container ("or") types. "or" types are not particularly "simple".