/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

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