4
Swift是否有类似于模式匹配中使用的Haskell's as-patterns?我想用嵌套模式,以摆脱在下面这段代码的第二switch
声明:Swift中的Haskell-like-patterns?
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"
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
谢谢,但我实际上是希望避免这种情况。 –
不幸的是,第二个版本并没有做我想做的事情,那就是用parantheses来表示函数类型中的左关联。最后,我去了这个,它使用'where'子句:https://gist.github.com/igstan/b786d870eb28d7e73dcf5223771db6c4 –
@IonuţG.Stan:我已经考虑过这种方法,但认为它是“作弊”因为你仍然使用第二个switch语句(只是间接的)。 –