 public struct Deque<Element> {
   private var front: List<Element> { didSet { check() } }
   private var back : List<Element> { didSet { check() } }
+  private init(_ front: List<Element>, _ back: List<Element>) {
+    (self.front, self.back) = (front, back)
+    check()
+  }
+}
+
+extension Deque {
+  private init(balancedFront: List<Element>, balancedBack: List<Element>) {
+    (front, back) = (balancedFront, balancedBack)
+  }
 }
 
 extension Deque : CustomDebugStringConvertible {


extension Deque {
  public func reverse() -> Deque<Element> {
    return Deque(front: back, back: front)
  }
}

extension Deque {
  public var tail: Deque<Element> {
    var ret = Deque(front: front.tail, back: back)
    ret.check()
    return ret
  }
  public var initial: Deque<Element> {
    var ret = Deque(front: front, back: back.tail)
    ret.check()
    return ret
  }
}


extension Deque {
  public func map<T>(@noescape transform: Element -> T) -> Deque<T> {
    return Deque<T>(
      balancedFront: front.map(transform),
      balancedBack : back .map(transform)
    )
  }
}

extension Deque {
  public func filter(@noescape includeElement: Element -> Bool) -> Deque<Element> {
    return Deque(front.filter(includeElement), back .filter(includeElement))
  }
}

extension Deque {
  public func flatMap<T>(@noescape transform: Element -> Deque<T>) -> Deque<T> {
    return Deque<T>(
      front.flatMap{List(transform($0))},
      back .flatMap{List(transform($0).reverse())}
    )
  }
  
  public func flatMap<T>(@noescape transform: Element -> T?) -> Deque<T> {
    return Deque<T>(front.flatMap(transform), back.flatMap(transform))
  }
}
