Skip to content

Commit c9e0f23

Browse files
committed
Some sketches of more complex trait heirarchies
1 parent 5067661 commit c9e0f23

2 files changed

Lines changed: 92 additions & 0 deletions

File tree

sketches/slices-as-traits.poni

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Any object that can be used as a slice requires that it can also be used as
2+
// a Sliceable.
3+
trait Slice[T] requires Sliceable[T] {
4+
// maybe a good place for exceptions...?
5+
fun get_index(idx: int) -> Option[T];
6+
fun set_index(idx: int, obj: T) -> Option[void];
7+
}
8+
9+
trait Sliceable[T] {
10+
fun slice(start: int, end: int) -> Option[Slice[T]];
11+
//fun slice_mut(start: int, end: int) -> Option[Slice[mut T]]; //????
12+
}
13+
14+
class ArraySlice[T] {
15+
var parent: Array[T];
16+
var start: int;
17+
var length: int;
18+
19+
impl Slice[T] {
20+
fun get_index(idx: int) -> Option[T] {
21+
if idx < 0 || idx >= length { return none; }
22+
return parent[idx + start];
23+
}
24+
25+
fun set_index(idx: int, obj: T) -> Option[void] {
26+
if idx < 0 || idx >= length { return none; }
27+
parent[idx + start] = obj;
28+
return some void;
29+
}
30+
}
31+
32+
impl Sliceable[T] {
33+
fun slice(start: int, end: int) -> Option[Slice[T]] {
34+
// todo better safety check..?
35+
if start < 0 || end >= length { return none; }
36+
37+
return new ArraySlice[T] {
38+
parent: self.parent,
39+
start: start + self.start,
40+
length: end - start
41+
}
42+
}
43+
}
44+
}
45+
46+
class Array[T] {
47+
impl Sliceable[T] {
48+
fun slice(start: int, end: int) -> Option[Slice[T]] {
49+
if start < 0 || end >= length { return none; }
50+
51+
return new ArraySlice[T] {
52+
parent: self,
53+
start,
54+
length: end - start
55+
};
56+
}
57+
}
58+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Example {
2+
impl Debug { fun fmt_debug(formatter: Fmt); }
3+
impl CloneShallow[Example] { fun clone_shallow() -> Example; }
4+
impl CloneDeep[Example] { fun clone_deep() -> Example; }
5+
impl DrawImmUI { fun ui(ui: ImmUI); }
6+
}
7+
8+
trait Debug {
9+
fun fmt_debug(formatter: Fmt);
10+
11+
fun dbg() {
12+
self.fmt_debug(IO.stderr);
13+
}
14+
15+
fun str() -> StrBuf {
16+
var s: StrBuf = "";
17+
self.fmt_debug(s);
18+
return s;
19+
}
20+
}
21+
22+
trait Display {
23+
fun fmt_display(formatter: Fmt);
24+
25+
fun print() {
26+
self.fmt_display(IO.stdout);
27+
}
28+
29+
fun repr() -> StrBuf {
30+
var s: StrBuf = "";
31+
self.fmt_display(s);
32+
return s;
33+
}
34+
}

0 commit comments

Comments
 (0)