Open
Description
I want a hamming-distance function that works both on arrays of length 4 and on arrays of length 8192. For now, it seems I must copy-paste code. Please consider the following and tell me how to improve it !
@dataclass
class LpBhv:
# Issue 2083: can't say HDC_DIM
dim : i32 = 8192
a : i8[8192] = empty(8192, dtype=int8)
def hamming_lp_bhv(this : LpBhv, that : LpBhv) -> i32:
"""ATTENTION: THE FOLLOWING CODE IS DUPLICATED BELOW
"""
i : i32
assert this.dim == that.dim
result : i32 = 0
for i in range(this.dim):
low1 : i32 = i32(this.a[i]) & 0x0F
hig1 : i32 = i32(this.a[i]) & 0xF0 >> 4
low2 : i32 = i32(that.a[i]) & 0x0F
hig2 : i32 = i32(that.a[i]) & 0xF0 >> 4
result += NIBBLE_HAMMINGS[low1][low2]
result += NIBBLE_HAMMINGS[hig1][hig2]
return result
@dataclass
class LpBhvSmall:
dim : i32 = 4
a : i8[4] = empty(4, dtype=int8)
def hamming_lp_bhv_smalll(this : LpBhvSmall, that : LpBhvSmall) -> i32:
"""ATTENTION: THE ONLY DIFFERENCE IS IN THE TYPES!
Could some kind of polymorphism save this duplication?
"""
i : i32
assert this.dim == that.dim
result : i32 = 0
for i in range(this.dim):
low1 : i32 = i32(this.a[i]) & 0x0F
hig1 : i32 = i32(this.a[i]) & 0xF0 >> 4
low2 : i32 = i32(that.a[i]) & 0x0F
hig2 : i32 = i32(that.a[i]) & 0xF0 >> 4
result += NIBBLE_HAMMINGS[low1][low2]
result += NIBBLE_HAMMINGS[hig1][hig2]
return result