Swift中类似Haskell的模式?

Ion*_*tan 5 haskell pattern-matching swift

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"
Run Code Online (Sandbox Code Playgroud)

使用as-pattern的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
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 1

与 Haskell as 模式不同,但您可以使用如下所示的嵌套模式摆脱第二个 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)"
    }
}
Run Code Online (Sandbox Code Playgroud)

或者通过重新排列案例:

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)"
    }
}
Run Code Online (Sandbox Code Playgroud)