Last active
December 16, 2022 21:38
-
-
Save cgarciae/9b7f5d456e8aed3181f8b30f13de2f01 to your computer and use it in GitHub Desktop.
Type Erasure in Nim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#------------------------------------------------------------- | |
# types | |
#------------------------------------------------------------- | |
type C = concept type C | |
proc name(x: C, msg: string): string | |
type AnyC = object | |
name: proc(msg: string): string # doesn't contain C | |
type A = object | |
type B = object | |
#------------------------------------------------------------- | |
# procs | |
#------------------------------------------------------------- | |
proc name(x: A, msg: string): string = "A" & msg | |
proc name(x: B, msg: string): string = "B" & msg | |
proc name(x: AnyC, msg: string): string = x.name(msg) # AnyC implements C | |
proc to_any(x: A): AnyC = AnyC( | |
name: proc (msg: string): string = name(x, msg) # x captured by proc | |
) | |
proc to_any(x: B): AnyC = AnyC( | |
name: proc (msg: string): string = name(x, msg) # x captured by proc | |
) | |
# actually use C | |
proc print_name(x: C, msg: string) = echo x.name(msg) | |
#------------------------------------------------------------- | |
# main | |
#------------------------------------------------------------- | |
let a = A() | |
let b = B() | |
let cs = [a.to_any(), b.to_any()] # the main goal of most erasure cases | |
for c in cs: | |
c.print_name(" erased") # e.g. "A erased" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment