Playground menjalankan subset sintaks di browser. Contoh file, proses, PostgreSQL, dan API harus dijalankan melalui CLI native. Status dukungan dijelaskan pada tiap pelajaran.The Playground runs a subset of the syntax in the browser. File, process, PostgreSQL, and API examples must run through the native CLI. Support status is explained in each lesson.
Cara membaca contoh YAZAHow to read YAZA examples
Cuplikan menunjukkan kode dalam file .yz. Nama tipe menjelaskan bentuk nilai, titik dua membuka blok, dan indentasi empat spasi menunjukkan baris mana yang berada di dalam blok. Tombol Salin kode menyalin hanya cuplikan tersebut.Snippets show code in a .yz file. Type names describe values, a colon opens a block, and four spaces show which lines belong to that block. The Copy code button copies only that snippet.
Label Didukung berarti sintaks terlihat pada compiler/library saat ini; itu bukan jaminan bahwa API stabil atau siap produksi. Preview browser berarti contoh sederhana dapat dicoba di halaman Playground.Supported means the syntax exists in the current compiler/library; it does not guarantee a stable or production-ready API. Browser preview means a simple example can run on the Playground page.
00 · Bagian terkecil dari sintaksThe smallest parts of the syntax
Sebelum membaca program, kenali potongan kecil yang dibaca compiler. File sumber YAZA memakai ekstensi .yz. Huruf besar dan kecil dibedakan: Text, text, dan TEXT adalah ejaan yang berbeda.Before reading a program, learn the small pieces the compiler reads. YAZA source files use the .yz extension. Letter case matters: Text, text, and TEXT are different spellings.
# A whole-line comment
start:
let price: Number = 7
var total: Number = price * 3
set total = total + 1
say "Total: {total}"| PotonganPart | ArtinyaMeaning | Contoh penggunaanExample use |
|---|---|---|
# | Mulai komentar sampai ujung baris.Starts a comment through the end of the line. | # note |
start, let, say | Kata khusus bahasa: titik mulai, deklarasi tetap, dan output.Language keywords: entry point, immutable declaration, and output. | let total: Number = 22 |
price, total | Identifier atau nama yang dipilih programmer. Nama identifier dimulai huruf atau garis bawah, lalu boleh berisi angka.Identifiers are names chosen by the programmer. They start with a letter or underscore, then may contain digits. | find_score |
7, true, "YAZA" | Literal: nilai yang ditulis langsung di source. Angka tidak memakai tanda kutip; teks memakai kutip ganda.Literals: values written directly in source. Numbers are unquoted; text uses double quotes. | 42, false |
: | Mengakhiri header blok atau memisahkan nama variabel dan anotasi tipenya.Ends a block header or separates a variable name from its type annotation. | start: · price: Number |
= | Memberi nilai awal atau nilai baru melalui set; bukan operator perbandingan.Assigns an initial or updated value with set; it is not the equality operator. | set total = 10 |
(), , | Kurung membatasi argumen fungsi; koma memisahkan argumen.Parentheses enclose function arguments; commas separate them. | add(2, 3) |
[] | Menuliskan parameter tipe list, misalnya list berisi Number.Writes a list type parameter, such as a list of Numbers. | List[Number] |
. | Mengakses field milik sebuah nilai shape.Accesses a field on a shape value. | product.price |
-> | Menyatakan tipe hasil fungsi, bukan nilai yang dikembalikan.Declares a function's return type; it is not the returned value. | fn add(...) -> Number: |
| Empat spasiFour spaces | Menentukan baris mana yang termasuk ke dalam blok. Gunakan indentasi konsisten; jangan campur tab dan spasi.Determines which lines belong to a block. Use consistent indentation; do not mix tabs and spaces. | start: lalu say ... |
Baris program selesai saat baris baru tiba; tidak perlu titik koma. Tanda kurung kurawal untuk blok tidak dipakai. Pada ekspresi, tanda kurung (...) dapat mengelompokkan perhitungan; perkalian/pembagian dikerjakan sebelum penjumlahan/pengurangan, lalu perbandingan, and, dan or. Gunakan tanda kurung bila urutannya ingin terlihat jelas.A statement ends at a newline; no semicolon is needed. Braces do not mark blocks. In expressions, parentheses (...) can group calculations; multiplication/division happen before addition/subtraction, then comparisons, and, and or. Use parentheses when you want the order to be explicit.
01 · Program pertama: Hello WorldFirst program: Hello World
Buat file hello.yz. Baris pertama menyatakan titik mulai; baris kedua mencetak teks.Create a file named hello.yz. The first line declares the entry point; the second prints text.
start:
say "Hello, world!"start:Titik masuk program. Compiler menjalankan isi blok ini. Tanda
:membuka blok.The program entry point. The compiler runs this block. The:opens the block.sayPerintah output YAZA. Nilai setelahnya ditampilkan sebagai satu baris.YAZA's output statement. The following value is printed on one line.
"Hello, world!"Nilai teks literal. Tanda kutip membedakan teks dari nama variabel atau kata bahasa.A text literal. Quotes distinguish text from a variable name or language keyword.
4 spacesIndentasi menandakan bahwa
sayberada di dalamstart. Pakai empat spasi secara konsisten.Indentation shows thatsaybelongs tostart. Use four spaces consistently.
02 · Komentar dan blokComments and blocks
Tanda # memulai komentar sampai akhir baris. Komentar membantu manusia; compiler mengabaikannya. YAZA memakai indentasi dan tanda titik dua untuk menandai blok, bukan kurung kurawal.# starts a comment through the end of the line. Comments help people; the compiler ignores them. YAZA uses indentation and colons for blocks instead of braces.
# This is a comment.
start:
# This statement belongs to start.
say "Comments do not run."# ...Keterangan di baris ini tidak menjadi output dan tidak mengubah nilai program.This line is documentation; it produces no output and changes no program value.
start:Membuka blok utama dengan indentasi nol.Opens the main block at indentation level zero.
say ...Empat spasi menempatkan perintah dalam blok. Salah indentasi akan membuat batas blok keliru.Four spaces place the statement inside the block. Incorrect indentation changes the block boundary.
03 · Variabel: let, var, dan setVariables: let, var, and set
let membuat binding yang tidak dapat diganti. var membuat binding yang boleh diperbarui; set melakukan pembaruan. Setiap deklarasi menuliskan tipe setelah nama.let creates a binding that cannot be reassigned. var creates a binding that may change; set updates it. Each declaration writes the type after the name.
start:
let name: Text = "Dina"
var attempts: Number = 1
set attempts = attempts + 1
say name
say attempts2
let nameMembuat nama
namedengan nilai yang tidak dapat ditimpa oleh perintahset.Createsname, which cannot be reassigned withset.: TextAnotasi tipe menyatakan bahwa nilainya berupa teks. Nilai awal harus cocok dengan tipe ini.The type annotation says the value is text. The initial value must match this type.
var attemptsNilai ini boleh diubah karena dideklarasikan dengan
var.This value may change because it is declared withvar.set attempts = ...Membaca nilai lama, menambah satu, lalu menyimpan hasilnya kembali.Reads the old value, adds one, and stores the result back.
say nameTanpa tanda kutip,
nameberarti baca nilai variabel. Dengan kutip,"name"adalah teks literal.Without quotes,namereads the variable. With quotes,"name"is literal text.
04 · Tipe data yang tersediaAvailable data types
Tipe diperiksa compiler. Berikut tipe inti yang dipakai pada contoh saat ini; tipe turunan dan library memiliki batas dukungan masing-masing.The compiler checks types. These core types appear in current examples; derived types and libraries have their own support limits.
| TipeType | ArtiMeaning | ContohExample |
|---|---|---|
Text | Teks UTF-8 yang direpresentasikan sebagai string berakhiran NUL pada runtime native.UTF-8 text represented as a NUL-terminated string in the native runtime. | "YAZA" |
Number | Integer bertanda 64-bit pada compiler native.Signed 64-bit integer in the native compiler. | 42 |
Int32 | Integer bertanda 32-bit dengan rentang yang diperiksa.Checked signed 32-bit integer. | int32_from_number(42) |
Float64 | Bilangan pecahan 64-bit; operasi non-finite ditolak pada jalur yang diperiksa.64-bit floating-point value; non-finite values are rejected in checked paths. | float64_parse("1.25") |
Boolean | Nilai logika true atau false.Logical value true or false. | true |
TextList | Daftar teks untuk API list dasar.A list of text values for the basic list API. | text_split("a,b", ",") |
List[T] | Daftar bertipe yang elemennya memiliki tipe T, misalnya List[Number] atau List[Product].A typed list whose items have type T, such as List[Number] or List[Product]. | List[Number]() |
Bytes | Data biner dengan panjang eksplisit dan batas ukuran per nilai.Binary data with an explicit length and a per-value size limit. | bytes_from_text("abc") |
shape, variant | Tipe data buatan programmer; dipelajari di pelajaran 15–16.Programmer-defined data types; covered in lessons 15–16. | Product, DeliveryState |
Option[T], Result[T,E] | Tipe pembungkus untuk nilai opsional dan hasil sukses/gagal.Wrapper types for optional values and success/error results. | Option[Text] |
Koleksi umum yang tersedia saat ini adalah TextList dan List[T]. Tipe tuple, set, dan map/dictionary belum tersedia sebagai koleksi umum. TextList hanya menyimpan teks, bukan pasangan kunci dan nilai.The general collections currently available are TextList and List[T]. Tuple, set, and map/dictionary are not available as general collections yet. TextList stores text only; it does not store key-value pairs.
05 · Teks, interpolation, panjang, dan pencarianText, interpolation, length, and search
Teks diapit tanda kutip ganda. Bentuk {namaVariabel} menyisipkan nilai variabel ke dalam teks. Fungsi text_length mengukur byte UTF-8, sedangkan text_find memberi offset byte atau -1 jika tidak ditemukan.Text uses double quotes. The form {variableName} inserts a variable value into text. text_length measures UTF-8 bytes, and text_find returns a byte offset or -1 when absent.
start:
let language: Text = "YAZA"
let message: Text = "Belajar {language}"
let position: Number = text_find(message, "YAZA")
let missing: Number = text_find(message, "Rust")
say message
say text_length(message)
say position
say missing12
8
-1
{language}Compiler mengganti placeholder dengan isi variabel
language.The compiler replaces the placeholder with the value oflanguage.text_find(text, needle)Mencari teks kedua di dalam teks pertama. Contoh memakai karakter ASCII agar offset byte mudah dibaca; teks multibyte menghasilkan offset byte, bukan indeks karakter.Searches for the second text inside the first. This example uses ASCII so byte offsets are easy to read; multibyte text returns a byte offset, not a character index.
text_split / text_joinMemecah satu teks menjadi
TextListatau menggabungkan list dengan pemisah. Pemisah kosong tidak valid untuktext_split.Split text into aTextListor join a list with a separator. An empty separator is invalid fortext_split.
06 · Angka, aritmetika, dan konversiNumbers, arithmetic, and conversion
Number dipakai untuk integer umum; Int32 untuk integer dengan batas 32-bit; Float64 untuk pecahan. Konversi ditulis eksplisit supaya batas dan perubahan representasi terlihat.Number is for general integers; Int32 for 32-bit bounded integers; Float64 for fractional numbers. Conversions are explicit so bounds and representation changes are visible.
start:
let width: Number = 7
let height: Number = 6
let area: Number = width * height
let price: Int32 = int32_from_number(1499)
let ratio: Float64 = float64_from_number(3)
say area
say int32_text(price)
say float64_text(ratio)1499
3
+ - * /Operator aritmetika bekerja pada nilai numerik. Pembagian
Numberadalah pembagian integer; gunakanFloat64untuk hasil pecahan.Arithmetic operators work on numeric values. DividingNumbervalues is integer division; useFloat64for fractional results.int32_from_numberMemeriksa bahwa nilai berada pada rentang Int32. Konversi yang di luar rentang gagal, bukan diam-diam dipotong.Checks that the value is within the Int32 range. An out-of-range conversion fails instead of silently truncating.
float64_from_numberMengubah integer menjadi Float64. Fungsi pasangan seperti
number_from_int32,float64_parse, danfloat64_texttersedia untuk konversi lain.Converts an integer to Float64. Related functions such asnumber_from_int32,float64_parse, andfloat64_textsupport other conversions.
07 · Operator perbandingan dan logikaComparison and logical operators
==, !=, <, <=, >, dan >= membandingkan nilai. Operator and, or, dan not menggabungkan atau membalik kondisi Boolean.==, !=, <, <=, >, and >= compare values. and, or, and not combine or invert Boolean conditions.
start:
let age: Number = 20
let has_ticket: Boolean = true
let can_enter: Boolean = age >= 17 and has_ticket
say can_enter
say not has_ticketfalse
Gunakan == untuk membandingkan. Satu tanda = dipakai saat memberi nilai awal, bukan untuk membandingkan.Use == to compare. A single = assigns an initial value; it is not a comparison operator.
08 · Kondisi: if, elif, elseConditions: if, elif, else
Pilih blok dengan if. Jika kondisi pertama salah, elif memeriksa kondisi berikutnya; else menangani sisa kemungkinan.Choose a block with if. If the first condition is false, elif checks the next one; else handles the remaining case.
fn label(score: Number) -> Text:
if score < 75:
return "Practice more"
elif score == 75:
return "On the line"
else:
return "Passed"
start:
say label(82)
say label(70)Practice more
if score < 75:Kondisi harus menghasilkan Boolean. Jika benar, jalankan blok yang menjorok di bawahnya.The condition must evaluate to Boolean. If true, run the indented block below it.
elifHanya diperiksa bila cabang sebelumnya tidak dipilih. Beberapa
elifdapat dirangkai.Checked only when earlier branches were not selected. Multipleelifbranches may be chained.returnMenghentikan fungsi dan mengembalikan nilai yang tipenya sesuai anotasi setelah tanda panah.Stops the function and returns a value matching the type written after the arrow.
09 · Perulangan whileWhile loops
while mengulang blok selama kondisi benar. Perbarui variabel kondisi agar loop selesai; compiler tidak otomatis menghentikan loop yang tidak berujung.while repeats a block while its condition is true. Update the condition variable so the loop can finish; the compiler does not automatically stop an infinite loop.
start:
var count: Number = 1
while count <= 3:
say count
set count = count + 12
3
Urutannya: uji kondisi, jalankan isi loop, ubah count, lalu uji lagi. Kata break dapat keluar lebih awal; continue lompat ke iterasi berikutnya.Order: test the condition, run the body, update count, then test again. break exits early; continue skips to the next iteration.
10 · Perulangan for, range, break, continueFor loops, ranges, break, continue
for mengunjungi setiap nilai pada range atau list. Pada 1..6, batas akhir tidak ikut: hasilnya 1 sampai 5.for visits each value in a range or list. In 1..6, the end is exclusive, so the values are 1 through 5.
start:
for value in 1..6:
if value == 3:
continue
if value == 5:
break
say value2
4
for value in ...Memberi nama
valuepada nilai saat ini selama satu putaran.Binds the current item tovaluefor one iteration.continueMelewati
saysaat nilainya 3 dan melanjutkan loop.Skipssaywhen the value is 3, then continues the loop.breakMengakhiri seluruh loop saat nilainya 5.Ends the entire loop when the value is 5.
11 · Fungsi, parameter, dan hasilFunctions, parameters, and return values
Fungsi diberi nama dengan fn. Setiap parameter dan hasil memiliki tipe. Fungsi membuat langkah yang dapat dipanggil dari beberapa tempat.Declare a function with fn. Each parameter and return value has a type. Functions package steps that can be called from multiple places.
fn add(left: Number, right: Number) -> Number:
return left + right
fn twice(value: Number) -> Number:
return add(value, value)
start:
let result: Number = twice(21)
say resultfn add(...)Nama fungsi diikuti daftar parameter. Setiap parameter ditulis
nama: Tipe.The function name is followed by parameters. Each parameter is written asname: Type.-> NumberMenyatakan tipe hasil fungsi. Tanda panah bukan operator di dalam baris pengembalian.Declares the function's return type. The arrow is part of the function signature.
add(value, value)Memanggil fungsi lain dan meneruskan dua argumen bertipe
Number.Calls another function and passes twoNumberarguments.
12 · List: TextList dan List[T]Lists: TextList and List[T]
List dibuat bertipe dan diisi satu per satu. TextList adalah bentuk list khusus teks; List[Number] menyimpan integer, dan List[Product] dapat menyimpan nilai shape.Lists are typed and populated one item at a time. TextList is a text-specific list; List[Number] stores integers, and List[Product] can store shape values.
start:
var scores: List[Number] = List[Number]()
list_push(scores, 82)
list_push(scores, 95)
let count: Number = list_count(scores)
let first: Number = list_get(scores, 0)
list_set(scores, 0, 90)
say count
say first
say list_get(scores, 0)82
90
List[Number]()Membuat list kosong dengan tipe elemen Number. Tipe tidak boleh dicampur sembarang.Creates an empty list whose items are Numbers. Arbitrary types cannot be mixed.
list_pushMenambahkan item ke akhir list. Tipe item harus cocok dengan
T.Appends an item to the end. Its type must matchT.list_get(list, index)Mengambil item berdasarkan indeks mulai dari nol. Indeks di luar rentang merupakan error.Gets an item by zero-based index. An out-of-range index is an error.
list_try_getMengembalikan
Option[T]sehingga indeks negatif/di luar list dapat ditangani tanpa akses langsung yang gagal.ReturnsOption[T]so negative or out-of-range indexes can be handled without an invalid direct access.list_setMengganti item yang sudah ada pada indeks tertentu; tidak menambahkan elemen baru di luar panjang list.Replaces an existing item at an index; it does not append a new item past the list length.
13 · Searching: mencari item dalam listSearching: find an item in a list
Untuk teks, gunakan text_find. Untuk mencari nilai dalam typed list, belum ada fungsi umum list_find; tulis loop, bandingkan item, lalu kembalikan indeks atau penanda -1.Use text_find for text. There is no general list_find function yet; loop through the typed list, compare each item, then return its index or the sentinel -1.
fn find_score(values: List[Number], target: Number) -> Number:
var index: Number = 0
while index < list_count(values):
if list_get(values, index) == target:
return index
set index = index + 1
return -1
start:
var scores: List[Number] = List[Number]()
list_push(scores, 82)
list_push(scores, 95)
list_push(scores, 76)
say find_score(scores, 95)
say find_score(scores, 100)-1
index = 0Pencarian dimulai dari item pertama. Indeks list YAZA dimulai dari nol.Search starts at the first item. YAZA list indexes begin at zero.
list_get(...) == targetBandingkan satu item dengan nilai yang dicari. Ini disebut linear search karena item diperiksa berurutan.Compares one item with the target. This is a linear search because items are checked in order.
return indexMenghentikan pencarian ketika ditemukan. Jika loop selesai, fungsi mengembalikan
-1.Stops searching when found. If the loop ends, the function returns-1.
Biaya pencarian ini bertambah sebanding dengan jumlah item: untuk list berisi n item, kasus terburuk memeriksa n item. Belum ada index/hash map umum bawaan.This search cost grows with the number of items: for a list of n items, the worst case checks n items. A general built-in index/hash map is not available yet.
Membaca fungsi pencarian satu bagian demi satu bagianRead the search function piece by piece
| KodeCode | Yang terjadiWhat happens |
|---|---|
fn find_score(...) | Mendeklarasikan fungsi pencarian. Ia menerima list bernama values dan satu nilai target; keduanya bertipe Number.Declares a search function. It receives a list named values and a target value; both use Number. |
-> Number | Hasil fungsi adalah angka yang dipakai sebagai indeks. Konvensi contoh ini memakai -1 untuk “tidak ditemukan”.The function returns a number used as an index. This example uses -1 to mean “not found.” |
var index = 0 | Membuat penghitung posisi mulai dari indeks pertama. Indeks pertama bernomor 0, yang kedua 1, dan seterusnya.Creates a position counter starting at the first index. The first index is 0, the next is 1, and so on. |
while index < list_count(values) | Mengulang hanya selama indeks masih lebih kecil dari jumlah item. Bila jumlah item 3, indeks validnya 0, 1, 2; kondisi ini mencegah baca indeks 3.Repeats only while the index is below the item count. If there are 3 items, valid indexes are 0, 1, and 2; this prevents reading index 3. |
list_get(values, index) | Mengambil nilai pada posisi saat ini. Akses langsung aman karena kondisi while membatasi indeks.Reads the value at the current position. This direct access is safe because the while condition bounds the index. |
== target | Membandingkan item dan target. Hasil perbandingan adalah Boolean, yaitu true atau false.Compares the item to the target. A comparison produces a Boolean: true or false. |
return index | Mengakhiri fungsi segera saat item sama. Jika ada nilai kembar, linear search ini mengembalikan kecocokan pertama.Immediately ends the function when values match. If duplicates exist, this linear search returns the first match. |
set index = index + 1 | Jika tidak cocok, maju satu posisi. Tanpa pembaruan ini loop akan terus memeriksa item yang sama.If there is no match, advance one position. Without this update, the loop would keep checking the same item. |
return -1 | Dicapai hanya setelah semua item diperiksa tanpa kecocokan. Untuk list kosong, loop langsung dilewati lalu hasilnya juga -1.Reached only after every item is checked with no match. For an empty list, the loop is skipped and the result is also -1. |
list_push(...) | Menyusun data contoh menjadi [82, 95, 76]. Argumen kedua pada find_score(scores, 95) adalah nilai yang dicari, bukan indeks.Builds the example data [82, 95, 76]. The second argument in find_score(scores, 95) is the value to find, not an index. |
Jejak pencarian 95: indeks 0 berisi 82 (tidak cocok), indeks 1 berisi 95 (cocok), maka hasilnya 1 dan indeks 2 tidak pernah diperiksa. Jejak pencarian 100: 82 → 95 → 76 (semuanya tidak cocok), lalu hasilnya -1.Searching for 95: index 0 contains 82 (no match), index 1 contains 95 (match), so the result is 1 and index 2 is never checked. Searching for 100: 82 → 95 → 76 (no matches), then the result is -1.
13b · Binary search: mencari pada list yang sudah urutBinary search: search an already sorted list
Binary search membuang setengah ruang pencarian pada tiap langkah. Jika urutan list tidak benar, hasilnya bisa salah meskipun target ada. Untuk list kecil atau data yang belum diurutkan, gunakan linear search di atas.Binary search discards half of the remaining search area at each step. If the list is not sorted, it can return the wrong result even when the target exists. For small or unsorted lists, use the linear search above.
fn binary_search(values: List[Number], target: Number) -> Number:
var low: Number = 0
var high: Number = list_count(values) - 1
while low <= high:
let middle: Number = low + (high - low) / 2
let current: Number = list_get(values, middle)
if current == target:
return middle
elif current < target:
set low = middle + 1
else:
set high = middle - 1
return -1
start:
var ordered: List[Number] = List[Number]()
list_push(ordered, 7)
list_push(ordered, 19)
list_push(ordered, 42)
list_push(ordered, 61)
list_push(ordered, 85)
say binary_search(ordered, 42)
say binary_search(ordered, 50)-1
| NamaName | PeranRole |
|---|---|
low | Batas indeks paling kiri yang belum dieliminasi.Leftmost index that has not been eliminated. |
high | Batas indeks paling kanan yang belum dieliminasi. Nilai awal jumlah item dikurangi satu.Rightmost index that has not been eliminated. It starts at item count minus one. |
middle | Titik tengah rentang aktif. Rumus low + (high - low) / 2 memilih indeks integer di tengah.Midpoint of the active range. low + (high - low) / 2 selects an integer index near the center. |
current < target | Semua angka di kiri atau sama dengan current tidak mungkin menjadi target; geser low melewati tengah.Nothing at or left of current can be the target; move low past the midpoint. |
else | Karena nilai tidak sama dan tidak lebih kecil, ia lebih besar. Geser high ke kiri tengah.Since the value is neither equal nor smaller, it is larger. Move high left of the midpoint. |
low > high | Rentang kosong berarti target tidak ada. Loop berhenti dan fungsi mengembalikan -1.An empty range means the target is absent. The loop ends and the function returns -1. |
Jejak untuk target 50 di list [7, 19, 42, 61, 85]: tengah indeks 2 adalah 42, jadi cari kanan; tengah indeks 3 adalah 61, jadi cari kiri; kini batas bertemu terbalik, sehingga hasilnya -1. Jumlah pemeriksaan tumbuh kira-kira seperti log₂(n). Bila ada angka kembar, contoh ini boleh mengembalikan salah satu indeks yang berisi nilai itu, tidak dijamin indeks pertama.Trace for target 50 in [7, 19, 42, 61, 85]: midpoint index 2 is 42, so search right; midpoint index 3 is 61, so search left; the bounds cross, so the result is -1. The number of checks grows roughly as log₂(n). If duplicates exist, this function may return any matching index; it does not promise the first.
14 · Sorting: urutkan angka dengan selection sortSorting: order numbers with selection sort
Compiler belum menyediakan list_sort. Contoh ini mengajarkan algoritma selection sort memakai list_get dan list_set: setiap putaran mencari nilai terkecil di bagian yang belum urut, lalu menukarnya ke depan.The compiler does not provide list_sort yet. This example teaches selection sort using list_get and list_set: each pass finds the smallest value in the unsorted portion, then swaps it to the front.
fn selection_sort(values: List[Number]) -> Number:
let size: Number = list_count(values)
var index: Number = 0
while index < size - 1:
var smallest: Number = index
var scan: Number = index + 1
while scan < size:
if list_get(values, scan) < list_get(values, smallest):
set smallest = scan
set scan = scan + 1
if smallest != index:
let current: Number = list_get(values, index)
let minimum: Number = list_get(values, smallest)
list_set(values, index, minimum)
list_set(values, smallest, current)
set index = index + 1
return size
start:
var scores: List[Number] = List[Number]()
list_push(scores, 42)
list_push(scores, 7)
list_push(scores, 19)
let sorted_count: Number = selection_sort(scores)
var position: Number = 0
while position < sorted_count:
say list_get(scores, position)
set position = position + 119
42
smallestMenyimpan indeks nilai terkecil yang ditemukan pada bagian sisa list.Stores the index of the smallest value found in the remaining part of the list.
scanMemeriksa setiap posisi setelah posisi yang sedang diisi.Checks each position after the slot currently being filled.
list_setDua pemanggilan menukar nilai lama dengan nilai minimum. Algoritma ini mudah dipelajari tetapi lambat untuk list besar: waktunya O(n²).The two calls swap the current value with the minimum. This algorithm is easy to learn but slow on large lists: O(n²) time.
Arti bagian selection sortWhat each part of selection sort means
| KodeCode | Arti dan alasanMeaning and reason |
|---|---|
fn selection_sort(values: List[Number]) | Fungsi menerima list integer. Karena list bertipe List[Number], nilainya tidak dicampur dengan teks atau Boolean.The function receives an integer list. Since it is List[Number], its items are not mixed with text or Booleans. |
size = list_count(values) | Menyimpan panjang list sekali agar kondisi loop mudah dibaca. size adalah jumlah item, bukan indeks terakhir.Stores the list length once to make loop conditions readable. size is the item count, not the last index. |
index = 0 | Menunjuk slot depan yang akan diisi dengan nilai terkecil berikutnya.Points to the front slot that will receive the next smallest value. |
index < size - 1 | Cukup mengerjakan sampai slot kedua dari belakang. Setelah itu, satu item tersisa pasti sudah berada pada tempatnya. List kosong atau satu item tidak perlu diubah.Only processes through the second-to-last slot. The final remaining item must then already be in place. Empty and one-item lists need no changes. |
smallest = index | Anggap dahulu nilai pada slot depan sebagai nilai terkecil sementara. Variabel ini menyimpan indeks, bukan nilai angkanya.Initially assume the front value is the smallest. This variable stores its index, not the numeric value. |
scan = index + 1 | Mulai memeriksa bagian yang belum terurut di sebelah kanan slot depan.Starts scanning the unsorted section to the right of the front slot. |
list_get(values, scan) < list_get(values, smallest) | Membaca dua angka lalu membandingkannya. Jika nilai yang sedang dipindai lebih kecil, catat posisinya sebagai kandidat terkecil baru.Reads and compares two numbers. If the scanned value is smaller, remember its position as the new minimum candidate. |
set smallest = scan | Memperbarui indeks kandidat. Nilai dalam list belum dipindah sampai semua kandidat selesai dibandingkan.Updates the candidate index. Values are not moved until all candidates have been compared. |
set scan = scan + 1 | Maju ke item berikutnya. Pembaruan ini berada di dalam loop kedua, jadi setiap item sisa hanya diperiksa sekali pada putaran tersebut.Moves to the next item. This update is inside the inner loop, so each remaining item is checked once on that pass. |
current dan minimum | Menyimpan kedua angka sebelum menulis ulang list. Variabel sementara mencegah nilai pertama hilang saat penukaran.Save both numbers before writing to the list. Temporary variables prevent the first value from being lost during the swap. |
list_set(...) | Menaruh nilai terkecil ke slot depan lalu memindahkan nilai lama ke slot asal minimum. List yang diberikan ke fungsi berubah langsung.Places the minimum in the front slot and moves the old front value to the minimum's former slot. The list passed to the function is changed in place. |
index = index + 1 | Menyelesaikan satu slot dan berpindah ke slot berikutnya. Bagian sebelum index kini sudah terurut.Completes one slot and advances to the next. The portion before index is now sorted. |
return size | Mengembalikan jumlah item agar pemanggil tahu berapa banyak nilai yang dapat dicetak. List yang terurut tetap berada di variabel aslinya.Returns the item count so the caller knows how many values to print. The sorted list remains in the original variable. |
position dan list_get | Loop terakhir hanya menampilkan hasil dari indeks 0 sampai sorted_count - 1; indeks akhir tidak boleh ikut.The final loop prints indexes 0 through sorted_count - 1; the endpoint itself is not a valid index. |
Jejak perubahan nilaiTrace the value changes
| PutaranPass | Bagian yang diperiksaValues scanned | TindakanAction | Isi list setelahnyaList afterward |
|---|---|---|---|
| 1 | [42, 7, 19] | Minimum 7; tukar indeks 0 dan 1.Minimum is 7; swap indexes 0 and 1. | [7, 42, 19] |
| 2 | [42, 19] | Minimum 19; tukar indeks 1 dan 2.Minimum is 19; swap indexes 1 and 2. | [7, 19, 42] |
| 3 | Tidak ada; satu nilai tersisa.None; one value remains. | Loop berhenti karena index < size - 1 salah.The loop stops because index < size - 1 is false. | [7, 19, 42] |
Contoh ini mengurutkan naik karena membandingkan dengan <. Untuk urutan turun, pilih nilai terbesar dan ubah perbandingannya menjadi >. Item kembar tetap ada; sorting tidak menghapus duplikat. Nilai negatif juga dapat diurutkan. List kosong dan list satu item langsung selesai. Algoritma ini memakai sekitar n × (n - 1) / 2 perbandingan, sehingga waktu tumbuh kuadratik O(n²); ia cocok untuk belajar dan data kecil, bukan list besar. Implementasi ini menukar item langsung di list dan memakai beberapa variabel sementara, sehingga ruang tambahan konstan. Belum ada fungsi bawaan list_sort; insertion sort, merge sort, atau API sorting standar belum didokumentasikan sebagai fitur library stabil.This example sorts ascending because it compares with <. For descending order, select the largest value and change the comparison to >. Duplicates remain; sorting does not remove them. Negative numbers also sort correctly. Empty and one-item lists finish immediately. This algorithm makes about n × (n - 1) / 2 comparisons, so its time grows quadratically as O(n²); it is useful for learning and small lists, not large ones. This implementation swaps items in place and uses only a few temporary variables, so extra space is constant. There is no built-in list_sort; insertion sort, merge sort, and a stable standard sorting API are not yet documented as stable library features.
15 · Shape: mendefinisikan bentuk dataShape: define a data structure
shape mendeklarasikan record bertipe: nama tipe dan daftar field tetap. Compiler memeriksa nama field, jumlah argumen constructor, dan tipe setiap nilai. Constructor mengisi field menurut urutan deklarasi.shape declares a typed record: a type name and a fixed list of fields. The compiler checks field names, constructor argument count, and each value's type. The constructor fills fields in declaration order.
shape Product:
id: Number
name: Text
price: Int32
available: Boolean
fn rename(product: Product, name: Text) -> Product:
return Product(product.id, name, product.price, product.available)
fn product_label(product: Product) -> Text:
return product.name + " (" + int32_text(product.price) + ")"
start:
let book: Product = Product(7, "YAZA Guide", int32_from_number(1499), true)
let renamed: Product = rename(book, "YAZA Programming Guide")
say product_label(renamed)
say renamed.available
var editable: Product = book
set editable.price = int32_from_number(1599)
say int32_text(editable.price)true
1599
shape Product:Mendaftarkan tipe baru bernama
Product. Semua nilai Product memiliki field yang dideklarasikan.Declares a new type namedProduct. Every Product value has the declared fields.price: Int32Nama field adalah
price; tipenya Int32. Memberi teks atau Boolean pada posisi ini akan ditolak compiler.The field is namedpriceand its type is Int32. Passing text or a Boolean here is rejected by the compiler.Product(...)Membuat nilai dengan empat argumen sesuai urutan field: id, name, price, available. Jumlah atau tipe yang salah menjadi error.Creates a value with four arguments in field order: id, name, price, available. Wrong count or types are errors.
product.nameAkses field menggunakan titik. Compiler menolak field yang tidak dideklarasikan.Access a field with a dot. The compiler rejects undeclared fields.
set editable.priceField dapat diperbarui melalui variabel
var. Bentuklettidak boleh dimutasi seperti ini.A field may be updated through avarbinding. Aletbinding cannot be mutated this way.fn product_label(...)Operasi terhadap data ditulis sebagai fungsi biasa yang menerima shape. Belum ada method syntax,
self, inheritance, atau dynamic dispatch.Operations on data are ordinary functions that accept a shape. There is no method syntax,self, inheritance, or dynamic dispatch yet.
16 · Variant dan matchVariants and match
variant mendefinisikan salah satu dari beberapa kasus bernama. Kasus boleh membawa payload bertipe. match memeriksa setiap kemungkinan secara jelas.variant defines one of several named cases. Cases may carry typed payloads. match handles each possibility explicitly.
variant DeliveryState:
Queued
InTransit(tracking_code: Text)
Delivered(recipient: Text)
fn describe(state: DeliveryState) -> Text:
match state:
Queued:
return "queued"
InTransit(code):
return "tracking " + code
Delivered(recipient):
return "delivered to " + recipient
start:
let state: DeliveryState = DeliveryState::InTransit("YZ-2048")
say describe(state)QueuedKasus tanpa payload. Kasus ini dibuat dengan konstruktor berscope seperti
DeliveryState::Queued().A case without a payload. Construct it with a scoped constructor such asDeliveryState::Queued().InTransit(Text)Kasus yang membawa nilai teks. Pola
InTransit(code)mengikat payload itu ke nama lokal.A case that carries text. The patternInTransit(code)binds the payload to a local name.matchCompiler memeriksa nama kasus, tipe payload, duplikasi, dan kelengkapan match untuk variant yang didukung.The compiler checks case names, payload types, duplicates, and exhaustiveness for supported variants.
17 · Option, Result, dan kegagalanOption, Result, and failures
Option[T] berarti ada nilai (some) atau tidak ada (none). Result[T,E] membedakan sukses (ok) dari gagal (err). Ini pola eksplisit untuk nilai yang mungkin tidak tersedia atau operasi yang bisa gagal.Option[T] means a value exists (some) or is absent (none). Result[T,E] distinguishes success (ok) from failure (err). These explicitly model missing values and fallible operations.
fn positive(value: Number) -> Result[Number, Text]:
if value > 0:
return ok(value)
return err("value must be positive")
fn doubled_positive(value: Number) -> Result[Number, Text]:
let accepted: Number = positive(value)?
return ok(accepted * 2)
start:
let good: Result[Number, Text] = doubled_positive(4)
let bad: Result[Number, Text] = doubled_positive(-1)
say result_unwrap(good)
say result_unwrap_error(bad)value must be positive
ok(value)Membungkus hasil sukses ke dalam Result.Wraps a successful value in Result.
err(message)Membungkus nilai error. Jenis error di contoh ini adalah Text.Wraps an error value. The error type in this example is Text.
positive(value)?Operator
?meneruskan error ke pemanggil dan mengambil nilai sukses. Fungsi pembungkus juga harus mengembalikan Result yang kompatibel.The?operator forwards an error to the caller and extracts a successful value. The enclosing function must return a compatible Result.result_unwrapAkses langsung dapat gagal jika Result ternyata berisi error. Periksa
result_is_okatau gunakanmatchpada program nyata.Direct unwrapping can fail if the Result contains an error. Checkresult_is_okor usematchin real programs.
Gunakan Result untuk operasi yang dapat gagal dan Option untuk nilai yang mungkin tidak tersedia. Periksa hasilnya dengan match atau fungsi pemeriksa sebelum mengambil nilainya; jangan menutupi kegagalan dengan nilai default tanpa alasan.Use Result for operations that can fail and Option for values that may be absent. Check the value with match or a status function before extracting it; do not hide failures behind an unjustified default.
18 · Module dan import dengan useModules and imports with use
use mengimpor file module YAZA. Compiler mengembangkan module lokal yang dirujuk oleh path. Dependency jarak jauh, registri package, dan alias dependency belum tersedia.use imports a YAZA module file. The compiler expands a local module referenced by path. Remote dependencies, a package registry, and dependency aliases are not available yet.
use "math"
start:
let total: Number = sum_to(10)
say "Sum: {total}"File math.yz mendeklarasikan fungsi sum_to. Path di-resolve dari file yang mengimpor. Ikuti aturan project/module yang didukung CLI dan gunakan nama module yang jelas.The math.yz file declares sum_to. The path is resolved relative to the importing file. Follow the project/module rules supported by the CLI and use clear module names.
19 · File handling: membaca dan menulis fileFile handling: read and write files
Runtime native menyediakan operasi file teks/biner dan direktori. Contoh berikut menulis, memeriksa, membaca, lalu menambahkan teks. Jalankan dari direktori kerja yang kamu pahami; path relatif dihitung dari direktori proses.The native runtime provides text/binary file and directory operations. This example writes, checks, reads, then appends text. Run it from a working directory you understand; relative paths use the process working directory.
start:
let path: Text = "notes.txt"
let write_status: Number = file_write(path, "First line.\n")
let exists: Boolean = file_exists(path)
let contents: Text = file_read(path)
let append_status: Number = file_append(path, "Second line.\n")
let updated: Text = file_read(path)
say exists
say contents
say updated
say write_status
say append_statusFirst line.
First line.
Second line.
0
0
file_write(path, text)Menulis teks ke path dan mengembalikan kode status numerik; contoh runtime saat ini memakai 0 untuk sukses.Writes text to a path and returns a numeric status; the current runtime uses 0 for success.
file_exists(path)Memeriksa apakah file tersedia sebelum membacanya.Checks whether a file exists before reading it.
file_read(path)Membaca isi file sebagai
Text. Untuk data biner, gunakan keluargafile_read_bytes/file_write_bytes.Reads a file asText. For binary data, use thefile_read_bytes/file_write_bytesfamily.file_append(path, text)Menambahkan teks di akhir file.
file_write_atomictersedia untuk mengganti file secara atomik pada operasi yang didukung.Appends text to a file.file_write_atomicis available for atomic replacement on supported operations.
API lain mencakup file_remove, directory_create, directory_list, path_join, stdin_read, dan byte buffer. Playground browser tidak bisa membaca atau menulis file lokal; gunakan CLI.Other APIs include file_remove, directory_create, directory_list, path_join, stdin_read, and byte buffers. The browser Playground cannot read or write local files; use the CLI.
20 · PostgreSQL: koneksi dan query berparameterPostgreSQL: connect and run parameterized queries
YAZA memiliki client PostgreSQL native dan API query. Contoh proyek examples/pg_wire_query.yz membaca konfigurasi dari environment, membuat koneksi dengan timeout, lalu mengirim parameter terpisah dari SQL. Siapkan YAZA_PG_HOST, YAZA_PG_PORT, YAZA_PG_USER, YAZA_PG_DATABASE, dan YAZA_PG_PASSWORD sebelum menjalankannya.YAZA has a native PostgreSQL client and query APIs. The project example examples/pg_wire_query.yz reads configuration from the environment, connects with a timeout, then sends parameters separately from SQL. Set YAZA_PG_HOST, YAZA_PG_PORT, YAZA_PG_USER, YAZA_PG_DATABASE, and YAZA_PG_PASSWORD first.
use "../std/pg/transport"
start:
let host: Text = env_get("YAZA_PG_HOST")
let port: Number = number_parse(env_get("YAZA_PG_PORT"))
let username: Text = env_get("YAZA_PG_USER")
let database: Text = env_get("YAZA_PG_DATABASE")
let password: Text = env_get("YAZA_PG_PASSWORD")
let connected: Result[Number, Text] = pg_connect(host, port, username, database, password, 5000)
if result_is_ok(connected):
let connection: Number = result_unwrap(connected)
let parameters: PgParameters = pg_parameters_new()
let added: Result[Boolean, Text] = pg_parameters_add_text(parameters, "YAZA")
let query: Result[PgQueryResult, Text] = pg_query_with_parameters(connection, "SELECT $1 AS greeting", parameters, 5000)
if result_is_ok(added) and result_is_ok(query):
let rows: PgQueryResult = result_unwrap(query)
let value: Result[PgValue, Text] = pg_query_value(rows, 0, 0)
if result_is_ok(value):
match result_unwrap(value):
TextValue(text):
say text
Null:
say "NULL"
NumberValue(_):
say "Unexpected number"
BooleanValue(_):
say "Unexpected Boolean"
BytesValue(_):
say "Unexpected bytes"
let closed: Number = pg_disconnect(connection)
else:
say "PostgreSQL connection failed."pg_connect(..., 5000)Membuka koneksi dengan timeout 5.000 milidetik. Nilainya adalah
Result, jadi program harus memeriksa sukses/gagal.Opens a connection with a 5,000 millisecond timeout. It returnsResult, so the program must check success or failure.PgParametersNilai query ditambahkan dengan fungsi bertipe seperti
pg_parameters_add_textataupg_parameters_add_number.Query values are added with typed functions such aspg_parameters_add_textorpg_parameters_add_number.$1Placeholder PostgreSQL mengacu ke parameter pertama. Jangan gabungkan input pengguna ke string SQL.The PostgreSQL placeholder refers to the first parameter. Do not concatenate user input into the SQL string.
pg_query_valueMembaca sel dari hasil berdasarkan indeks baris dan kolom yang dimulai dari nol.
PgValuediperiksa denganmatch.Reads a result cell by zero-based row and column indexes. InspectPgValuewithmatch.pg_disconnectMenutup koneksi setelah pekerjaan selesai. Kode lengkap memeriksa juga kegagalan penambahan parameter, query, dan hasil.Closes the connection when done. The full example also checks parameter, query, and result failures.
Untuk filter/sort/page yang lebih terstruktur, library punya db_select_new, db_select_where, db_select_order_by, db_select_page, dan db_postgres_select. Query builder hanya menerima identifier tervalidasi dan nilai bind terpisah. Contoh lengkap ada di tests/db_postgres_live_smoke.yz. Dukungan PostgreSQL masih testing/development; TLS remote, versi server tambahan, dan CI database menyeluruh masih terbuka.For structured filtering, sorting, and paging, the library provides db_select_new, db_select_where, db_select_order_by, db_select_page, and db_postgres_select. The query builder validates identifiers and keeps bind values separate. See tests/db_postgres_live_smoke.yz for a complete example. PostgreSQL support is still in testing/development; remote TLS, more server versions, and broad database CI remain open.
Buka contoh transaksi PostgreSQL →Open the PostgreSQL transaction example → · Pelajari API HTTP dan PostgreSQL →Learn about the HTTP API and PostgreSQL →
21 · Input terminal, argumen, dan environmentTerminal input, arguments, and environment
Runtime CLI menyediakan stdin_read() untuk membaca teks dari standard input, arg(index) untuk argumen program, dan env_get(name) untuk environment variable. Jangan menaruh password/database secret sebagai literal di source atau log.The CLI runtime provides stdin_read() for standard input, arg(index) for program arguments, and env_get(name) for environment variables. Do not put passwords or database secrets in source literals or logs.
start:
let input: Text = stdin_read()
let file_name: Text = arg(1)
let mode: Text = env_get("YAZA_MODE")
say "Input: {input}"
say "File: {file_name}"
say "Mode: {mode}"Jalankan dengan input pipe atau argumen setelah --, sesuai perintah CLI. Browser preview tidak memiliki stdin atau akses environment proses.Run it with piped input or arguments after --, as supported by the CLI. The browser preview has no process stdin or environment access.
22 · Assert dan menjalankan testAssertions and running tests
assert kondisi menghentikan test bila kondisinya tidak benar. File test memakai ekstensi .test.yz dan dijalankan oleh test runner CLI.assert condition fails a test when the condition is false. Test files use the .test.yz extension and run through the CLI test runner.
fn add(left: Number, right: Number) -> Number:
return left + right
start:
assert add(20, 22) == 42dist/yaza test testsJalankan contoh dengan compiler nativeRun examples with the native compiler
Playground browser mendukung subset sintaks yang ditampilkan pada contoh interaktif. Jalankan PostgreSQL, file, API, module, dan test dari root repository memakai compiler native yang sesuai platform.The browser Playground supports the syntax subset shown in its interactive examples. Run PostgreSQL, file, API, module, and test examples from the repository root with the native compiler for your platform.
dist/yaza check examples/shapes.yz
dist/yaza run examples/shapes.yz
dist/yaza run examples/pg_wire_query.yzBaca panduan API YAZA untuk route, request JSON, CRUD, autentikasi, PostgreSQL, dan batas yang masih dikembangkan.Read the YAZA API guide for routes, JSON requests, CRUD, authentication, PostgreSQL, and remaining development limits.