PageRenderTime 124ms CodeModel.GetById 18ms app.highlight 94ms RepoModel.GetById 1ms app.codeStats 0ms

/core/src/main/scala/scalaz/FingerTree.scala

http://github.com/scalaz/scalaz
Scala | 1183 lines | 860 code | 195 blank | 128 comment | 21 complexity | 7103d9cde9443bbf5a679d33e71114d4 MD5 | raw file
   1package scalaz
   2
   3import scala.collection.Iterator
   4import Maybe.Just
   5import std.list.listMonoid
   6import std.option._
   7import std.stream.streamMonoid
   8import syntax.Ops
   9import syntax.semigroup._
  10import FingerTree._
  11import Tags.LastVal
  12
  13/**
  14 * Finger trees with leaves of type A and Nodes that are annotated with type V.
  15 *
  16 * Finger Trees provide a base for implementations of various collection types,
  17 * as described in "Finger trees: a simple general-purpose data structure", by
  18 * Ralf Hinze and Ross Paterson.
  19 * A gentle introduction is presented in the blog post "Monoids and Finger Trees" by Heinrich Apfelmus.
  20 *
  21 * This is done by choosing a suitable type to annotate the nodes. For example,
  22 * a binary tree can be implemented by annotating each node with the size of its subtree,
  23 * while a priority queue can be implemented by labelling the nodes by the minimum priority of its children.
  24 *
  25 * The operations on FingerTree enforce the constraint measured (in the form of a Reducer instance).
  26 *
  27 * Finger Trees have excellent (amortized) asymptotic performance:
  28 *
  29 *  - Access to the first and last elements is `O(1)`
  30 *  - Appending/prepending a single value is `O(1)`
  31 *  - Concatenating two trees is `(O lg min(l1, l2))` where `l1` and `l2` are their sizes
  32 *  - Random access to an element at `n` is `O(lg min(n, l - n))`, where `l` is the size of the tree.
  33 *  - Constructing a tree with n copies of a value is O(lg n).
  34 *
  35 * @tparam V The type of the annotations of the nodes (the '''measure''')
  36 * @tparam A The type of the elements stored at the leaves
  37 *
  38 * @see [[https://www.staff.city.ac.uk/~ross/papers/FingerTree.pdf Finger trees: a simple general-purpose data structure]]
  39 * @see [[https://apfelmus.nfshost.com/articles/monoid-fingertree.html]]
  40 */
  41sealed abstract class FingerTree[V, A](implicit measurer: Reducer[A, V]) {
  42  import measurer.semigroup
  43
  44  def measure: Maybe[V] =
  45    fold(Maybe.empty, (v, _) => Just(v), (v, _, _, _) => Just(v))
  46
  47  def foldMap[B](f: A => B)(implicit s: Monoid[B]): B =
  48    fold(s.zero, (v, x) => f(x), (v, pr, m, sf) =>
  49      s.append(s.append(pr.foldMap(f), m.foldMap(x => x.foldMap(f))), sf.foldMap(f)))
  50
  51  def foldRight[B](z: => B)(f: (A, => B) => B): B = {
  52    foldMap(a => Endo.endoByName[B](f(a, _))).apply(z)
  53  }
  54
  55  def foldLeft[B](b: B)(f: (B, A) => B): B = {
  56    fold(b,
  57          (v, a) => f(b, a),
  58          (v, pr, m, sf) =>
  59              fingerFoldable[V].foldLeft(sf, m.foldLeft[B](fingerFoldable[V].foldLeft(pr, b)(f))((x, y) => nodeFoldable[V].foldLeft(y, x)(f)))(f))
  60  }
  61
  62  /**
  63   * Fold over the structure of the tree. The given functions correspond to the three possible variations of the finger tree.
  64   *
  65   * @param empty value to return if the tree is empty
  66   * @param single if the tree contains a single element, convert the measure and this element to a `B`
  67   * @param deep otherwise, convert the measure, the two fingers, and the sub tree to a `B`.
  68   */
  69  def fold[B](empty: => B, single: (V, A) => B, deep: (V, Finger[V, A], => FingerTree[V, Node[V, A]], Finger[V, A]) => B): B
  70
  71  /** Prepends an element to the left of the tree. O(1). */
  72  def +:(a: A): FingerTree[V, A] = {
  73    implicit val nm: Reducer[FingerTree.Node[V, A], V] = nodeMeasure[A, V]
  74    fold(
  75      single(measurer.unit(a), a),
  76      (v, b) => deep(measurer.cons(a, v), one(a), empty[V, Node[V, A]], one(b)),
  77      (v, pr, m, sf) => {
  78        val mz = m
  79        pr match {
  80          case Four(vf, b, c, d, e) => deep(measurer.cons(a, v), two(a, b), node3[V, A](c, d, e) +: mz, sf)
  81          case _ => deep(measurer.cons(a, v), a +: pr, mz, sf)
  82      }})
  83  }
  84
  85  /** Appends an element to the right of the tree. O(1). */
  86  def :+(a: => A): FingerTree[V, A] = {
  87    implicit val nm: Reducer[FingerTree.Node[V, A], V] = nodeMeasure[A, V]
  88    val az = Need(a)
  89    fold(
  90      single(measurer.unit(az.value), az.value),
  91      (v, b) => deep(measurer.snoc(v, az.value), one(b), empty[V, Node[V, A]], one(az.value)),
  92      (v, pr, m, sf) => {
  93        val mz = m
  94        sf match {
  95          case Four(vf, b, c, d, e) => deep(measurer.snoc(v, az.value), pr, (mz :+ node3(b, c, d)), two(e, az.value))
  96          case _ => deep(measurer.snoc(v, az.value), pr, mz, sf :+ az.value)
  97      }})
  98  }
  99
 100  /** Replace the first element of the tree with the given value. O(1) */
 101  def |-:(a: A): FingerTree[V, A] =
 102    fold(
 103      sys.error("Replacing first element of an empty FingerTree"),
 104      (v, b) => single(a),
 105      (v, pr, m, sf) => deep(a |-: pr, m, sf))
 106
 107  /** Replace the last element of the tree with the given value. O(1) */
 108  def :-|(a: => A): FingerTree[V, A] = {
 109    val az = Need(a)
 110    fold(
 111      sys.error("Replacing last element of an empty FingerTree"),
 112      (v, b) => single(az.value),
 113      (v, pr, m, sf) => deep(pr, m, sf :-| az.value))
 114  }
 115
 116  /** Appends the given finger tree to the right of this tree. */
 117  def <++>(right: => FingerTree[V, A]): FingerTree[V, A] = {
 118    val rightz = Need(right)
 119    fold(
 120      rightz.value,
 121      (v, x) => x +: rightz.value,
 122      (v1, pr1, m1, sf1) =>
 123        rightz.value.fold(
 124          this,
 125          (v, x) => this :+ x,
 126          (v2, pr2, m2, sf2) => deep(measurer.append(v1, v2), pr1, addDigits0(m1, sf1, pr2, m2), sf2)
 127        )
 128    )
 129  }
 130
 131  private type ATree = FingerTree[V, A]
 132  private type AFinger = Finger[V, A]
 133  private type NodeTree = FingerTree[V, Node[V, A]]
 134
 135  def add1(n: A, right: => ATree): ATree = {
 136    val rightz = Need(right)
 137    fold(
 138      n +: rightz.value,
 139      (v, x) => x +: n +: rightz.value,
 140      (v1, pr1, m1, sf1) =>
 141        rightz.value.fold(
 142          this :+ n,
 143          (v, x) => this :+ n :+ x,
 144          (v2, pr2, m2, sf2) =>
 145            deep(measurer.append((measurer.snoc(v1, n)), v2), pr1, addDigits1(m1, sf1, n, pr2, m2), sf2)
 146        )
 147    )
 148  }
 149
 150  def add2(n1t: => A, n2t: => A, right: => ATree): ATree = {
 151    val rightz = Need(right)
 152    val n1 = Need(n1t)
 153    val n2 = Need(n2t)
 154    fold(
 155      n1.value +: n2.value +: rightz.value,
 156      (v, x) => x +: n1.value +: n2.value +: rightz.value,
 157      (v1, pr1, m1, sf1) =>
 158        rightz.value.fold(
 159          this :+ n1.value :+ n2.value,
 160          (v, x) => this :+ n1.value :+ n2.value :+ x,
 161          (v2, pr2, m2, sf2) =>
 162            deep(measurer.append(measurer.snoc(measurer.snoc(v1, n1.value), n2.value), v2),
 163              pr1, addDigits2(m1, sf1, n1.value, n2.value, pr2, m2), sf2)
 164        )
 165    )
 166  }
 167
 168  def add3(n1t: => A, n2t: => A, n3t: => A, right: => ATree): ATree = {
 169    val rightz = Need(right)
 170    val n1 = Need(n1t)
 171    val n2 = Need(n2t)
 172    val n3 = Need(n3t)
 173    fold(
 174      n1.value +: n2.value +: n3.value +: rightz.value,
 175      (v, x) => x +: n1.value +: n2.value +: n3.value +: rightz.value,
 176      (v1, pr1, m1, sf1) =>
 177        rightz.value.fold(
 178           this :+ n1.value :+ n2.value :+ n3.value,
 179           (v, x) => this :+ n1.value :+ n2.value :+ n3.value :+ x,
 180           (v2, pr2, m2, sf2) =>
 181             deep(measurer.append(measurer.snoc(measurer.snoc(measurer.snoc(v1, n1.value), n2.value), n3.value), v2),
 182               pr1, addDigits3(m1, sf1, n1.value, n2.value, n3.value, pr2, m2), sf2)
 183        )
 184    )
 185  }
 186
 187  def add4(n1t: => A, n2t: => A, n3t: => A, n4t: => A, right: => ATree): ATree = {
 188    val rightz = Need(right)
 189    val n1 = Need(n1t)
 190    val n2 = Need(n2t)
 191    val n3 = Need(n3t)
 192    val n4 = Need(n4t)
 193    fold(
 194      n1.value +: n2.value +: n3.value +: n4.value +: rightz.value,
 195      (v, x) => x +: n1.value +: n2.value +: n3.value +: n4.value +: rightz.value,
 196      (v1, pr1, m1, sf1) =>
 197        rightz.value.fold(
 198          this :+ n1.value :+ n2.value :+ n3.value :+ n4.value,
 199          (v, x) => this :+ n1.value :+ n2.value :+ n3.value :+ n4.value :+ x,
 200          (v2, pr2, m2, sf2) =>
 201            deep(measurer.append(measurer.snoc(measurer.snoc(measurer.snoc(measurer.snoc(v1, n1.value), n2.value), n3.value), n4.value), v2),
 202              pr1, addDigits4(m1, sf1, n1.value, n2.value, n3.value, n4.value, pr2, m2), sf2)
 203        )
 204    )
 205  }
 206
 207  def addDigits0(m1: NodeTree, dig1: AFinger, dig2: AFinger, m2: => NodeTree): NodeTree = dig1 match {
 208    case One(_, a) => dig2 match {
 209      case One(_, b) => m1.add1(node2(a, b), m2)
 210      case Two(_, b,c) => m1.add1(node3(a,b,c), m2)
 211      case Three(_, b,c,d) => m1.add2(node2(a,b), node2(c,d),m2)
 212      case Four(_, b,c,d,e) => m1.add2(node3(a,b,c), node2(d,e), m2)
 213    }
 214    case Two(_, a,b) => dig2 match {
 215      case One(_, c) => m1.add1(node3(a,b,c), m2)
 216      case Two(_, c,d) => m1.add2(node2(a,b), node2(c,d), m2)
 217      case Three(_, c,d,e) => m1.add2(node3(a,b,c), node2(d,e), m2)
 218      case Four(_, c,d,e,f) => m1.add2(node3(a,b,c), node3(d,e,f), m2)
 219    }
 220    case Three(_, a,b,c) => dig2 match {
 221      case One(_, d) => m1.add2(node2(a,b), node2(c,d), m2)
 222      case Two(_, d,e) => m1.add2(node3(a,b,c), node2(d,e), m2)
 223      case Three(_, d,e,f) => m1.add2(node3(a,b,c), node3(d,e,f), m2)
 224      case Four(_, d,e,f,g) => m1.add3(node3(a,b,c), node2(d,e), node2(f,g), m2)
 225    }
 226    case Four(_, a,b,c,d) => dig2 match {
 227      case One(_, e) => m1.add2(node3(a,b,c), node2(d,e), m2)
 228      case Two(_, e,f) => m1.add2(node3(a,b,c), node3(d,e,f), m2)
 229      case Three(_, e,f,g) => m1.add3(node3(a,b,c), node2(d,e), node2(f,g), m2)
 230      case Four(_, e,f,g,h) => m1.add3(node3(a,b,c), node3(d,e,f), node2(g,h), m2)
 231    }
 232  }
 233
 234  def addDigits1(m1: NodeTree, d1: AFinger, xt: => A, d2: AFinger, m2t: => NodeTree): NodeTree = {
 235    val x = Need(xt)
 236    val m2 = Need(m2t)
 237    d1 match {
 238      case One(_, a) => d2 match {
 239        case One(_, b) => m1.add1(node3(a,x.value,b), m2.value)
 240        case Two(_, b,c) => m1.add2(node2(a,x.value), node2(b,c), m2.value)
 241        case Three(_, b,c,d) => m1.add2(node3(a,x.value,b), node2(c,d), m2.value)
 242        case Four(_, b,c,d,e) => m1.add2(node3(a,x.value,b), node3(c,d,e), m2.value)
 243      }
 244      case Two(_, a,b) => d2 match {
 245        case One(_, c) => m1.add2(node2(a,b), node2(x.value,c), m2.value)
 246        case Two(_, c,d) => m1.add2(node3(a,b,x.value), node2(c,d), m2.value)
 247        case Three(_, c,d,e) => m1.add2(node3(a,b,x.value), node3(c,d,e), m2.value)
 248        case Four(_, c,d,e,f) => m1.add3(node3(a,b,x.value), node2(c,d), node2(e,f), m2.value)
 249      }
 250      case Three(_, a,b,c) => d2 match {
 251        case One(_, d) => m1.add2(node3(a,b,c), node2(x.value,d), m2.value)
 252        case Two(_, d,e) => m1.add2(node3(a,b,c), node3(x.value,d,e), m2.value)
 253        case Three(_, d,e,f) => m1.add3(node3(a,b,c), node2(x.value,d), node2(e,f), m2.value)
 254        case Four(_, d,e,f,g) => m1.add3(node3(a,b,c), node3(x.value,d,e), node2(f,g), m2.value)
 255      }
 256      case Four(_, a,b,c,d) => d2 match {
 257        case One(_, e) => m1.add2(node3(a,b,c), node3(d,x.value,e), m2.value)
 258        case Two(_, e,f) => m1.add3(node3(a,b,c), node2(d,x.value), node2(e,f), m2.value)
 259        case Three(_, e,f,g) => m1.add3(node3(a,b,c), node3(d,x.value,e), node2(f,g), m2.value)
 260        case Four(_, e,f,g,h) => m1.add3(node3(a,b,c), node3(d,x.value,e), node3(f,g,h), m2.value)
 261      }
 262    }
 263  }
 264
 265  def addDigits2(m1: NodeTree, d1: AFinger, xt: => A, yt: => A, d2: AFinger, m2t: => NodeTree): NodeTree = {
 266    val x = Need(xt)
 267    val y = Need(yt)
 268    val m2 = Need(m2t)
 269    d1 match {
 270      case One(_, a) => d2 match {
 271        case One(_, b) => m1.add2(node2(a,x.value), node2(y.value,b), m2.value)
 272        case Two(_, b,c) => m1.add2(node3(a,x.value,y.value), node2(b,c), m2.value)
 273        case Three(_, b,c,d) => m1.add2(node3(a,x.value,y.value), node3(b,c,d), m2.value)
 274        case Four(_, b,c,d,e) => m1.add3(node3(a,x.value,y.value), node2(b,c), node2(d,e), m2.value)
 275      }
 276      case Two(_, a,b) => d2 match {
 277        case One(_, c) => m1.add2(node3(a,b,x.value), node2(y.value,c), m2.value)
 278        case Two(_, c,d) => m1.add2(node3(a,b,x.value), node3(y.value,c,d), m2.value)
 279        case Three(_, c,d,e) => m1.add3(node3(a,b,x.value), node2(y.value,c), node2(d,e), m2.value)
 280        case Four(_, c,d,e,f) => m1.add3(node3(a,b,x.value), node3(y.value,c,d), node2(e,f), m2.value)
 281      }
 282      case Three(_, a,b,c) => d2 match {
 283        case One(_, d) => m1.add2(node3(a,b,c), node3(x.value,y.value,d), m2.value)
 284        case Two(_, d,e) => m1.add3(node3(a,b,c), node2(x.value,y.value), node2(d,e), m2.value)
 285        case Three(_, d,e,f) => m1.add3(node3(a,b,c), node3(x.value,y.value,d), node2(e,f), m2.value)
 286        case Four(_, d,e,f,g) => m1.add3(node3(a,b,c), node3(x.value,y.value,d), node3(e,f,g), m2.value)
 287      }
 288      case Four(_, a,b,c,d) => d2 match {
 289        case One(_, e) => m1.add3(node3(a,b,c), node2(d,x.value), node2(y.value,e), m2.value)
 290        case Two(_, e,f) => m1.add3(node3(a,b,c), node3(d,x.value,y.value), node2(e,f), m2.value)
 291        case Three(_, e,f,g) => m1.add3(node3(a,b,c), node3(d,x.value,y.value), node3(e,f,g), m2.value)
 292        case Four(_, e,f,g,h) => m1.add4(node3(a,b,c), node3(d,x.value,y.value), node2(e,f), node2(g,h), m2.value)
 293      }
 294    }
 295  }
 296
 297  def addDigits3(m1: NodeTree, d1: AFinger, xt: => A, yt: => A, zt: => A, d2: AFinger, m2t: => NodeTree): NodeTree = {
 298    val x = Need(xt)
 299    val y = Need(yt)
 300    val z = Need(zt)
 301    val m2 = Need(m2t)
 302    d1 match {
 303      case One(_, a) => d2 match {
 304        case One(_, b) => m1.add2(node3(a,x.value,y.value), node2(z.value,b), m2.value)
 305        case Two(_, b,c) => m1.add2(node3(a,x.value,y.value), node3(z.value,b,c), m2.value)
 306        case Three(_, b,c,d) => m1.add3(node3(a,x.value,y.value), node2(z.value,b), node2(c,d), m2.value)
 307        case Four(_, b,c,d,e) => m1.add3(node3(a,x.value,y.value), node3(z.value,b,c), node2(d,e), m2.value)
 308      }
 309      case Two(_, a,b) => d2 match {
 310        case One(_, c) => m1.add2(node3(a,b,x.value), node3(y.value,z.value,c), m2.value)
 311        case Two(_, c,d) => m1.add3(node3(a,b,x.value), node2(y.value,z.value), node2(c,d), m2.value)
 312        case Three(_, c,d,e) => m1.add3(node3(a,b,x.value), node3(y.value,z.value,c), node2(d,e), m2.value)
 313        case Four(_, c,d,e,f) => m1.add3(node3(a,b,x.value), node3(y.value,z.value,c), node3(d,e,f),m2.value)
 314      }
 315      case Three(_, a,b,c) => d2 match {
 316        case One(_, d) => m1.add3(node3(a,b,c), node2(x.value,y.value), node2(z.value,d), m2.value)
 317        case Two(_, d,e) => m1.add3(node3(a,b,c), node3(x.value,y.value,z.value), node2(d,e), m2.value)
 318        case Three(_, d,e,f) => m1.add3(node3(a,b,c), node3(x.value,y.value,z.value), node3(d,e,f), m2.value)
 319        case Four(_, d,e,f,g) => m1.add4(node3(a,b,c), node3(x.value,y.value,z.value), node2(d,e), node2(f,g), m2.value)
 320      }
 321      case Four(_, a,b,c,d) => d2 match {
 322        case One(_, e) => m1.add3(node3(a,b,c), node3(d,x.value,y.value), node2(z.value,e), m2.value)
 323        case Two(_, e,f) => m1.add3(node3(a,b,c), node3(d,x.value,y.value), node3(z.value,e,f), m2.value)
 324        case Three(_, e,f,g) => m1.add4(node3(a,b,c), node3(d,x.value,y.value), node2(z.value,e),node2(f,g), m2.value)
 325        case Four(_, e,f,g,h) => m1.add4(node3(a,b,c), node3(d,x.value,y.value), node3(z.value,e,f), node2(g,h), m2.value)
 326      }
 327    }
 328  }
 329
 330  def addDigits4(m1: NodeTree, d1: AFinger, xt: => A, yt: => A, zt: => A, wt: => A, d2: AFinger, m2t: => NodeTree): NodeTree = {
 331      val x = Need(xt)
 332      val y = Need(yt)
 333      val z = Need(zt)
 334      val w = Need(wt)
 335      val m2 = Need(m2t)
 336      d1 match {
 337      case One(_, a) => d2 match {
 338        case One(_, b) => m1.add2(node3(a,x.value,y.value), node3(z.value,w.value,b), m2.value)
 339        case Two(_, b,c) => m1.add3(node3(a,x.value,y.value), node2(z.value,w.value), node2(b,c), m2.value)
 340        case Three(_, b,c,d) => m1.add3(node3(a,x.value,y.value), node3(z.value,w.value,b), node2(c,d), m2.value)
 341        case Four(_, b,c,d,e) => m1.add3(node3(a,x.value,y.value), node3(z.value,w.value,b), node3(c,d,e), m2.value)
 342      }
 343      case Two(_, a,b) => d2 match {
 344        case One(_, c) => m1.add3(node3(a,b,x.value), node2(y.value,z.value), node2(w.value,c), m2.value)
 345        case Two(_, c,d) => m1.add3(node3(a,b,x.value), node3(y.value,z.value,w.value), node2(c,d), m2.value)
 346        case Three(_, c,d,e) => m1.add3(node3(a,b,x.value), node3(y.value,z.value,w.value), node3(c,d,e), m2.value)
 347        case Four(_, c,d,e,f) => m1.add4(node3(a,b,x.value), node3(y.value,z.value,w.value), node2(c,d), node2(e,f),m2.value)
 348      }
 349      case Three(_, a,b,c) => d2 match {
 350        case One(_, d) => m1.add3(node3(a,b,c), node3(x.value,y.value,z.value), node2(w.value,d), m2.value)
 351        case Two(_, d,e) => m1.add3(node3(a,b,c), node3(x.value,y.value,z.value), node3(w.value,d,e), m2.value)
 352        case Three(_, d,e,f) => m1.add4(node3(a,b,c), node3(x.value,y.value,z.value), node2(w.value,d),node2(e,f), m2.value)
 353        case Four(_, d,e,f,g) => m1.add4(node3(a,b,c), node3(x.value,y.value,z.value), node3(w.value,d,e), node2(f,g), m2.value)
 354      }
 355      case Four(_, a,b,c,d) => d2 match {
 356        case One(_, e) => m1.add3(node3(a,b,c), node3(d,x.value,y.value), node3(z.value,w.value,e), m2.value)
 357        case Two(_, e,f) => m1.add4(node3(a,b,c), node3(d,x.value,y.value), node2(z.value,w.value), node2(e,f), m2.value)
 358        case Three(_, e,f,g) => m1.add4(node3(a,b,c), node3(d,x.value,y.value), node3(z.value,w.value,e),node2(f,g), m2.value)
 359        case Four(_, e,f,g,h) => m1.add4(node3(a,b,c), node3(d,x.value,y.value), node3(z.value,w.value,e), node3(f,g,h), m2.value)
 360      }
 361    }
 362  }
 363
 364  /**
 365   * Splits this tree into a pair of subtrees at the point where the given predicate, based on the measure,
 366   * changes from `false` to `true`. O(log(min(i,n-i)))
 367   *
 368   * @param pred predicate on node measures. Must be a semigroup homomorphism from the semigroup `V` of
 369   *             node measures to the semigroup of `Boolean`s with `||` as the semigroup operation.
 370   *             Namely, it must hold that `pred(v1 |+| v2) = pred(v1) || pred(v2)`.
 371   * @return `(as, bs)`, where
 372   *          - `as`: the subtree containing elements before the point where `pred` first holds
 373   *          - `bs`: the subtree containing elements at and after the point where `pred` first holds. Empty if `pred` never holds.
 374   */
 375  def split(pred: V => Boolean): (FingerTree[V, A], FingerTree[V, A]) =
 376    measure match {
 377      case Just(v) if pred(v) =>
 378        val (l, x, r) = split1(pred)
 379        (l, x +: r)
 380      case _ =>
 381        (this, empty)
 382    }
 383
 384  /**
 385   * Like `split`, but returns the element where `pred` first holds separately
 386   *
 387   * @throws if the tree is empty.
 388   */
 389  def split1(pred: V => Boolean): (FingerTree[V, A], A, FingerTree[V, A]) = split1(pred, Maybe.empty)
 390
 391  private def split1(pred: V => Boolean, accV: Maybe[V]): (FingerTree[V, A], A, FingerTree[V, A]) = fold(
 392    sys.error("Splitting an empty FingerTree"), // we can never get here
 393    (v, x) => (empty, x, empty),
 394    (v, pr, m, sf) => {
 395      val accVpr = accV.map(measurer.append(_, pr.measure)).getOrElse(pr.measure)
 396      if (pred(accVpr)) {
 397        val (l, x, r) = pr.split1(pred, accV)
 398        (cata(l)(_.toTree, empty), x, deepL(r, m, sf))
 399      } else {
 400        val accVm = mappendVal(accVpr, m)
 401        if (pred(accVm)) {
 402          val (ml, xs, mr) = m.split1(pred, Just(accVpr))
 403          val (l, x, r) = xs.split1(pred, mappendVal(accVpr, ml))
 404          (deepR(pr, ml, l), x, deepL(r, mr, sf))
 405        } else {
 406          val (l, x, r) = sf.split1(pred, Just(accVm))
 407          (deepR(pr, m, l), x, cata(r)(_.toTree, empty))
 408        }
 409      }
 410    }
 411  )
 412
 413  def isEmpty: Boolean = fold(true, (v, x) => false, (v, pr, m, sf) => false)
 414
 415  def viewl: ViewL[FingerTree[V, *], A] =
 416    fold(
 417      EmptyL[FingerTree[V, *], A],
 418      (v, x) => OnL[FingerTree[V, *], A](x, empty[V, A]),
 419      (v, pr, m, sf) =>
 420        pr match {
 421          case One(v, x) => OnL[FingerTree[V, *], A](x, rotL(m, sf))
 422          case _ => OnL[FingerTree[V, *], A](pr.lhead, deep(pr.ltail, m, sf))
 423        })
 424
 425  def viewr: ViewR[FingerTree[V, *], A] =
 426    fold(
 427      EmptyR[FingerTree[V, *], A],
 428      (v, x) => OnR[FingerTree[V, *], A](empty[V, A], x),
 429      (v, pr, m, sf) =>
 430        sf match {
 431          case One(v, x) => OnR[FingerTree[V, *], A](rotR(pr, m), x)
 432          case _ => OnR[FingerTree[V, *], A](deep(pr, m, sf.rtail), sf.rhead)
 433        })
 434
 435  /**
 436   * Selects the first element in the tree.
 437   *
 438   * @throws if the tree is empty
 439   */
 440  def head: A = viewl.head
 441
 442  /**
 443   * Selects the last element in the tree.
 444   *
 445   * @throws if the tree is empty
 446   */
 447  def last: A = viewr.last
 448
 449  /**
 450   * Selects a subtree containing all elements except the first
 451   *
 452   * @throws if the tree is empty
 453   */
 454  def tail: FingerTree[V, A] = viewl.tail
 455
 456  /**
 457   * Selects a subtree containing all elements except the last
 458   *
 459   * @throws if the tree is empty
 460   */
 461  def init: FingerTree[V, A] = viewr.init
 462
 463  /** Maps the given function across the tree, annotating nodes in the resulting tree according to the provided `Reducer`. */
 464  def map[B, V2](f: A => B)(implicit r: Reducer[B, V2]): FingerTree[V2, B] = {
 465    import r.semigroup
 466    implicit val nm: Reducer[FingerTree.Node[V2, B], V2] = nodeMeasure[B, V2]
 467    fold(
 468      empty[V2, B],
 469      (v, x) => single(f(x)),
 470      (v, pr, mt, sf) => deep(pr map f, mt.map(x => x.map(f)), sf map f))
 471  }
 472
 473  /**
 474   * Like traverse, but with a more constraint type: we need the additional measure to construct the new tree.
 475   */
 476  def traverseTree[F[_], V2, B](f: A => F[B])(implicit ms: Reducer[B, V2], F: Applicative[F]): F[FingerTree[V2, B]]
 477  = {
 478    import ms.semigroup
 479    def mkDeep(pr: Finger[V2, B])(m: FingerTree[V2, Node[V2, B]])(sf: Finger[V2, B]): FingerTree[V2, B] = deep(pr, m, sf)
 480    fold(F.pure(FingerTree.empty[V2, B]),
 481         (v, a) => F.map(f(a))(a => single(ms.unit(a), a)),
 482         (v, pr, m, sf) => {
 483           //F.ap(traverseFinger(sf)(f))(F.ap(m.traverseTree(n => traverseNode(n)(f)))(F.map(traverseFinger(pr)(f))(pr => mkDeep(pr)_)))
 484           //the implementation below seems most efficient. The straightforward implementation using F.map3 leads to an explosion of traverseTree calls
 485           val fmap2 = F.apply2(traverseFinger(pr)(f), m.traverseTree(n => traverseNode(n)(f)))((a,b) => mkDeep(a)(b)_)
 486           F.ap(traverseFinger(sf)(f))(fmap2)
 487        })
 488  }
 489
 490  private def traverseNode[F[_], V2, B](node: Node[V, A])(f: A => F[B])(implicit ms: Reducer[B, V2], F: Applicative[F]): F[Node[V2, B]] = {
 491    def mkNode(x: B)(y: B)(z: B): Node[V2, B] = node3(x, y, z)
 492    node.fold((v, a, b) => F.apply2(f(a), f(b))((x, y) => node2(x, y)),
 493        (v, a, b, c) =>  {
 494          F.ap(f(c))(F.ap(f(b))(F.map(f(a))(x => mkNode(x)_)))
 495        }
 496    )
 497  }
 498
 499  private def traverseFinger[F[_], A, B, V2](digit: Finger[V, A])(f: A => F[B])(implicit ms: Reducer[B, V2], F: Applicative[F]): F[Finger[V2, B]] = {
 500    def mkTwo(x: B)(y: B): Finger[V2, B] = two(x, y)
 501    def mkThree(x: B)(y: B)(z: B): Finger[V2, B] = three(x, y, z)
 502    def mkFour(w: B)(x: B)(y: B)(z: B): Finger[V2, B] = four(w, x, y, z)
 503    digit match {
 504      case One(v, a) => F.map(f(a))(x => one(x))
 505      case Two(v, a, b) => F.ap(f(b))(F.map(f(a))(x => mkTwo(x)_))
 506      case Three(v, a, b, c) => F.ap(f(c))(F.ap(f(b))(F.map(f(a))(x => mkThree(x)_)))
 507      case Four(v, a, b, c, d) => F.ap(f(d))(F.ap(f(c))(F.ap(f(b))(F.map(f(a))(x => mkFour(x)_))))
 508    }
 509  }
 510
 511  /** Execute the provided side effect for each element in the tree. */
 512  def foreach(f: A => Unit): Unit = {
 513    fold(
 514      {},
 515      (_, x) => { f(x) },
 516      (_, pr, m, sf) => { pr.foreach(f); m.foreach(_.foreach(f)); sf.foreach(f) }
 517    )}
 518
 519  /** An iterator that visits each element in the tree. */
 520  def iterator: Iterator[A] = fold(
 521    Iterator.empty,
 522    (_, x) => Iterator.single(x),
 523    (_, pr, m, sf) => pr.iterator ++ m.iterator.flatMap(_.iterator) ++ sf.iterator)
 524
 525  /** An iterator that visits each element in the tree in reverse order. */
 526  def reverseIterator: Iterator[A] = fold(
 527    Iterator.empty,
 528    (_, x) => Iterator.single(x),
 529    (_, pr, m, sf) => sf.reverseIterator ++ m.reverseIterator.flatMap(_.reverseIterator) ++ pr.reverseIterator)
 530
 531  /** Convert the leaves of the tree to a `scala.Stream` */
 532  def toStream: Stream[A] = to[Stream]
 533
 534  /** Convert the leaves of the tree to a `scala.List` */
 535  def toList: List[A] = to[List]
 536
 537  /** Convert the leaves of the tree to a `scalaz.IList` */
 538  def toIList: IList[A] = to[IList]
 539
 540  /** Convert the leaves of the tree to an `M` */
 541  def reduceTo[M: Reducer[A, *]: Monoid]: M = map[A, M](x => x).measure.getOrElse(Monoid[M].zero)
 542
 543  /** Convert the leaves of the tree to an `F[A]` */
 544  def to[F[_]](implicit R: Reducer[A, F[A]], M: Monoid[F[A]]): F[A] = reduceTo[F[A]]
 545
 546  /** Convert the tree to a `String`. Unsafe: this uses `Any#toString` for types `V` and `A` */
 547  override def toString = {
 548    val showV = Show.showFromToString[V]
 549    val showA = Show.showFromToString[A]
 550    fingerTreeShow(showV, showA).shows(this)
 551  }
 552}
 553
 554sealed abstract class FingerTreeInstances {
 555  import FingerTree._
 556
 557  implicit def viewLFunctor[S[_]](implicit s: Functor[S]): Functor[ViewL[S, *]] =
 558    new Functor[ViewL[S, *]] {
 559      def map[A, B](t: ViewL[S, A])(f: A => B): ViewL[S, B] =
 560        t.fold(EmptyL[S, B], (x, xs) => OnL(f(x), s.map(xs)(f))) //TODO define syntax for &: and :&
 561    }
 562
 563  implicit def viewRFunctor[S[_]](implicit s: Functor[S]): Functor[ViewR[S, *]] =
 564    new Functor[ViewR[S, *]] {
 565      def map[A, B](t: ViewR[S, A])(f: A => B): ViewR[S, B] =
 566        t.fold(EmptyR[S, B], (xs, x) => OnR(s.map(xs)(f), f(x)))
 567    }
 568
 569  implicit def fingerFoldable[V]: Foldable[Finger[V, *]] =
 570    new Foldable[Finger[V, *]] with Foldable.FromFoldMap[Finger[V, *]] {
 571      override def foldMap[A, M: Monoid](v: Finger[V, A])(f: A => M) = v.foldMap(f)
 572    }
 573
 574  implicit def fingerMeasure[A, V: Semigroup]: Reducer[Finger[V, A], V] =
 575    UnitReducer((a: Finger[V, A]) => a.measure)
 576
 577  implicit def nodeMeasure[A, V: Semigroup]: Reducer[Node[V, A], V] =
 578    UnitReducer((a: Node[V, A]) => a fold (
 579            (v, _, _) => v,
 580            (v, _, _, _) => v))
 581
 582  implicit def nodeFoldable[V]: Foldable[Node[V, *]] =
 583    new Foldable[Node[V, *]] {
 584      def foldMap[A, M: Monoid](t: Node[V, A])(f: A => M): M = t foldMap f
 585      def foldRight[A, B](v: Node[V, A], z: => B)(f: (A, => B) => B): B =
 586         foldMap(v)((a: A) => Endo.endoByName[B](f(a, _))) apply z
 587    }
 588
 589  implicit def fingerTreeFoldable[V]: Foldable[FingerTree[V, *]] =
 590    new Foldable[FingerTree[V, *]] {
 591      override def foldLeft[A, B](t: FingerTree[V, A], b: B)(f: (B, A) => B) = t.foldLeft(b)(f)
 592
 593      def foldMap[A, M: Monoid](t: FingerTree[V, A])(f: A => M): M = t foldMap(f)
 594
 595      override def foldRight[A, B](t: FingerTree[V, A], z: => B)(f: (A, => B) => B) = t.foldRight(z)(f)
 596    }
 597
 598  implicit def fingerTreeMonoid[V: Reducer[A, *], A]: Monoid[FingerTree[V, A]] =
 599    new Monoid[FingerTree[V, A]] {
 600      def append(f1: FingerTree[V, A], f2: => FingerTree[V, A]) = f1 <++> f2
 601      def zero = empty
 602    }
 603
 604  implicit def fingerTreeShow[V, A](implicit V: Show[V], A: Show[A]): Show[FingerTree[V,A]] =
 605    new Show[FingerTree[V,A]] {
 606      import std.iterable._
 607      val AS = Show[List[A]]
 608      import syntax.show._
 609      override def show(t: FingerTree[V,A]) = t.fold(
 610        empty = cord"[]",
 611        single = (v, x) => cord"$v [$x]",
 612        deep = (v, pf, m, sf) => cord"$v [${AS.show(pf.toList)}, *, ${AS.show(sf.toList)}]"
 613      )
 614    }
 615
 616  implicit def fingerTreeEqual[V, A : Equal]: Equal[FingerTree[V, A]] =
 617    new Equal[FingerTree[V, A]] {
 618      import std.stream._
 619      def equal(x: FingerTree[V, A], y: FingerTree[V, A]) =
 620        Equal[Stream[A]].equal(x.toStream, y.toStream)
 621    }
 622}
 623
 624object FingerTree extends FingerTreeInstances {
 625
 626  def Node2[V: Reducer[A, *], A](v: V, a1: => A, a2: => A): Node[V, A] =
 627    new Node[V, A] {
 628      def fold[B](two: (V, => A, => A) => B, three: (V, => A, => A, => A) => B) =
 629        two(v, a1, a2)
 630      val measure = v
 631    }
 632
 633  def Node3[V: Reducer[A, *], A](v: V, a1: => A, a2: => A, a3: => A): Node[V, A] =
 634    new Node[V, A] {
 635      def fold[B](two: (V, => A, => A) => B, three: (V, => A, => A, => A) => B) =
 636        three(v, a1, a2, a3)
 637      val measure = v
 638    }
 639
 640  def EmptyR[S[_], A]: ViewR[S, A] =
 641    new ViewR[S, A] {
 642      def fold[B](b: => B, f: (=> S[A], => A) => B) = b
 643    }
 644
 645  def OnR[S[_], A](sa: => S[A], a: => A): ViewR[S, A] =
 646    new ViewR[S, A] {
 647      def fold[B](b: => B, f: (=> S[A], => A) => B) = f(sa, a)
 648    }
 649
 650  def EmptyL[S[_], A]: ViewL[S, A] =
 651    new ViewL[S, A] {
 652      def fold[B](b: => B, f: (=> A, => S[A]) => B) = b
 653    }
 654
 655  def OnL[S[_], A](a: => A, sa: => S[A]): ViewL[S, A] =
 656    new ViewL[S, A] {
 657      def fold[B](b: => B, f: (=> A, => S[A]) => B) = f(a, sa)
 658    }
 659
 660  def one[V, A](a: A)(implicit measure: Reducer[A, V]): Finger[V, A] =
 661    One(measure.unit(a), a)
 662
 663  def two[V, A](a1: A, a2: A)(implicit measure: Reducer[A, V]): Finger[V, A] =
 664    Two(measure.snoc(measure.unit(a1), a2), a1, a2)
 665
 666  def three[V, A](a1: A, a2: A, a3: A)(implicit measure: Reducer[A, V]): Finger[V, A] =
 667    Three(measure.snoc(measure.snoc(measure.unit(a1), a2), a3), a1, a2, a3)
 668
 669  def four[V, A](a1: A, a2: A, a3: A, a4: A)(implicit measure: Reducer[A, V]): Finger[V, A] =
 670    Four(measure.snoc(measure.snoc(measure.snoc(measure.unit(a1), a2), a3), a4), a1, a2, a3, a4)
 671
 672  def node2[V, A](a: A, b: A)(implicit measure: Reducer[A, V]): Node[V, A] =
 673    Node2[V, A](measure.snoc(measure.unit(a), b), a, b)
 674
 675  def node3[V, A](a: A, b: A, c: A)(implicit measure: Reducer[A, V]): Node[V, A] =
 676    Node3[V, A](measure.snoc(measure.snoc(measure.unit(a), b), c), a, b, c)
 677
 678  def mappendVal[V: Semigroup, A](v: V, t: FingerTree[V, A]): V =
 679    t.fold(v, (vt, _) => v |+| vt, (vt, _, _, _) => v |+| vt)
 680
 681  def empty[V, A](implicit ms: Reducer[A, V]): FingerTree[V, A] =
 682    new FingerTree[V, A] {
 683      def fold[B](b: => B, s: (V, A) => B, d: (V, Finger[V, A], => FingerTree[V, Node[V, A]], Finger[V, A]) => B): B = b
 684    }
 685
 686  def single[V, A](a: A)(implicit ms: Reducer[A, V]): FingerTree[V, A] = single(ms.unit(a), a)
 687
 688  def single[V: Reducer[A, *], A](v: V, a: => A): FingerTree[V, A] =
 689    new FingerTree[V, A] {
 690      def fold[B](b: => B, s: (V, A) => B, d: (V, Finger[V, A], => FingerTree[V, Node[V, A]], Finger[V, A]) => B): B = s(v, a)
 691    }
 692
 693  def deep[V, A](pr: Finger[V, A], m: => FingerTree[V, Node[V, A]], sf: Finger[V, A])(implicit r: Reducer[A, V]): FingerTree[V, A] = {
 694    import r.semigroup
 695    val measure = fingerMeasure[A, V]
 696    deep(measure.snoc(mappendVal(measure.unit(pr), m), sf), pr, m, sf)
 697  }
 698
 699  def deep[V: Reducer[A, *], A](v: V, pr: Finger[V, A], m: => FingerTree[V, Node[V, A]], sf: Finger[V, A]): FingerTree[V, A] =
 700    new FingerTree[V, A] {
 701      private[this] val mz = Need(m)
 702      def fold[B](b: => B, f: (V, A) => B, d: (V, Finger[V, A], => FingerTree[V, Node[V, A]], Finger[V, A]) => B): B =
 703        d(v, pr, mz.value, sf)
 704    }
 705
 706  def deepL[V: Reducer[A, *], A](mpr: Option[Finger[V, A]], m: => FingerTree[V, Node[V, A]], sf: Finger[V, A]): FingerTree[V, A] =
 707    mpr match {
 708      case None => rotL(m, sf)
 709      case Some(pr) => deep(pr, m, sf)
 710    }
 711
 712  def deepR[V: Reducer[A, *], A](pr: Finger[V, A], m: => FingerTree[V, Node[V, A]], msf: Option[Finger[V, A]]): FingerTree[V, A] =
 713    msf match {
 714      case None => rotR(pr, m)
 715      case Some(sf) => deep(pr, m, sf)
 716    }
 717
 718  def rotL[V, A](m: FingerTree[V, Node[V, A]], sf: Finger[V, A])(implicit r: Reducer[A, V]): FingerTree[V, A] = {
 719    import r.semigroup
 720    m.viewl.fold(
 721      sf.toTree,
 722      (a, mm) => deep(m.measure.cata(_ |+| sf.measure, sf.measure), a.toDigit, mm, sf))
 723  }
 724
 725  def rotR[V, A](pr: Finger[V, A], m: FingerTree[V, Node[V, A]])(implicit r: Reducer[A, V]): FingerTree[V, A] = {
 726    import r.semigroup
 727    m.viewr.fold(
 728      pr.toTree,
 729      (mm, a) => deep(mappendVal(pr.measure, m), pr, mm, a.toDigit))
 730  }
 731
 732  /**View of the left end of a sequence.*/
 733  sealed abstract class ViewL[S[_], A] {
 734    def fold[B](b: => B, f: (=> A, => S[A]) => B): B
 735    def headOption: Option[A] = fold(None, (a, sa) => Some(a))
 736    def tailOption: Option[S[A]] = fold(None, (a, sa) => Some(sa))
 737    def head: A = headOption.getOrElse(sys.error("Head on empty view"))
 738    def tail: S[A] = tailOption.getOrElse(sys.error("Tail on empty view"))
 739  }
 740
 741  /**View of the right end of a sequence.*/
 742  sealed abstract class ViewR[S[_], A] {
 743    def fold[B](b: => B, f: (=> S[A], => A) => B): B
 744    def lastOption: Option[A] = fold(None, (sa, a) => Some(a))
 745    def initOption: Option[S[A]] = fold(None, (sa, a) => Some(sa))
 746    def last: A = lastOption.getOrElse(sys.error("Last on empty view"))
 747    def init: S[A] = initOption.getOrElse(sys.error("Init on empty view"))
 748  }
 749
 750  sealed abstract class Finger[V, A] {
 751    def foldMap[B](f: A => B)(implicit m: Semigroup[B]): B
 752
 753    /**
 754      * Append the given element to the right
 755      *
 756      * @throws if the finger is `Four`.
 757      */
 758    def +:(a: A): Finger[V, A]
 759
 760    /**
 761      * Prepends the given element to the left
 762      *
 763      * @throws if the finger is `Four`.
 764      */
 765    def :+(a: A): Finger[V, A]
 766
 767    /** Replaces the first element of this finger with `a` */
 768    def |-:(a: A): Finger[V, A]
 769
 770    /** Replaces the last element of this finger with `a` */
 771    def :-|(a: A): Finger[V, A]
 772
 773    def lhead: A
 774
 775    def ltail: Finger[V, A]
 776
 777    def rhead: A
 778
 779    def rtail: Finger[V, A]
 780
 781    def toTree: FingerTree[V, A]
 782
 783    def map[B, V2: Reducer[B, *]](f: A => B): Finger[V2, B]
 784
 785    /** Apply the given side effect to each element. */
 786    def foreach(f: A => Unit): Unit
 787
 788    /** An iterator that visits each element. */
 789    def iterator: Iterator[A]
 790
 791    /** An iterator that visits each element in reverse order. */
 792    def reverseIterator: Iterator[A]
 793
 794    def measure: V
 795
 796    def toList: List[A] = map[A, List[A]](x => x).measure
 797
 798    private[scalaz] def split1(pred: V => Boolean, accV: Maybe[V]): (Option[Finger[V, A]], A, Option[Finger[V, A]])
 799  }
 800  case class One[V, A](v: V, a1: A)(implicit r: Reducer[A, V]) extends Finger[V, A] {
 801
 802    def foldMap[B](f: A => B)(implicit m: Semigroup[B]) = f(a1)
 803
 804    def +:(a: A) = Two(r.cons(a, v), a, a1)
 805
 806    def :+(a: A) = Two(r.snoc(v, a), a1, a)
 807
 808    def |-:(a: A) = one(a)
 809
 810    def :-|(a: A) = one(a)
 811
 812    def lhead = a1
 813
 814    def ltail = sys.error("Tail on the digit One")
 815
 816    def rhead = a1
 817
 818    def rtail = sys.error("Tail on the digit One")
 819
 820    def toTree = single(a1)
 821
 822    def map[B, V2: Reducer[B, *]](f: A => B) = one(f(a1))
 823
 824    def foreach(f: A => Unit): Unit = {
 825      f(a1)
 826    }
 827
 828    def iterator = Iterator.single(a1)
 829
 830    def reverseIterator = Iterator.single(a1)
 831
 832    val measure = v
 833
 834    private[scalaz] def split1(pred: V => Boolean, accV: Maybe[V]) = (None, a1, None)
 835  }
 836
 837
 838  case class Two[V, A](v: V, a1: A, a2: A)(implicit r: Reducer[A, V]) extends Finger[V, A] {
 839    import r.semigroup
 840
 841    def foldMap[B](f: A => B)(implicit m: Semigroup[B]) = m.append(f(a1), f(a2))
 842
 843    def +:(a: A) = Three(r.cons(a, v), a, a1, a2)
 844
 845    def :+(a: A) = Three(r.snoc(v, a), a1, a2, a)
 846
 847    def |-:(a: A) = two(a, a2)
 848
 849    def :-|(a: A) = two(a1, a)
 850
 851    def lhead = a1
 852
 853    def ltail = one(a2)
 854
 855    def rhead = a2
 856
 857    def rtail = one(a1)
 858
 859    def toTree = {
 860      deep(v, one(a1), empty[V, Node[V, A]], one(a2))
 861    }
 862
 863    def map[B, V2: Reducer[B, *]](f: A => B) = two(f(a1), f(a2))
 864
 865    def foreach(f: A => Unit): Unit = {
 866      f(a1)
 867      f(a2)
 868    }
 869
 870    def iterator = Iterator(a1, a2)
 871
 872    def reverseIterator = Iterator(a2, a1)
 873
 874    val measure = v
 875
 876    private[scalaz] def split1(pred: V => Boolean, accV: Maybe[V]) = {
 877      val va1 = r.unit(a1)
 878      val accVa1 = accV.cata(_ |+| va1, va1)
 879      if (pred(accVa1))
 880        (None, a1, Some(one(a2)))
 881      else
 882        (Some(One(va1, a1)), a2, None)
 883    }
 884  }
 885  case class Three[V, A](v: V, a1: A, a2: A, a3: A)(implicit r: Reducer[A, V]) extends Finger[V, A] {
 886    import r.semigroup
 887
 888    def foldMap[B](f: A => B)(implicit m: Semigroup[B]) = m.append(m.append(f(a1), f(a2)), f(a3))
 889
 890    def +:(a: A) = Four(r.cons(a, v), a, a1, a2, a3)
 891
 892    def :+(a: A) = Four(r.snoc(v, a), a1, a2, a3, a)
 893
 894    def |-:(a: A) = three(a, a2, a3)
 895
 896    def :-|(a: A) = three(a1, a2, a)
 897
 898    def lhead = a1
 899
 900    def ltail = two(a2, a3)
 901
 902    def rhead = a3
 903
 904    def rtail = two(a1, a2)
 905
 906    def toTree = {
 907      deep(v, two(a1, a2), empty[V, Node[V, A]], one(a3))
 908    }
 909
 910    def map[B, V2: Reducer[B, *]](f: A => B) = three(f(a1), f(a2), f(a3))
 911
 912    def foreach(f: A => Unit): Unit = {
 913      f(a1)
 914      f(a2)
 915      f(a3)
 916    }
 917
 918    def iterator = Iterator(a1, a2, a3)
 919
 920    def reverseIterator = Iterator(a3, a2, a1)
 921
 922    val measure = v
 923
 924    private[scalaz] def split1(pred: V => Boolean, accV: Maybe[V]) = {
 925      val va1 = r.unit(a1)
 926      val accVa1 = accV.cata(_ |+| va1, va1)
 927      if (pred(accVa1))
 928        (None, a1, Some(two(a2, a3)))
 929      else {
 930        val accVa2 = r.snoc(accVa1, a2)
 931        if (pred(accVa2))
 932          (Some(One(va1, a1)), a2, Some(one(a3)))
 933        else
 934          (Some(two(a1, a2)), a3, None)
 935      }
 936    }
 937  }
 938  case class Four[V, A](v: V, a1: A, a2: A, a3: A, a4: A)(implicit r: Reducer[A, V]) extends Finger[V, A] {
 939    import r.semigroup
 940
 941    def foldMap[B](f: A => B)(implicit m: Semigroup[B]) = m.append(m.append(f(a1), f(a2)), m.append(f(a3), f(a4)))
 942
 943    def +:(a: A) = sys.error("Digit overflow")
 944
 945    def :+(a: A) = sys.error("Digit overflow")
 946
 947    def |-:(a: A) = four(a, a2, a3, a4)
 948
 949    def :-|(a: A) = four(a1, a2, a3, a)
 950
 951    def lhead = a1
 952
 953    def ltail = three(a2, a3, a4)
 954
 955    def rhead = a4
 956
 957    def rtail = three(a1, a2, a3)
 958
 959    def toTree = {
 960      deep(v, two(a1, a2), empty[V, Node[V, A]], two(a3, a4))
 961    }
 962
 963    def map[B, V2: Reducer[B, *]](f: A => B) = four(f(a1), f(a2), f(a3), f(a4))
 964
 965    def foreach(f: A => Unit): Unit = {
 966      f(a1)
 967      f(a2)
 968      f(a3)
 969      f(a4)
 970    }
 971
 972    def iterator = Iterator(a1, a2, a3, a4)
 973
 974    def reverseIterator = Iterator(a4, a3, a2, a1)
 975
 976    val measure = v
 977
 978    private[scalaz] def split1(pred: V => Boolean, accV: Maybe[V]) = {
 979      val va1 = r.unit(a1)
 980      val accVa1 = accV.cata(_ |+| va1, va1)
 981      if (pred(accVa1))
 982        (None, a1, Some(three(a2, a3, a4)))
 983      else {
 984        val accVa2 = r.snoc(accVa1, a2)
 985        if (pred(accVa2))
 986          (Some(One(va1, a1)), a2, Some(two(a3, a4)))
 987        else {
 988          val accVa3 = r.snoc(accVa2, a3)
 989          if (pred(accVa3))
 990            (Some(two(a1, a2)), a3, Some(one(a4)))
 991          else
 992            (Some(three(a1, a2, a3)), a4, None)
 993        }
 994      }
 995    }
 996  }
 997
 998  sealed abstract class Node[V, A](implicit r: Reducer[A, V]) {
 999    def fold[B](two: (V, => A, => A) => B, three: (V, => A, => A, => A) => B): B
1000
1001    def foldMap[B](f: A => B)(implicit m: Semigroup[B]): B = fold(
1002      (v, a1, a2) => m.append(f(a1), f(a2)),
1003      (v, a1, a2, a3) => m.append(m.append(f(a1), f(a2)), f(a3)))
1004
1005    def toDigit: Finger[V, A] = fold(
1006      (v, a1, a2) => Two(v, a1, a2),
1007      (v, a1, a2, a3) => Three(v, a1, a2, a3))
1008
1009    val measure: V
1010
1011    def map[B, V2: Reducer[B, *]](f: A => B): Node[V2, B] = fold(
1012      (v, a1, a2) => node2(f(a1), f(a2)),
1013      (v, a1, a2, a3) => node3(f(a1), f(a2), f(a3)))
1014
1015    def foreach(f: A => Unit): Unit = {
1016      fold(
1017        (_, a1, a2) => { f(a1); f(a2) },
1018        (_, a1, a2, a3) => { f(a1); f(a2); f(a3) }
1019      )}
1020
1021    def iterator: Iterator[A] = fold(
1022      (_, a1, a2) => Iterator(a1, a2),
1023      (_, a1, a2, a3) => Iterator(a1, a2, a3))
1024
1025    def reverseIterator: Iterator[A] = fold(
1026      (_, a1, a2) => Iterator(a2, a1),
1027      (_, a1, a2, a3) => Iterator(a3, a2, a1))
1028
1029    private[scalaz] def split1(pred: V => Boolean, accV: V): (Option[Finger[V, A]], A, Option[Finger[V, A]]) = fold(
1030      (v, a1, a2) => {
1031        val va1 = r.unit(a1)
1032        val accVa1 = r.append(accV, va1)
1033        if (pred(accVa1))
1034          (None, a1, Some(one(a2)))
1035        else
1036          (Some(One(va1, a1)), a2, None)
1037      },
1038      (v, a1, a2, a3) => {
1039        val va1 = r.unit(a1)
1040        val accVa1 = r.append(accV, va1)
1041        if (pred(accVa1))
1042          (None, a1, Some(two(a2, a3)))
1043        else {
1044          val accVa2 = r.snoc(accVa1, a2)
1045          if (pred(accVa2))
1046            (Some(One(va1, a1)), a2, Some(one(a3)))
1047          else
1048            (Some(two(a1, a2)), a3, None)
1049        }
1050      })
1051  }
1052
1053}
1054
1055/** Indexed sequences, based on [[scalaz.FingerTree]]
1056 *
1057 * The measure is the count of the preceding elements, provided by `UnitReducer((e: Int) => 1)`.
1058 */
1059final class IndSeq[A](val self: FingerTree[Int, A]) {
1060
1061  import IndSeq.indSeq
1062  import std.anyVal._
1063
1064  private implicit def sizer[A]: Reducer[A, Int] = UnitReducer((_: A) => 1)
1065  def apply(i: Int): A =
1066    self.split(_ > i)._2.viewl.headOption.getOrElse(sys.error("Index " + i + " > " + self.measure))
1067  def replace(i: Int, a: => A): IndSeq[A] = {
1068    val (l, r) = self.split(_ > i)
1069    indSeq(l <++> (a |-: r))
1070  }
1071  def split(i: Int): (IndSeq[A], IndSeq[A]) = {
1072    val (l, r) = self.split(_ > i)
1073    (indSeq(l), indSeq(r))
1074  }
1075  def ++(xs: IndSeq[A]): IndSeq[A] = indSeq(self <++> xs.self)
1076  def :+(x: => A): IndSeq[A] = indSeq(self :+ x)
1077  def +:(x: A): IndSeq[A] = indSeq(x +: self)
1078  def length: Int = self.measure.getOrElse(0)
1079  def tail: IndSeq[A] = indSeq(self.tail)
1080  def init: IndSeq[A] = indSeq(self.init)
1081  def drop(n: Int): IndSeq[A] = split(n)._2
1082  def take(n: Int): IndSeq[A] = split(n)._1
1083  def map[B](f: A => B): IndSeq[B] = indSeq(self map f)
1084
1085  import FingerTree.fingerTreeFoldable
1086
1087  def flatMap[B](f: A => IndSeq[B]): IndSeq[B] = indSeq(fingerTreeFoldable.foldLeft(self, empty[Int, B])((ys, x) => ys <++> f(x).self))
1088}
1089
1090object IndSeq extends IndSeqInstances {
1091  private def indSeq[A](v: FingerTree[Int, A]): IndSeq[A] = new IndSeq(v)
1092
1093  import std.anyVal._
1094
1095  def apply[A](as: A*): IndSeq[A] = fromSeq(as)
1096  def fromSeq[A](as: Seq[A]): IndSeq[A] = indSeq(as.foldLeft(empty[Int, A](UnitReducer(a => 1)))((x, y) => x :+ y))
1097}
1098
1099sealed abstract class IndSeqInstances {
1100
1101  implicit def indSeqEqual[A: Equal]: Equal[IndSeq[A]] =
1102    Equal.equalBy(_.self)
1103
1104  implicit val indSeqInstance: MonadPlus[IndSeq] with Alt[IndSeq] with Traverse[IndSeq] with IsEmpty[IndSeq] =
1105    new MonadPlus[IndSeq] with Alt[IndSeq] with Traverse[IndSeq] with IsEmpty[IndSeq] with IsomorphismFoldable[IndSeq, FingerTree[Int, *]]{
1106      def G = implicitly
1107      override val naturalTrans = λ[IndSeq ~> FingerTree[Int, *]](_.self)
1108      def traverseImpl[G[_], A, B](fa: IndSeq[A])(f: A => G[B])(implicit G: Applicative[G]) = {
1109        import std.anyVal._
1110        implicit val r: Reducer[B, Int] = UnitReducer((_: B) => 1)
1111        G.map(fa.self.traverseTree(f))(new IndSeq(_))
1112      }
1113      override def length[A](fa: IndSeq[A]) =
1114        fa.length
1115      override def index[A](fa: IndSeq[A], i: Int) =
1116        if(0 <= i && i < fa.length) Some(fa(i)) else None
1117      override def isEmpty[A](fa: IndSeq[A]) =
1118        fa.self.isEmpty
1119      override def empty[A](fa: IndSeq[A]) =
1120        fa.self.isEmpty
1121      def point[A](a: => A) =
1122        IndSeq(a)
1123      def bind[A, B](fa: IndSeq[A])(f: A => IndSeq[B]) =
1124        fa flatMap f
1125      override def map[A, B](fa: IndSeq[A])(f: A => B) =
1126        fa map f
1127      def plus[A](a: IndSeq[A], b: => IndSeq[A]) =
1128        a ++ b
1129      def alt[A](a: => IndSeq[A], b: => IndSeq[A]) =
1130        plus(a, b)
1131      def empty[A] =
1132        IndSeq.apply()
1133    }
1134}
1135
1136/** Ordered sequences, based on [[scalaz.FingerTree]]
1137 *
1138 *  `a` has a higher priority than `b` if `Order[A].greaterThan(a, b)`.
1139 *
1140 * `insert` and `++` maintains the ordering.
1141 *
1142 * The measure is calculated with a `Semigroup[A @@ LastVal]`, whose `append`
1143 * operation favours the first argument. Accordingly, the measure of a node is the
1144 * item with the highest priority contained recursively below that node.
1145 */
1146sealed abstract class OrdSeq[A] extends Ops[FingerTree[A @@ LastVal, A]] {
1147  import std.function._
1148
1149  implicit val ord: Order[A]
1150
1151  /**
1152   * @return (higher, lowerOrEqual) The sub-sequences that contain elements of higher and of lower-than-or-equal
1153   *                                priority than `a`, and of lower or equal priority respectively.
1154   */
1155  def partition(a: A): (OrdSeq[A], OrdSeq[A]) =
1156    function1Instance.product(OrdSeq.ordSeq[A](_: FingerTree[A @@ LastVal, A]))(self.split(a1 =>
1157      ord.greaterThanOrEqual(Tag.unwrap(a1), a)))
1158
1159  /** Insert `a` at a the first point that all elements to the left are of higher priority */
1160  def insert(a: A): OrdSeq[A] = partition(a) match {
1161    case (l, r) => OrdSeq.ordSeq(l <++> (a +: r))
1162  }
1163
1164  /** Append `xs` to this sequence, reordering elements to  */
1165  def ++(xs: OrdSeq[A]): OrdSeq[A] = xs.self.toList.foldLeft(this)(_ insert _)
1166}
1167
1168object OrdSeq {
1169  private def ordSeq[A: Order](t: FingerTree[A @@ LastVal, A]): OrdSeq[A] = new OrdSeq[A] {
1170    val self = t
1171    val ord = Order[A]
1172  }
1173
1174  implicit def unwrap[A](t: OrdSeq[A]): FingerTree[A @@ LastVal, A] = t.self
1175
1176  def apply[A: Order](as: A*): OrdSeq[A] = {
1177    val z: OrdSeq[A] = {
1178      implicit val keyer: Reducer[A, A @@ LastVal] = UnitReducer((a: A) => LastVal(a))
1179      ordSeq(empty[A @@ LastVal, A])
1180    }
1181    as.foldLeft(z)((x, y) => x insert y)
1182  }
1183}