Swift中是否有类似于Haskell的模式匹配中使用的as-patterns?我正在尝试通过使用嵌套模式来消除以下代码片段中的第二个switch
语句:
indirect enum Type: CustomStringConvertible {
case Int
case Fun(Type, Type)
var description: String {
switch self {
case .Int: return "int"
case .Fun(let p, let r):
switch p {
case .Fun(_): return "(\(p)) -> \(r)"
case _: return "\(p) -> \(r)"
}
}
}
}
Type.Int // "int"
Type.Fun(.Int, .Int) // "int -> int"
Type.Fun(Type.Fun(.Int, .Int), .Int) // "(int -> int) -> int"
使用 as-patterns 的 Haskell 等效代码如下:
data Type =
Int
| Fun Type Type
desc :: Type -> String
desc t =
case t of
Int -> "int"
Fun (p @ (Fun _ _)) r -> "(" ++ desc p ++ ") -> " ++ desc r
Fun p r -> desc p ++ " -> " ++ desc r
where
子句:https://gist.github.com/igstan/b786d870eb28d7e73dcf5223771db6c4 - Ionuț G. Stanswitch
看起来更容易阅读。就这样。 - Ionuț G. Stan.Int
和.Fun
之外还有其他情况时,比如.Bool
或.String
,它就变得很丑陋。现在我们也必须列出这些嵌套的情况。不过还是谢谢你的帮助。希望Swift将来能够获得模式匹配。 - Ionuț G. Stanwhere case .Fun = p
子句将是一个干净的解决方案(正如您在Swift邮件列表上所写的那样)。 - Martin R