如何从Nim的GameMove枚举获取整数值或定义减法操作?
Advent of Code 2022 Day 2 枚举减法问题解决方法
问题场景
在完成Advent of Code 2022第2天题目时,定义了如下枚举:
type GameMove {.pure.} = enum rock = 1, paper = 2, scissors = 3
尝试执行以下计算时触发错误:
ours = rock theirs = scissors echo ours - theirs
错误提示:未定义针对<GameMove, GameMove>的proc '-'
方法一:直接转换为整数值计算
Nim支持用int()将枚举值转为对应整数,直接基于整数完成减法:
let ours = rock let theirs = scissors echo int(ours) - int(theirs) # 输出:-2
方法二:为枚举定义减法操作符
如果需要频繁使用枚举间的减法,可以专门为GameMove实现-操作符:
type GameMove {.pure.} = enum rock = 1, paper = 2, scissors = 3 # 定义返回整数的减法proc proc `-`(a: GameMove, b: GameMove): int = result = int(a) - int(b) # 直接使用减法操作符 let ours = rock let theirs = scissors echo ours - theirs # 输出:-2
如果需要返回结果仍是GameMove类型(比如处理剪刀石头布的循环胜负逻辑),可以调整proc做取模处理:
proc `-`(a: GameMove, b: GameMove): GameMove = let diff = int(a) - int(b) # 处理负数,确保结果落在枚举的有效取值范围内 result = GameMove((diff - 1) mod 3 + 1) let ours = rock let theirs = scissors echo ours - theirs # 输出:paper(对应枚举值2)
内容的提问来源于stack exchange,提问作者shadowtalker
相关产品推荐
相关产品推荐

