2017-04-23 19 views
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 

回答

1

不一样的哈斯克尔的模式,但你可以摆脱 第二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)" 
    } 
} 

或REA整理案例:

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

谢谢,但我实际上是希望避免这种情况。 –

+0

不幸的是,第二个版本并没有做我想做的事情,那就是用parantheses来表示函数类型中的左关联。最后,我去了这个,它使用'where'子句:https://gist.github.com/igstan/b786d870eb28d7e73dcf5223771db6c4 –

+0

@IonuţG.Stan:我已经考虑过这种方法,但认为它是“作弊”因为你仍然使用第二个switch语句(只是间接的)。 –