Swift与模式匹配中使用的Haskell的 as-patterns有什么相似之处吗?我试图通过使用嵌套模式摆脱下面一段代码中的第二个switch语句: indirect enum Type: CustomStringConvertible { case Int case Fun(Type, T
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与Haskell as-pattern不同,但你可以摆脱它
第二个带有嵌套模式的switch语句,如下所示:
var description: String { switch self { case .Int: return "int" case .Fun(.Fun(let p, let q), let r): return "(\(Type.Fun(p, q))) -> \(r)" case .Fun(let p, let r): return "\(p) -> \(r)" } }
或通过重新安排案件:
var description: String { switch self { case .Int: return "int" case .Fun(.Int, let r): return "int -> \(r)" case .Fun(let p, let r): return "(\(p)) -> \(r)" } }