Hi I need some tips to cleanup my code. My 4 ctors are very similar, I want to
use templates to avoid duplicate codes. However I don't know if templates
create unique global variable for each of those ctor functions:
import tables, options, sequtils
type
Male = object
id: int
name: string
Female = object
id: int
name: string
Ranking = int
Husband = object
base: ptr[Male]
preferences: Table[ptr[Female], Ranking]
engagedTo: Option[ptr[Female]]
Wife = object
base: ptr[Female]
preferences: Table[ptr[Male], Ranking]
engagedTo: Option[ptr[Male]]
MatchPool = object
pairCount: int
husbands: seq[ptr[Husband]]
wives: seq[ptr[Wife]]
template initMaleOrFemale(name: string = "Unnamed"): untyped =
var nextID {.global.} = 0 # is nextID unique/hygienic for male and
female?
result.id = nextID
result.name = name
inc nextID
proc newMale(name: string = "Unnamed Male"): Male =
# var nextID {.global.} = 0
# result.id = nextID
# result.name = name
# inc nextID
initMaleOrFemale(name)
proc newFemale(name: string = "Unnamed Female"): Female =
# var nextID {.global.} = 0
# result.id = nextID
# result.name = name
# inc nextID
initMaleOrFemale(name)
func newHusband(base: ptr[Male]; preferences: openArray[ptr[Female]]):
Husband =
result.base = base
for idx, femalePtr in preferences:
result.preferences[femalePtr] = preferences.high() - idx
func newWife(base: ptr[Female]; preferences: openArray[ptr[Male]]): Wife =
result.base = base
for idx, malePtr in preferences:
result.preferences[malePtr] = preferences.high() - idx
func prefersMoreThanCurrentHusband(wife: Wife; probeHusband: ptr[Male]):
bool =
if wife.engagedTo.isNone:
return true
else:
return wife.preferences[wife.engagedTo.unsafeGet] <
wife.preferences[probeHusband]
proc engage(wife: ptr[Wife]; husband: ptr[Husband]) =
wife.engagedTo = some(husband.base)
husband.engagedTo = some(wife.base)
proc disengage(wife: ptr[Wife]; husband: ptr[Husband]) =
wife.engagedTo = none[ptr[Male]]()
husband.engagedTo = none[ptr[Female]]()
func newMatchPool(husbands: openArray[ptr[Husband]]; wives: openArray[ptr[
Wife]]): Option[MatchPool] =
var prefCount = husbands.len()
if wives.len() == prefCount and husbands.allIt(it.preferences.len() ==
prefCount) and wives.allIt(it.preferences.len() == prefCount):
return some[MatchPool](MatchPool(husbands: husbands.toSeq(),
wives: wives.toSeq()))
else: return none[MatchPool]()
Run
Also, does the compiler automatically treat procs as func's if possible?