Haskell-like templates in Swift?

Does Swift have something similar to the Haskell as-patterns used in pattern matching? I am trying to get rid of the second statement switchin the following code snippet using a nested template:

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"

The Haskell equivalent using as-patterns will be as follows:

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
+4
source share
1 answer

Not the same as the Haskell as-pattern, but you can get rid of the second switch statement with a nested template like this:

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)"
    }
}

or by reordering cases:

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)"
    }
}
+1
source

Source: https://habr.com/ru/post/1675425/


All Articles