Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // The "struct" keyword establishes a namespace and a new type name
- // This block directly describes the layout of the type
- // I don't want to mix data with the behavior so this block is
- // strictly for the instance fields.
- struct Turtle{
- var x y: f32;
- var heading: f32;
- var shell_color: u32;
- }
- // The "implementation" block lets you put the stuff into the type's namespace
- // This stuff will be accessible with the `Turtle.name` syntax and is also
- // allowed to access private stuff within the namespace, like private fields.
- implementation Turtle{
- // 'ref' is lifetime-checked non-nullable pointer
- // functions return void by default
- function advance(self: ref Turtle){
- // '.' lets us access Turtle's fields here because ref T implements
- // proxy[T] protocol - so when a name lookup fails on the `ref Turtle`
- // type itself, it continues to search on the `T`
- self.x += cos(self.heading);
- self.y += sin(self.heading);
- }
- function rotate(self: ref Turtle, delta: f32){
- self.heading += delta;
- }
- // 'private' means private to the namespace - it is not possible to invoke
- // color_multiply from the outside
- private function color_mix(first second: u32): u32{
- // x `identifier` y lets you use a two-argument function as an infix operator
- // and is in fact a syntactic sugar for identifier(x, y)
- // all such operators are left-associative and have the same priority
- var r1: u32 = (first `shr` 16) `bitand` 0xff;
- var g1: u32 = (first `shr` 8) `bitand` 0xff;
- var b1: u32 = (first `shr` 0) `bitand` 0xff;
- var r2: u32 = (second `shr` 16) `bitand` 0xff;
- var g2: u32 = (second `shr` 8) `bitand` 0xff;
- var b2: u32 = (second `shr` 0) `bitand` 0xff;
- var r: u32 = (r1 + r2) / 2;
- var g: u32 = (g1 + g2) / 2;
- var b: u32 = (b1 + b2) / 2;
- return (r `shl` 16) `bitor` (g `shl` 8) `bitor` (b `shl` 0);
- }
- function breed(first second: ref Turtle): Turtle{
- // constructor expression - struct name followed by JSON-like object
- // creates a new instance of the type
- return Turtle{
- x: (first.x + second.x) / 2,
- y: (first.y + second.y) / 2,
- heading: (first.heading + second.heading) / 2,
- shell_color: color_mix(first.shell_color, second.shell_color)
- };
- }
- }
Add Comment
Please, Sign In to add comment