Skip to content

文法の概要

Thirdの文法は、Rustをベースに設計されています。Thirdは動的型付け言語であるため、Rustと比較して文法が簡略化されていたり、マクロなどの高度な言語機能については、実装されていなかったりします。

このページではThirdの基本的な文法について、コード例を用いて簡単に紹介します。具体的な仕様については、各項目のページを確認してください。

コメントアウト

third
// hello
// world
// hello
// world

変数

third
let a = 1;
{
    let a = 2;      // shadowing
    assert a == 2;
}
assert a == 1;
let a = 1;
{
    let a = 2;      // shadowing
    assert a == 2;
}
assert a == 1;

基本型

third
nil     // nil
true    // bool
3.14    // num
"hello" // str
nil     // nil
true    // bool
3.14    // num
"hello" // str

演算子

third
3 + 4   // 7
3 - 4   // -1
3 * 4   // 12
3 / 4   // 0.75
3 % 4   // 3

!true   // false
-(-4)   // 4

let a = 1;
a += 2;
a       // 3

true && false   // false
true || false   // true
3 + 4   // 7
3 - 4   // -1
3 * 4   // 12
3 / 4   // 0.75
3 % 4   // 3

!true   // false
-(-4)   // 4

let a = 1;
a += 2;
a       // 3

true && false   // false
true || false   // true

制御フロー

if式

third
let a = 1;
if a == 1 {
    print "one";
} else if a % 2 == 0 {
    print "even";
} else {
    print "odd";
}

// if-expression is an expression, so it can return a value.
let is_one = if a == 1 { "yes" } else { "no" };
assert is_one == "yes";
let a = 1;
if a == 1 {
    print "one";
} else if a % 2 == 0 {
    print "even";
} else {
    print "odd";
}

// if-expression is an expression, so it can return a value.
let is_one = if a == 1 { "yes" } else { "no" };
assert is_one == "yes";

while文

third
let a = 1;
while a < 60 {
    a += 1;
}
let a = 1;
while a < 60 {
    a += 1;
}

loop文

third
let a = 1;
loop {
    if a >= 10 { break; }
    a += 1;
}
assert a == 10;
let a = 1;
loop {
    if a >= 10 { break; }
    a += 1;
}
assert a == 10;

for文

third
0..10   // range (0 <= x < 10)
0..=10  // range (0 <= x <= 10)

for i in 0..10 {
    if a % 2 == 0 {
        continue;
    }
    print i; // 1, 3, .., 9
}
0..10   // range (0 <= x < 10)
0..=10  // range (0 <= x <= 10)

for i in 0..10 {
    if a % 2 == 0 {
        continue;
    }
    print i; // 1, 3, .., 9
}

関数

third
fn f(x) {
    if x == 1 { 1 }
    else if x % 2 == 0 { 
        return f(x / 2); 
    }
    else { f(3 * x + 1) }
}

for i in 1..=100 {
    assert f(x) == 1;
}
fn f(x) {
    if x == 1 { 1 }
    else if x % 2 == 0 { 
        return f(x / 2); 
    }
    else { f(3 * x + 1) }
}

for i in 1..=100 {
    assert f(x) == 1;
}

メソッド

third
let a = -1;
assert a.abs() == 1;
let a = -1;
assert a.abs() == 1;

クロージャー

third
let f = |x| x + 1;
assert f(1) == 2;
let f = |x| x + 1;
assert f(1) == 2;

配列 (TODO)

third
let arr = [1, 2, 3];
assert arr[1] == 2;

arr.push(4);
assert arr.len() == 4;

let a = arr.pop();
assert a == 4;
assert arr.len() = 3;

for a in arr {
    print a;
}
let arr = [1, 2, 3];
assert arr[1] == 2;

arr.push(4);
assert arr.len() == 4;

let a = arr.pop();
assert a == 4;
assert arr.len() = 3;

for a in arr {
    print a;
}

タプル (TODO)

third
let tup = (1, 2);
assert tup.0 == 1;
let tup = (1, 2);
assert tup.0 == 1;