79379081

Date: 2025-01-22 20:12:29
Score: 2.5
Natty:
Report link

This is what I came up with using generics. Not sure if this is what the commenter had in mind. I can pass in different types of Tables and I get the correct output.

How do I resolve MyKeyType to float ?

import std/strformat
import std/tables

type 
  Rect = ref object
    x: int
    y: int
  RectTableStringKey = Table[string, Rect]
  RefRectTableStringKey = ref Table[string, Rect]

  MyKeyType = float
  MyValueType = string

  XTableYKey = Table[MyKeyType, MyValueType]
  RefXTableYKey = ref Table[MyKeyType, MyValueType]

proc `$`[K,V](table: Table[K,V]): string = 
  result = fmt"hello from $Table[{$K}, {$V}]"

proc `$`[K,V](table: ref Table[K,V]): string = 
  result = fmt"hello from $refTable[{$K}, {$V}]"

var myTable1: RectTableStringKey
myTable1["one"] = Rect(x:10, y:20)
myTable1["two"] = Rect(x:15, y:25)

var myTable2: RefRectTableStringKey
new myTable2
myTable2["three"] = Rect(x:99, y:100)
myTable2["four"]  = Rect(x:909, y:109)

var myTable3: XTableYKey
myTable3[3.14159] = "hello"
myTable3[2.78183] = "bye"

var myTable4: RefXTableYKey
new myTable4
myTable4[1.2345] = "dog"
myTable4[9.9998] = "horse"


echo myTable1
echo myTable2[]
echo myTable3
echo myTable4[]

Output:

hello from $Table[string, Rect]
hello from $Table[string, Rect]
hello from $Table[MyKeyType, MyValueType]
hello from $Table[MyKeyType, MyValueType]
Reasons:
  • Blacklisted phrase (1): How do I
  • RegEx Blacklisted phrase (1.5): resolve MyKeyType to float ?
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Self-answer (0.5):
  • High reputation (-1):
Posted by: Sonicsmooth