diff --git a/examples/extending-structs.jt b/examples/extending-structs.jt new file mode 100644 index 0000000..3d8d8bc --- /dev/null +++ b/examples/extending-structs.jt @@ -0,0 +1,15 @@ + +struct A { + int a, + int b +} + +struct B <- A { + int c +} + +fn main () { + a := A{1, 2} + b := B{1, 2, 3} +} + diff --git a/examples/function-overload.jt b/examples/function-overload.jt index 4912ef9..e47830a 100644 --- a/examples/function-overload.jt +++ b/examples/function-overload.jt @@ -13,4 +13,3 @@ fn main () { my_puts(2) my_puts("aaa") } - diff --git a/examples/hello.jt b/examples/hello.jt index 798ae28..efed740 100644 --- a/examples/hello.jt +++ b/examples/hello.jt @@ -1,6 +1,10 @@ import io +// if a return type is not defined, it is implicitly void and so the function +// returns nil (the only instance of void) + +// main can return int or void, void mains are handled by jortsc fn main () -> int { - io.puts("pant") - ret 0 + io.puts("pants") + 0 } diff --git a/examples/sockets.jt b/examples/sockets.jt new file mode 100644 index 0000000..08ab425 --- /dev/null +++ b/examples/sockets.jt @@ -0,0 +1,10 @@ +import socket +import io + +fn main () { + sock := socket.tcp_connect("example.com", 80) + sock.send("HTTP/1.1\n") + frame := sock.recv(1024) + sock.close() + io.puts(frame) +} diff --git a/examples/strings.jt b/examples/strings.jt index d7554f4..75f0931 100644 --- a/examples/strings.jt +++ b/examples/strings.jt @@ -7,7 +7,7 @@ fn main () { s := "this is {s}" io.puts(s) - s + 2 // invalid + s := s + 2 // invalid // this however, is valid, there is an io.puts that handles int, // more on function overload in a bit diff --git a/examples/struct-functions.jt b/examples/struct-functions.jt new file mode 100644 index 0000000..38df73e --- /dev/null +++ b/examples/struct-functions.jt @@ -0,0 +1,60 @@ +import io + +struct A { + int val1, + int val2 +} + +// self is injected and represents the struct A +// from the functions' definition +fn A:sum_fields() -> int { + self.val1 + self.val2 +} + +// type of sum_fields is: +// Func ([A] -> int) + +// the mut keyword signals that self is a "reference" +// to self, instead of a copy + +// however, what actually happens is that an instance of +// A is returned from the function implicitly + +fn mut A:incr_both_fields() { + self.val1++ + self.val2++ +} + +// and so, the type becomes: +// Func ([A] -> A) + +fn mut A:incr_and_sum () { + self.val1++ + self.val2++ + + self.val1 + self.val2 +} + +// type is: +// Func ([A] -> (A, int)) + +fn main () { + a := A{0, 0} + + a.incr_both_fields() + + /* + translates to: + a := incr_both_fields(a) + */ + + sum := a.sum_fields() + io.puts(sum) + + val = a.incr_and_sum() + + /* + translates to: + a, val := incr_and_sum(a) + */ +}