加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift中类似Haskell的as-patterns?

发布时间:2020-12-14 04:31:53 所属栏目:百科 来源:网络整理
导读:Swift与模式匹配中使用的Haskell的 as-patterns有什么相似之处吗?我试图通过使用嵌套模式摆脱下面一段代码中的第二个switch语句: indirect enum Type: CustomStringConvertible { case Int case Fun(Type,Type) var description: String { switch self { c
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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读