我正在尝试在 Haskell中以更通用的术语模拟版本编号。我正在寻找一个代表我自己定义的结构的 Haskell 数据结构(VersionNumberWithMaybe
)。
data VersionCompoundWithMaybe = Maybe Int -- Just n: 0, 1, 2, 3 ...
-- Nothing: x
maybeToString :: Maybe Int -> String
maybeToString (Just n) = (show n)
maybeToString Nothing = "x"
data VersionNumberWithMaybe = VC (Maybe Int) -- VersionCompound: x, 0, 1, 2, 3 ...
| VNL (Maybe Int) VersionNumberWithMaybe -- VersionNumberLeft: x.x, x.0, x.1, x.2, ... , 1.0, 1.1, 1.2, ... 1.x.x, 2.x.x, 3.x.x, ...
| VNR VersionNumberWithMaybe (Maybe Int) -- VersionNumberRight: the same as above, only underlying structure is different for simple parsing pursposes: x.x, x.0, x.1, x.2, ... , 1.0, 1.1, 1.2, ... 1.x.x, 2.x.x, 3.x.x, ...
deriving (Show)
versionNumberWithMaybeToString :: VersionNumberWithMaybe -> String
versionNumberWithMaybeToString (VNL vc vn) = (maybeToString vc) ++ "." ++ (versionNumberWithMaybeToString vn)
versionNumberWithMaybeToString (VNR vn vc) = (versionNumberWithMaybeToString vn) ++ "." ++ (maybeToString vc)
versionNumberWithMaybeToString (VC vc) = (maybeToString vc)
是否有类似的标准库实现可以将字符串解析为这种数据结构并在左右表示之间进行转换?我将不胜感激任何评论/想法。提前致谢!
PS。我需要VNL
和VNR
选项,以便我可以按以下方式比较版本号:x.x.3
== x.3
== 3
。我假设只有VNR
版本可以用于此目的:
instance Eq VersionNumberWithMaybe where
(VC vc1) == (VC vc2) = (vc1 == vc2)
( VNL vc1 vn1 ) == ( VNL vc2 vn2 ) = (vc1 == vc2 && vn1 == vn2)
( VNR vn1 vc1 ) == ( VNR vn2 vc2 ) = (vc1 == vc2 && vn1 == vn2)
( VNL _ (VC vc1) ) == ( VC vc2 ) = vc1 == vc2
( VC vc1 ) == ( VNL _ (VC vc2)) = vc1 == vc2
( VNR _ vc1 ) == (VC vc2) = vc1 == vc2
( VC vc1 ) == (VNR _ vc2) = vc1 == vc2
鉴于 的这个定义Eq
,以下比较将按预期正常工作:
VNR (VNR ( VC Nothing ) Nothing) (Just 3) == VNR (VC Nothing) (Just 3) -- x.x.3 == x.3 -> True
VNR (VC Nothing) (Just 3) == VC (Just 3) -- x.3 == 3 -> True
虽然VNL
它不会按预期工作,因为它会允许进行这样的3.x.x == 3.x -> True
比较
PS2。谢谢大家的意见。我开始重新思考我是否真的需要两者VNR
和VNL
(而不仅仅是,例如,VNL
)来实现我想要的。我正在评估哪种方法最好只留下一个并避免整个conversion_between_representations 头痛。