@@ -9,3 +9,105 @@ This is a first trial run for my blog. Let's check whether syntax highlighting w
99object Test :
1010 def f (x : String ) = s " hello, $x"
1111```
12+
13+ And something bigger:
14+
15+ ``` scala
16+ //> using options -YXtypeclass -source future
17+ package hylo
18+
19+ /** A collection of elements accessible by their position. */
20+ trait Collection :
21+ type Self
22+
23+ /** The type of the elements in the collection. */
24+ type Element : Value
25+
26+ /** The type of a position in the collection. */
27+ type Position : Value
28+
29+ extension (self : Self )
30+
31+ /** Returns `true` iff `self` is empty. */
32+ def isEmpty : Boolean =
33+ startPosition `eq` endPosition
34+
35+ /** Returns the number of elements in `self`.
36+ *
37+ * @complexity
38+ * O(n) where n is the number of elements in `self`.
39+ */
40+ def count : Int =
41+ val e = endPosition
42+ def loop (p : Position , n : Int ): Int =
43+ if p `eq` e then n else loop(self.positionAfter(p), n + 1 )
44+ loop(startPosition, 0 )
45+
46+ /** Returns the position of `self`'s first element', or `endPosition` if `self` is empty.
47+ *
48+ * @complexity
49+ * O(1)
50+ */
51+ def startPosition : Position
52+
53+ /** Returns the "past the end" position in `self`, that is, the position immediately after the
54+ * last element in `self`.
55+ *
56+ * @complexity
57+ * O(1).
58+ */
59+ def endPosition : Position
60+
61+ /** Returns the position immediately after `p`.
62+ *
63+ * @requires
64+ * `p` is a valid position in `self` different from `endPosition`.
65+ * @complexity
66+ * O(1).
67+ */
68+ def positionAfter (p : Position ): Position
69+
70+ /** Accesses the element at `p`.
71+ *
72+ * @requires
73+ * `p` is a valid position in `self` different from `endPosition`.
74+ * @complexity
75+ * O(1).
76+ */
77+ def at (p : Position ): Element
78+
79+ /** Returns `true` iff `i` precedes `j`.
80+ *
81+ * @requires
82+ * `i` and j` are valid positions in `self`.
83+ * @complexity
84+ * O(n) where n is the number of elements in `self`.
85+ */
86+ def isBefore (i : Position , j : Position ): Boolean =
87+ val e = self.endPosition
88+ if i `eq` e then false
89+ else if j `eq` e then true
90+ else
91+ def recur (n : Position ): Boolean =
92+ if n `eq` j then true
93+ else if n `eq` e then false
94+ else recur(self.positionAfter(n))
95+ recur(self.positionAfter(i))
96+
97+ class Slice2 (val base : Self , val bounds : Range [Position ]):
98+
99+ def isEmpty : Boolean =
100+ bounds.lowerBound.eq(bounds.upperBound)
101+
102+ def startPosition : Position =
103+ bounds.lowerBound
104+
105+ def endPosition : Position =
106+ bounds.upperBound
107+
108+ def at (p : Position ): Element =
109+ base.at(p)
110+ end Slice2
111+
112+ end Collection
113+ ```
0 commit comments