Build a Lox Interpreter
What you will build
Turn source text into tokens, parse expressions and evaluate values. Add state, functions and classes as electives.
Before you start
For developers who can use recursive functions and distinguish text, numbers and Boolean values.
Programme directory
Starter projects
Learning path
Project labs
- Scan source and report errors
- Build a syntax tree
- Evaluate typed expressions
Elective extensions
Electives are available separately below and do not count towards this course’s core project.
- State and control flow
- Functions, closures and binding
- Classes and inheritance
Project brief
Scan source and report errors
Worked example and independent check
Scan var x = 12; and retain the lexeme, token type and literal value for each token. Add an unknown character on a second line; verify its line number and the final EOF token.
Implementation stages
- RY8 · In this stage, you'll implement basic support for the tokenize command which we'll use in all stages that are part of the Scanning chapter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
$ ./your_program.sh tokenize test.lox
EOF null
Full original stage (English) - OL4 · In this stage, you'll implement support for scanning parentheses.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
(()
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Full original stage (English) - OE8 · In this stage, you'll implement support for scanning braces.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
{{}}
$ ./your_program.sh tokenize test.lox
LEFT_BRACE { null
LEFT_BRACE { null
RIGHT_BRACE } null
RIGHT_BRACE } null
EOF null
Full original stage (English) - XC5 · In this stage, you'll implement support for scanning other single-character tokens.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
({*.,+*})
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_BRACE { null
STAR * null
DOT . null
COMMA , null
PLUS + null
STAR * null
RIGHT_BRACE } null
RIGHT_PAREN ) null
EOF null
Full original stage (English) - EA6 · In this stage, you'll implement support for scanning lexical errors.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
,.$(#
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: $
[line 1] Error: Unexpected character: #
COMMA , null
DOT . null
LEFT_PAREN ( null
EOF null
Full original stage (English) - MP7 · In this stage, you'll implement support for scanning the assignment & equality operators.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
={===}
$ ./your_program.sh tokenize test.lox
EQUAL = null
LEFT_BRACE { null
EQUAL_EQUAL == null
EQUAL = null
RIGHT_BRACE } null
EOF null
Full original stage (English) - BU3 · In this stage, you'll implement support for scanning negation & inequality operators.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
!!===
$ ./your_program.sh tokenize test.lox
BANG ! null
BANG_EQUAL != null
EQUAL_EQUAL == null
EOF null
Full original stage (English) - ET2 · In this stage, you'll implement support for scanning relational operators.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
<<=>>=
$ ./your_program.sh tokenize test.lox
LESS < null
LESS_EQUAL <= null
GREATER > null
GREATER_EQUAL >= null
EOF null
Full original stage (English) - ML2 · In this stage, you'll implement support for scanning the division operator & comments.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
()// Comment
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
/()
$ ./your_program.sh tokenize test.lox
SLASH / null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Full original stage (English) - ER2 · In this stage, you'll implement support for scanning whitespace characters.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
(<|TAB|>
<|SPACE|>)
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Full original stage (English) - TZ7 · In this stage, you'll implement support for scanning multi-line errors.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
#<|SPACE|>(
)<|TAB|>@
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: #
[line 2] Error: Unexpected character: @
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Full original stage (English) - UE7 · In this stage, you'll implement support for scanning string literals.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"foo baz"
$ ./your_program.sh tokenize test.lox
STRING "foo baz" foo baz
EOF null
"bar
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unterminated string.
EOF null
Full original stage (English) - KJ0 · In this stage, you'll implement support for scanning number literals.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
42
$ ./your_program.sh tokenize test.lox
NUMBER 42 42.0
EOF null
1234.1234
$ ./your_program.sh tokenize test.lox
NUMBER 1234.1234 1234.1234
EOF null
Full original stage (English) - EY7 · In this stage, you'll implement support for scanning identifiers.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
foo bar _hello
$ ./your_program.sh tokenize test.lox
IDENTIFIER foo null
IDENTIFIER bar null
IDENTIFIER _hello null
EOF null
Full original stage (English) - PQ5 · In this stage, you'll implement support for scanning reserved words.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
and
$ ./your_program.sh tokenize test.lox
AND and null
EOF null
Full original stage (English)
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Learning path
Build a syntax tree
Worked example and independent check
Draw the two trees for 2 + 3 * 4 and (2 + 3) * 4. Their root operators differ. Print both trees from your parser, then remove a closing parenthesis and inspect the reported location.
Implementation stages
- SC2 · In this stage, you'll implement support for parsing boolean values and the nil literal.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
true
$ ./your_program.sh parse test.lox
true
Full original stage (English) - RA8 · In this stage, you'll implement support for parsing number literals.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
42.47
$ ./your_program.sh parse test.lox
42.47
Full original stage (English) - TH5 · In this stage, you'll implement support for parsing string literals.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"hello"
$ ./your_program.sh parse test.lox
hello
Full original stage (English) - XE6 · In this stage, you'll implement support for parsing parentheses.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
("foo")
$ ./your_program.sh parse test.lox
(group foo)
Full original stage (English) - MQ1 · In this stage, you'll implement support for parsing unary operators ! and -.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
!true
$ ./your_program.sh parse test.lox
(! true)
Full original stage (English) - WA9 · In this stage, you'll implement support for parsing multiplicative algebraic operators * and /.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
16 * 38 / 58
$ ./your_program.sh parse test.lox
(/ (* 16.0 38.0) 58.0)
Full original stage (English) - YF2 · In this stage, you'll implement support for parsing additive algebraic operators + and -.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
52 + 80 - 94
$ ./your_program.sh parse test.lox
(- (+ 52.0 80.0) 94.0)
Full original stage (English) - UH4 · In this stage, you'll implement support for parsing comparison operators >, <, >= & <=.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
83 < 99 < 115
$ ./your_program.sh parse test.lox
(< (< 83.0 99.0) 115.0)
Full original stage (English) - HT8 · In this stage, you'll implement support for parsing equality operators == & !=.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"baz" == "baz"
$ ./your_program.sh parse test.lox
(== baz baz)
Full original stage (English) - WZ8 · In this stage, you'll implement support for handling syntax errors in expressions.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
(72 +)
$ ./your_program.sh parse test.lox
[line 1] Error at ')': Expect expression.
Full original stage (English)
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Learning path
Evaluate typed expressions
Worked example and independent check
The two trees produce 14 and 20. Add a string concatenation, then replace one string with a number. Compare a parsing error with a runtime type error and capture the output channel and exit code.
Implementation stages
- IZ6 · In this stage, you'll implement support for evaluating boolean values and the nil literal.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
true
$ ./your_program.sh evaluate test.lox
true
Full original stage (English) - LV1 · In this stage, you'll implement support for evaluating number and string literals.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"hello world!"
$ ./your_program.sh evaluate test.lox
hello world!
Full original stage (English) - OQ9 · In this stage, you'll implement support for evaluating expressions inside parentheses.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
("hello world!")
$ ./your_program.sh evaluate test.lox
hello world!
Full original stage (English) - DC1 · In this stage, you'll implement support for evaluating unary operators - and !.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
-(73)
$ ./your_program.sh evaluate test.lox
-73
Full original stage (English) - BP3 · In this stage, you'll implement support for evaluating binary operators * and /.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
(18 * 3 / (3 * 6))
$ ./your_program.sh evaluate test.lox
3
Full original stage (English) - JY2 · In this stage, you'll implement support for evaluating binary operators + and -.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
20 + 74 - (-(14 - 33))
$ ./your_program.sh evaluate test.lox
75
Full original stage (English) - JX8 · In this stage, you'll implement support for overloading the + operator. When the + operator is applied to two strings, it should concatenate them.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"hello" + " world!"
$ ./your_program.sh evaluate test.lox
hello world!
Full original stage (English) - ET4 · In this stage, you'll implement support for evaluating relational operators >, <, >= & <=.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
10 > 5
$ ./your_program.sh evaluate test.lox
true
Full original stage (English) - HW7 · In this stage, you'll implement support for evaluating equality operators == and !=.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
156 == (89 + 67)
$ ./your_program.sh evaluate test.lox
true
Full original stage (English) - GJ9 · In this stage, you'll implement support for handling runtime errors while evaluating the unary operator -.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
-"hello world!"
$ ./your_program.sh evaluate test.lox
Operand must be a number.
[line 1]
Full original stage (English) - YU6 · In this stage, you'll implement support for handling runtime errors while evaluating the binary operators * & /.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"foo" / 42
$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]
Full original stage (English) - CQ1 · In this stage, you'll implement support for handling runtime errors while evaluating the binary operators + & -.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
17 + "bar"
$ ./your_program.sh evaluate test.lox
Operands must be two numbers or two strings.
[line 1]
Full original stage (English) - IB5 · In this stage, you'll implement support for handling runtime errors while evaluating the relational operators >, <, >= & <=.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
17 > "bar"
$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]
Full original stage (English)
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Learning path
State and control flow
Worked example and independent check
Shadow an outer variable inside a block and print both values. Then implement a loop that sums 1, 2 and 3; the final result must be 6. Trace assignments to distinguish a scoping bug from a loop error.
Implementation stages
- XY1 · In this stage, you'll add support for generating output using the print statement.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print "Hello, World!";
$ ./your_program.sh run test.lox
Hello, World!
print;
Full original stage (English) - OE4 · In this stage, you'll add support for handling multiple statements in a single program.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print "Hello, World!";
print 42;
$ ./your_program.sh run test.lox
Hello, World!
42
print "world" + "baz" + "bar";
print 27 - 26;
print "bar" == "quz";
worldbazbar
1
false
print "hello"; print true;
print false;
print "bar"; print 43;
hello
true
false
bar
43
print 81;
print 81 + 46;
print 81 + 46 + 19;
81
127
146
print true != true;
print "36
10
78
";
print "There should be an empty line above this.";
false
36
10
78
There should be an empty line above this.
Full original stage (English) - FI3 · In this stage, you'll add support for handling expression statements.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
"foo" + "bar";
print "baz";
$ ./your_program.sh run test.lox
baz
(37 + 42 - 21) > (76 - 37) * 2;
print !false;
"baz" + "hello" + "quz" + "bar" == "bazhelloquzbar";
print !false;
true
true
27 - 60 >= -99 * 2 / 99 + 76;
true == true;
("world" == "bar") == ("baz" != "hello");
print true;
true
print "the expression below is invalid";
49 + "baz";
print "this should not be printed";
the expression below is invalid
Operands must be two numbers or two strings.
[line 2]
print "79" + "baz";
print false * (18 + 84);
79baz
Operands must be numbers.
[line 2]
Full original stage (English) - YG2 · In this stage, you'll add support for declaring variables using the var statement.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var a = "foo";
print a;
$ ./your_program.sh run test.lox
foo
var world = 10;
print world;
10
var bar = 99;
var foo = 99;
print bar + foo;
var quz = 99;
print bar + foo + quz;
198
297
var foo = (8 * (62 + 62)) / 4 + 62;
print foo;
310
var quz = 76;
var baz = quz;
print baz + quz;
152
Full original stage (English) - SV7 · In this stage, you'll add support for declaring variables using the var statement.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print a;
$ ./your_program.sh run test.lox
Undefined variable 'a'.
[line 1]
print 22;
print x;
22
Undefined variable 'x'.
[line 2]
var baz = 96;
print hello;
Undefined variable 'hello'.
[line 2]
var hello = 85;
var result = (hello + bar) / world;
print result;
Undefined variable 'bar'.
[line 2]
var quz = 20;
var world = 51;
var hello = 56;
print quz + world + he
Undefined variable 'he'.
[line 4]
Full original stage (English) - BC1 · In this stage, you'll add support for initializing variables.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var a;
print a;
$ ./your_program.sh run test.lox
nil
var foo;
print foo;
nil
var baz = "foo";
var bar;
print bar;
var baz = 69;
var world;
var quz;
print world;
var quz = 73 + 26 * 20;
print quz;
var hello = 26 * 20;
print quz + hello;
var foo;
print foo;
593
1113
nil
Full original stage (English) - DW9 · In this stage, you'll add support for redeclaring variables.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var a = 1;
var a = 2;
print a;
$ ./your_program.sh run test.lox
2
var baz = "before";
print baz;
var baz = "after";
print baz;
before
after
var hello = "after";
var hello = "before";
var hello = hello;
print hello;
before
var world = 2;
print world;
var world = 3;
print world;
var hello = 5;
print hello;
var world = hello;
print world;
2
3
5
5
var baz = bar;
Undefined variable 'bar'.
[line 1]
Full original stage (English) - PL3 · In this stage, you'll add support for the assignment operation (=).
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var a;
var b = 2;
var a = b = 1;
print a;
$ ./your_program.sh run test.lox
1
var quz;
quz = 1;
print quz;
print quz = 2;
print quz;
1
2
2
var hello = 93;
var bar = 93;
bar = hello;
hello = bar;
print hello + bar;
186
var quz;
var hello;
quz = hello = 16 + 34 * 92;
print quz;
print hello;
3144
3144
var hello = 65;
var baz;
var quz;
hello = baz = quz = hello * 2;
print hello;
print baz;
print baz;
130
130
130
Full original stage (English) - VR5 · In this stage, you'll add support for block syntax using curly braces {}.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
{
var foo = "before";
print foo;
}
{
var foo = "after";
print foo;
}
$ ./your_program.sh run test.lox
before
after
{
var hello = "baz";
print hello;
}
baz
{
var world = "before";
print world;
}
{
var world = "after";
print world;
}
before
after
{
var hello = 88;
{
var foo = 88;
print foo;
}
print hello;
}
88
88
{
var bar = 11;
var world = 11;
{
print bar + world;
}
[line 6] Error at end: Expect '}' .
Full original stage (English) - FB4 · In this stage, you'll add support for scopes in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
{
var world = "before";
{
var world = "after";
print world;
}
print world;
}
$ ./your_program.sh run test.lox
after
before
var baz = (91 * 16) - 61;
{
var world = "quz" + "89";
print world;
}
print baz;
quz89
1395
{
var quz = "before";
{
var quz = "after";
print quz;
}
print quz;
}
after
before
var bar = "global bar";
var world = "global world";
var hello = "global hello";
{
var bar = "outer bar";
var world = "outer world";
{
var bar = "inner bar";
print bar;
print world;
print hello;
}
print bar;
print world;
print hello;
}
print bar;
print world;
print hello;
inner bar
outer world
global hello
outer bar
outer world
global hello
global bar
global world
global hello
{
var hello = "outer hello";
{
var hello = "inner hello";
print hello;
}
print hello;
}
print hello;
inner hello
outer hello
Undefined variable 'hello'.
[line 9]
Full original stage (English) - NE3 · In this stage, you'll add support for the if statement in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
if (true) print "good";
$ ./your_program.sh run test.lox
good
if (true) print "bar";
bar
if (true) {
print "block body";
}
block body
var a = false;
if (a = true) {
print (a == true);
}
true
var stage = "unknown";
var age = 50;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
adult
eligible for voting: true
Full original stage (English) - ST5 · In this stage, you'll add support for the else statement in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
if (true) print "if branch"; else print "else branch";
$ ./your_program.sh run test.lox
if branch
if branch
var age = 21;
if (age > 18) print "adult"; else print "child";
adult
if (false) {
print "if block";
} else print "else statement";
if (false) print "if statement"; else {
print "else block";
}
else statement
else block
var celsius = 67;
var fahrenheit = 0;
var isHot = false;
{
fahrenheit = celsius * 9 / 5 + 32;
print celsius; print fahrenheit;
if (celsius > 30) {
isHot = true;
print "It's a hot day. Stay hydrated!";
} else {
print "It's cold today. Wear a jacket!";
}
if (isHot) { print "Remember to use sunscreen!"; }
}
67
152.6
It's a hot day. Stay hydrated!
Remember to use sunscreen!
Full original stage (English) - FH8 · In this stage, you'll add support for the else-if statement in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
if (false) print "if branch"; else if (false) print "else-if branch";
$ ./your_program.sh run test.lox
if (true) print "if branch"; else if (false) print "else-if branch";
if branch
if (true) {
print "hello";
} else if (true) print "hello";
if (true) print "hello"; else if (true) {
print "hello";
}
hello
hello
var age = 88;
var stage = "unknown";
if (age < 18) { stage = "child"; }
else if (age >= 18) { stage = "adult"; }
else if (age >= 65) { stage = "senior"; }
else if (age >= 100) { stage = "centenarian"; }
print stage;
adult
var age = 67;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
else { print "eligible for voting: false"; }
if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) { print "eligible for driving: learner's permit"; }
else { print "eligible for driving: full license"; }
if (age < 21) { print "eligible for drinking (US): false"; }
else { print "eligible for drinking (US): true"; }
eligible for voting: true
eligible for driving: full license
eligible for drinking (US): true
Full original stage (English) - XJ4 · In this stage, you'll add support for nested if statements in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
if (true) if (true) print "nested true";
$ ./your_program.sh run test.lox
nested true
nested true
if (true) {
if (false) print "quz"; else print "quz";
}
quz
var stage = "unknown";
var age = 29;
if (age < 18) {
if (age < 13) { stage = "child"; }
else if (age < 16) { stage = "young teenager"; }
else { stage = "teenager"; }
}
else if (age < 65) {
if (age < 30) { stage = "young adult"; }
else if (age < 50) { stage = "adult"; }
else { stage = "middle-aged adult"; }
}
else { stage = "senior"; }
print stage;
var isAdult = age >= 18;
if (isAdult) {
print "eligible for voting: true";
if (age < 25) {
print "first-time voter: likely";
}
else { print "first-time voter: unlikely"; }
}
else { print "eligible for voting: false"; }
if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) {
print "eligible for driving: learner's permit";
if (age < 17) { print "supervised driving required"; }
else { print "unsupervised driving allowed with restrictions"; }
}
else { print "eligible for driving: full license"; }
if (age < 21) { print "eligible for drinking (US): false"; }
else {
print "eligible for drinking (US): true";
if (age < 25) { print "remember: drink responsibly!"; }
}
young adult
eligible for voting: true
first-time voter: unlikely
eligible for driving: full license
eligible for drinking (US): true
if (true) if (false) print "world"; else print "baz";
baz
Full original stage (English) - WK8 · In this stage, you'll add support for the logical OR operator in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print nil or "ok";
$ ./your_program.sh run test.lox
ok
if (false or "ok") print "baz";
if (nil or "ok") print "baz";
if (false or false) print "world";
if (true or "world") print "world";
if (24 or "bar") print "bar";
if ("bar" or "bar") print "bar";
baz
baz
world
bar
bar
print 41 or true;
print false or 41;
print false or false or true;
print false or false;
print false or false or false;
print true or true or true or true;
41
41
true
false
false
true
var a = "hello";
var b = "hello";
(a = false) or (b = true) or (a = "hello");
print a;
print b;
false
true
var stage = "unknown";
var age = 23;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
adult
eligible for voting: true
Full original stage (English) - JX4 · In this stage, you'll add support for the logical AND operator in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print false and "ok";
$ ./your_program.sh run test.lox
false
if (false and "bad") print "foo";
if (nil and "bad") print "foo";
if (true and "hello") print "hello";
if (97 and "baz") print "baz";
if ("baz" and "baz") print "baz";
if ("" and "bar") print "bar";
hello
baz
baz
bar
print false and 1;
print true and 1;
print 23 and "hello" and false;
print 23 and true;
print 23 and "hello" and 23;
false
1
false
true
23
var a = "quz";
var b = "quz";
(a = true) and (b = false) and (a = "bad");
print a;
print b;
true
false
var stage = "unknown";
var age = 14;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
child
eligible for voting: false
Full original stage (English) - QY3 · In this stage, you'll add support for while statements in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var foo = 0;
while (foo < 3) print foo = foo + 1;
$ ./your_program.sh run test.lox
1
2
3
1
2
3
var quz = 0;
while (quz < 3) {
print quz;
quz = quz + 1;
}
0
1
2
while (false) {
print "should not print";
}
var product = 1;
var i = 1;
while (i <= 5) {
product = product * i;
i = i + 1;
}
print "Product of numbers 1 to 5: "; print product;
Product of numbers 1 to 5:
120
var n = 10;
var fm = 0;
var fn = 1;
var index = 0;
while (index < n) {
print fm;
var temp = fm;
fm = fn;
fn = temp + fn;
index = index + 1;
}
0
1
1
2
3
5
8
13
21
34
Full original stage (English) - BW6 · In this stage, you'll add support for for statements in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
for (var baz = 0; baz < 3;) print baz = baz + 1;
$ ./your_program.sh run test.lox
1
2
3
1
2
3
for (var world = 0; world < 3; world = world + 1) {
print world;
}
0
1
2
var world = 0;
for (; world < 2; world = world + 1) print world;
for (var foo = 0; foo < 2;) {
print foo;
foo = foo + 1;
}
0
1
0
1
var quz = "after";
{
var quz = "before";
for (var quz = 0; quz < 1; quz = quz + 1) {
print quz;
var quz = -1;
print quz;
}
}
{
for (var quz = 0; quz > 0; quz = quz + 1) {}
var quz = "after";
print quz;
for (quz = 0; quz < 1; quz = quz + 1) {
print quz;
}
}
0
-1
after
0
Full original stage (English) - VT1 · In this stage, you'll handle several syntactic errors in your interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
for (;;) var foo;
$ ./your_program.sh run test.lox
[line 1] Error at 'var': Expect expression.
if (true) "ok"; else var foo;
[line 1] Error at 'var': Expect expression.
for (var a = 1; {}; a = a + 1) {}
[line 2] Error at '{': Expect expression.
[line 2] Error at ')': Expect ';' after expression.
for (var a = 1; a < 2; {}) {}
[line 2] Error at '{': Expect expression.
for ({}; a < 2; a = a + 1) {}
Full original stage (English)
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Learning path
Functions, closures and binding
Worked example and independent check
Return a counter closure from a function, create two counters and call them independently. Then move a return outside a function and verify that the resolver reports the invalid context.
Implementation stages
- AV4 · In this stage, you'll add native functions to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print clock();
$ ./your_program.sh run test.lox
1731411035
print clock() + 75;
1731411035
print clock() / 1000;
1731410
var startTime = clock();
var timeoutSeconds = 2;
// Check if less than 2 seconds have elapsed
if ((clock() >= startTime) and (clock() <= (startTime + timeoutSeconds))) {
print "Operation in progress...";
} else {
print "Operation timed out!";
}
Operation in progress...
// Countdown from 3 seconds
var startTime = clock();
var totalDuration = 3; // 3 seconds countdown
var lastCheck = startTime;
var completed = false;
while (!completed) {
var currentTime = clock();
var elapsedTime = currentTime - startTime;
var remainingTime = totalDuration - elapsedTime;
// Update progress every second
if (currentTime >= lastCheck + 1) {
if (remainingTime >= 2) {
print "Plenty of time remaining: ";
print remainingTime;
} else if (remainingTime >= 1) {
print "Getting closer: ";
print remainingTime;
} else if (remainingTime > 0) {
print "Almost there: ";
print remainingTime;
}
lastCheck = currentTime;
}
// Check for completion
if (elapsedTime >= totalDuration) {
completed = true;
print "Countdown complete!";
} else if (elapsedTime < 0) {
// Handle clock overflow or system time changes
print "Time error detected!";
completed = true;
}
}
Plenty of time remaining:
2
Getting closer:
1
Countdown complete!
Full original stage (English) - PG8 · In this stage, you'll add support for user defined functions with no arguments to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
fun bar() { print 10; }
bar();
$ ./your_program.sh run test.lox
10
fun foo() {
print 7;
}
foo();
7
fun f() {}
f();
fun foo() {}
print foo;
<fn foo>
fun cumulative_sum() {
var n = 10; // Fixed value
var total = 0;
var i = 1;
while (i <= n) {
total = total + i;
i = i + 1;
}
print "The cumulative sum from 1 to 10 is: ";
print total;
}
cumulative_sum();
The cumulative sum from 1 to 10 is:
55
Full original stage (English) - LB6 · In this stage, you'll add support for user defined functions with arguments to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
fun foo(a) { print a; }
foo(10);
$ ./your_program.sh run test.lox
10
fun f1(a) {
print a;
}
f1(76);
76
fun f3(a, b, c) { print a + b + c; }
f3(24, 24, 24);
72
fun f8(a, b, c, d, e, f, g, h) { print a - b + c * d + e - f + g - h; }
f8(51, 51, 51, 51, 51, 51, 51, 51);
2601
fun calculateGrade(score, bonus) {
var finalScore = score + bonus;
if (finalScore >= 90) {
print "A";
} else if (finalScore >= 80) {
print "B";
} else if (finalScore >= 70) {
print "C";
} else if (finalScore >= 60) {
print "D";
} else {
print "F";
}
}
var score = 81;
var bonus = 3;
print "Grade for given score is: ";
calculateGrade(score, bonus);
Grade for given score is:
B
Full original stage (English) - PX4 · In this stage, you'll add support for detecting and handling syntax errors.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
clock(;
$ ./your_program.sh run test.lox
[line 2] Error at ';': Expect expression.
print clock(;
[line 1] Error at ';': Expect expression.
print clock)));
[line 1] Error at ')': Expect ';' after value.
fun f() 74;
print f();
[line 2] Error at '74': Expect '{' before function body.
fun foo(a, b c, d, e, f) {}
foo();
[line 2] Error at 'c': Expect ')' after parameters.
Full original stage (English) - RD2 · In this stage, you'll add support for return statements in functions to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
fun foo() { return 10; }
print foo();
$ ./your_program.sh run test.lox
10
fun fib(n) {
if (n < 2) return n;
return fib(n - 2) + fib(n - 1);
}
var start = clock();
print fib(10) == 55;
print (clock() - start) < 5; // 5 seconds
true
true
fun f() {
if (false) return "no"; else return "ok";
}
print f();
ok
fun f() {
while (!true) return "ok";
}
print f();
nil
fun f() {
return;
print "bad";
}
print f();
Full original stage (English) - EY3 · In this stage, you'll add support for higher order functions to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
fun makeGreeter() {
fun greet(name) {
print "Hello " + name;
}
return greet;
}
var sayHello = makeGreeter();
sayHello("Bob");
$ ./your_program.sh run test.lox
Hello Bob
Hello Bob
fun returnArg(arg) {
return arg;
}
fun returnFunCallWithArg(func, arg) {
return returnArg(func)(arg);
}
fun printArg(arg) {
print arg;
}
returnFunCallWithArg(printArg, "foo");
foo
fun square(x) {
return x * x;
}
// This higher-order function applies a
// function N times to a starting value x.
fun applyTimesN(N, f, x) {
var i = 0;
while (i < N) {
x = f(x);
i = i + 1;
}
return x;
}
// 6 is squared once
print applyTimesN(1, square, 6);
// 6 is squared twice
print applyTimesN(2, square, 6);
// 6 is squared thrice
print applyTimesN(3, square, 6);
36
1296
1679616
fun makeFilter() {
fun filter(n) {
if (n < 42) {
return false;
}
return true;
}
return filter;
}
// This function applies a function to a list of numbers
fun applyToNumbers(f, count) {
var n = 0;
while (n < count) {
if (f(n)) {
print n;
}
n = n + 1;
}
}
var greaterThanX = makeFilter();
print "Numbers >= 42:";
applyToNumbers(greaterThanX, 42 + 5);
Numbers >= 42:
42
43
44
45
46
Full original stage (English) - FJ7 · In this stage, you'll add handling for runtime errors in your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
85();
$ ./your_program.sh run test.lox
Can only call functions and classes.
[line 1]
"not a function"();
Can only call functions and classes.
[line 1]
fun f(a, b) {
print a;
print b;
}
f(1, 2, 3, 4);
Expected 2 arguments but got 4.
[line 6]
fun f(a, b) {}
f(1);
Expected 2 arguments but got 1.
[line 3]
false();
Full original stage (English) - BZ4 · In this stage, you'll add support for global and local scope to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var a = 38;
fun printAndModify() {
print a;
var a = 95;
print a;
}
print a;
a = 68;
printAndModify();
$ ./your_program.sh run test.lox
38
68
95
38
68
95
var count = 3;
fun tick() {
if (count > 0) {
print count;
count = count - 1;
return false;
}
print "Blast off!";
return true;
}
while (!tick()) {}
3
2
1
Blast off!
var counter = 89;
fun incrementCounter(amount) {
counter = counter + amount;
print counter;
}
{
counter = 83;
incrementCounter(6);
print counter;
}
print counter;
89
89
89
var x = 1;
var y = 2;
fun printBoth() {
if (x < y) {
print "x is less than y:";
print x;
print y;
} else {
print "x is not less than y:";
print x;
print y;
}
}
{
var x = 10;
{
var y = 20;
var i = 0;
while (i < 3) {
x = x + 1;
y = y - 1;
print "Local x: ";
print x;
print "Local y: ";
print y;
i = i + 1;
}
if (x > y) {
print "Local x > y";
}
printBoth();
}
}
Local x:
11
Local y:
19
Local x:
12
Local y:
18
Local x:
13
Local y:
17
x is less than y:
1
2
Full original stage (English) - GG6 · In this stage, you'll add support for closures to your lox interpreter.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter();
counter();
$ ./your_program.sh run test.lox
1
2
1
2
{
var threshold = 50;
fun isEven(n) {
if (n == 0) return true;
if (n > threshold) return false;
return isOdd(n - 1);
}
fun isOdd(n) {
if (n == 0) return false;
if (n > threshold) return false;
return isEven(n - 1);
}
print isEven(61);
}
false
fun makeLogger(prefix) {
var logCount = 0;
fun log(message) {
logCount = logCount + 1;
print prefix + ": " + message;
if (logCount > 6) {
print prefix + ": Too many log lines!";
logCount = 0;
}
}
return log;
}
var debugLog = makeLogger("debug");
var errorLog = makeLogger("error");
debugLog("Starting");
debugLog("Processing");
debugLog("Finishing");
debugLog("Extra line");
errorLog("Failed!");
errorLog("Retrying...");
debug: Starting
debug: Processing
debug: Finishing
debug: Extra line
error: Failed!
error: Retrying...
fun makeAccumulator(label) {
var sum = 0;
var count = 0;
fun accumulate(value) {
sum = sum + value;
count = count + 1;
print label;
print count;
print sum;
print sum;
if (count > 3) {
print "reset";
sum = 0;
count = 0;
}
return sum;
}
return accumulate;
}
var acc1 = makeAccumulator("First:");
var acc2 = makeAccumulator("Second:");
acc1(2);
acc1(6);
acc1(3);
acc1(4);
acc2(6);
acc2(4);
First:
1
2
2
First:
2
8
8
First:
3
11
11
First:
4
15
15
reset
Second:
1
6
6
Second:
2
10
10
Full original stage (English) - DE8 · In this stage, you'll add support for identifier resolution and binding at compile time.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var variable = "global";
{
fun f() {
print variable;
}
f();
var variable = "local";
f();
}
$ ./your_program.sh run test.lox
global
global
fun global() {
print "global";
}
{
fun f() {
global();
}
f();
fun global() {
print "local";
}
f();
}
global
global
var x = "global";
fun outer() {
var x = "outer";
fun middle() {
fun inner() {
print x;
}
inner();
var x = "middle";
inner();
}
middle();
}
outer();
outer
outer
var count = 0;
{
fun makeCounter() {
fun counter() {
count = count + 1;
print count;
}
return counter;
}
var counter1 = makeCounter();
counter1();
counter1();
var count = 0;
counter1();
}
1
2
3
Full original stage (English) - PT7 · In this stage, you'll add support for detecting invalid self-initialization of variables, ensuring variables can't reference themselves before they're fully defined.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
var a = "value";
var a = a; // This is allowed in global scope
print a; // Should print "value"
$ ./your_program.sh run test.lox
value
var a = "outer";
{
var a = a; // Error: Can't read local variable in its own initializer
}
[line 3] Error at 'a': Can't read local variable in its own initializer.
fun returnArg(arg) {
return arg;
}
var b = "global";
{
var a = "first";
var b = returnArg(b); // Error: Can't read local variable in its own initializer
print b;
}
var b = b + " updated";
print b;
[line 8] Error at 'b': Can't read local variable in its own initializer.
fun outer() {
var a = "outer";
fun inner() {
var a = a; // Error: Can't read local variable in its own initializer
print a;
}
inner();
}
outer();
[line 5] Error at 'a': Can't read local variable in its own initializer.
Full original stage (English) - PZ7 · In this stage, you'll add support for detecting invalid variable redeclarations, ensuring variables can't be declared multiple times in the same local scope.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
{
var a = "value";
var a = "other";
}
$ ./your_program.sh run test.lox
[line 3] Error at 'a': Already a variable with this name in this scope.
fun foo(a) {
var a;
}
[line 2] Error at 'a': Already a variable with this name in this scope.
fun foo(arg, arg) {
"body";
}
[line 1] Error at 'arg': Already a variable with this name in this scope.
var a = "1";
print a;
var a;
print a;
var a = "2";
print a;
{
var a = "1";
var a = "2";
print a;
}
[line 12] Error at 'a': Already a variable with this name in this scope.
Full original stage (English) - EH3 · In this stage, you'll add support for detecting invalid return statements, ensuring they only appear within function bodies.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
fun foo() {
return "at function scope is ok";
}
return;
$ ./your_program.sh run test.lox
[line 6] Error at 'return': Can't return from top-level code.
fun foo() {
if (true) {
return "early return";
}
for (var i = 0; i < 10; i = i + 1) {
return "loop return";
}
}
if (true) {
return "conditional return";
}
[line 12] Error at 'return': Can't return from top-level code.
{
return "not allowed in a block either";
}
fun allowed() {
if (true) {
return "this is fine";
}
return;
}
[line 3] Error at 'return': Can't return from top-level code.
fun outer() {
fun inner() {
return "ok";
}
return "also ok";
}
if (true) {
fun nested() {
return;
}
return "not ok";
}
[line 15] Error at 'return': Can't return from top-level code.
Full original stage (English)
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Learning path
Classes and inheritance
Worked example and independent check
Define a class with speak(), override it in a subclass and call super.speak() from the subclass. Record which implementation runs and check an invalid super outside a subclass.
Implementation stages
- VF4 · In this stage, you'll add support for class declarations, allowing users to define classes in their Lox programs.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Spaceship {}
print Spaceship;
$ ./your_program.sh run test.lox
Spaceship
// Multiple class declarations with empty body
class Robot {}
class Wizard {}
print Robot;
print Wizard;
print "Both classes successfully printed";
Robot
Wizard
Both classes successfully printed
{
// Class declaration inside blocks should work
class Dinosaur {}
print "Inside block: Dinosaur exists";
print Dinosaur;
}
print "Accessing out-of-scope class:";
print Dinosaur; // expect runtime error
Inside block: Dinosaur exists
Dinosaur
Accessing out-of-scope class:
Undefined variable 'Dinosaur'.
[line 8]
// Class declaration inside function should work
fun foo() {
class Superhero {}
print "Class declared inside function";
print Superhero;
}
foo();
print "Function called successfully";
Class declared inside function
Superhero
Function called successfully
Full original stage (English) - YK8 · In this stage, you'll add support for class instantiation, allowing users to create instances of classes in their Lox programs.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Spaceship {}
var falcon = Spaceship();
print falcon;
$ ./your_program.sh run test.lox
Spaceship instance
// Creating multiple instances of the same class
class Robot {}
var r1 = Robot();
var r2 = Robot();
print "Created multiple robots:";
print r1;
print r2;
Created multiple robots:
Robot instance
Robot instance
class Wizard {}
class Dragon {}
// Instantiating classes in a function should work
fun createCharacters() {
var merlin = Wizard();
var smaug = Dragon();
print "Characters created in fantasy world:";
print merlin;
print smaug;
return merlin;
}
var mainCharacter = createCharacters();
// An instance of a class should be truthy
if (mainCharacter) {
print "The main character is:";
print mainCharacter;
} else {
print "Failed to create a main character.";
}
Characters created in fantasy world:
Wizard instance
Dragon instance
The main character is:
Wizard instance
class Superhero {}
var count = 0;
while (count < 3) {
var hero = Superhero();
print "Hero created:";
print hero;
count = count + 1;
}
print "All heroes created!";
Hero created:
Superhero instance
Hero created:
Superhero instance
Hero created:
Superhero instance
All heroes created!
Full original stage (English) - YF3 · In this stage, you'll add support for getting and setting properties on class instances.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
// Basic property setting and getting
class Spaceship {}
var falcon = Spaceship();
falcon.name = "Millennium Falcon";
falcon.speed = 75.5;
print "Ship details:";
print falcon.name;
print falcon.speed;
$ ./your_program.sh run test.lox
Ship details:
Millennium Falcon
75.5
// Multiple properties and conditional access
class Robot {}
var r2d2 = Robot();
r2d2.model = "Astromech";
r2d2.operational = false;
if (r2d2.operational) {
print r2d2.model;
r2d2.mission = "Navigate hyperspace";
print r2d2.mission;
}
(No output because the condition is false)
// Multiple instances with properties
class Superhero {}
var batman = Superhero();
var superman = Superhero();
batman.name = "Batman";
batman.called = 18;
superman.name = "Superman";
superman.called = 66;
print "Times " + superman.name + " was called: ";
print superman.called;
print "Times " + batman.name + " was called: ";
print batman.called;
Times Superman was called:
66
Times Batman was called:
18
// Property manipulation in functions
class Wizard {}
var gandalf = Wizard();
gandalf.color = "Grey";
gandalf.power = nil;
print gandalf.color;
fun promote(wizard) {
wizard.color = "White";
if (true) {
wizard.power = 100;
} else {
wizard.power = 0;
}
}
promote(gandalf);
print gandalf.color;
print gandalf.power;
Grey
White
100
Full original stage (English) - QR2 · In this stage, you'll add support for instance methods, allowing classes to define behavior that operates on their instances.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Robot {
beep() {
print "Beep boop!";
}
}
var r2d2 = Robot();
r2d2.beep();
Robot().beep();
$ ./your_program.sh run test.lox
Beep boop!
Beep boop!
{
class Foo {
returnSelf() {
return Foo;
}
}
print Foo().returnSelf(); // expect: Foo
}
Foo
class Wizard {
castSpell(spell) {
print "Casting a magical spell: " + spell;
}
}
class Dragon {
breatheFire(fire, intensity) {
print "Breathing " + fire + " with intensity: "
+ intensity;
}
}
// Methods on different class instances
var merlin = Wizard();
var smaug = Dragon();
// Conditional method calling
if (true) {
var action = merlin.castSpell;
action("Fireball");
} else {
var action = smaug.breatheFire;
action("Fire", "100");
}
Casting a magical spell: Fireball
class Superhero {
useSpecialPower(hero) {
print "Using power: " + hero.specialPower;
}
hasSpecialPower(hero) {
return hero.specialPower;
}
giveSpecialPower(hero, power) {
hero.specialPower = power;
}
}
// Methods in functions
fun performHeroics(hero, superheroClass) {
if (superheroClass.hasSpecialPower(hero)) {
superheroClass.useSpecialPower(hero);
} else {
print "No special power available";
}
}
var superman = Superhero();
var heroClass = Superhero();
if (true) {
heroClass.giveSpecialPower(superman, "Flight");
} else {
heroClass.giveSpecialPower(superman, "Strength");
}
performHeroics(superman, heroClass);
Using power: Flight
Full original stage (English) - YD7 · In this stage, you'll add support for the this keyword, enabling methods to access and manipulate the instance they were called on.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Spaceship {
identify() {
print this;
}
}
Spaceship().identify();
$ ./your_program.sh run test.lox
Spaceship instance
class Calculator {
add(a, b) {
return a + b + this.memory;
}
}
var calc = Calculator();
calc.memory = 82;
print calc.add(92, 1);
175
class Animal {
makeSound() {
print this.sound;
}
identify() {
print this.species;
}
}
var dog = Animal();
dog.sound = "Woof";
dog.species = "Dog";
var cat = Animal();
cat.sound = "Meow";
cat.species = "Cat";
// Swap methods between instances
cat.makeSound = dog.makeSound;
dog.identify = cat.identify;
cat.makeSound();
dog.identify();
Woof
Cat
class Wizard {
getSpellCaster() {
fun castSpell() {
print this;
print "Casting spell as " + this.name;
}
return castSpell;
}
}
var wizard = Wizard();
wizard.name = "Merlin";
wizard.getSpellCaster()();
Wizard instance
Casting spell as Merlin
Full original stage (English) - DG2 · In this stage, you'll add validation for the this keyword, ensuring it's only used in appropriate contexts and providing clear error messages when it's not.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
print this;
$ ./your_program.sh run test.lox
[line 1] Error at 'this': Can't use 'this' outside of a class.
fun notAMethod() {
print this;
}
[line 2] Error at 'this': Can't use 'this' outside of a class.
class Person {
sayName() {
print this();
}
}
Person().sayName();
Can only call functions and classes.
[line 3]
class Confused {
method() {
fun inner(instance) {
var feeling = "confused";
print this.feeling;
}
return inner;
}
}
var instance = Confused();
var m = instance.method();
m(instance);
Undefined property 'feeling'.
[line 5]
Full original stage (English) - OU5 · In this stage, you'll add support for constructors, allowing classes to initialize their instances with custom logic when they're created.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Default {
init() {
this.x = "bar";
this.y = 91;
}
}
print Default().x;
print Default().y;
$ ./your_program.sh run test.lox
bar
91
class Robot {
init(model, function) {
this.model = model;
this.function = function;
}
}
print Robot("R2-D2", "Astromech").model;
R2-D2
class Counter {
init(startValue) {
if (startValue < 0) {
print "startValue can't be negative";
this.count = 0;
} else {
this.count = startValue;
}
}
}
var instance = Counter(-52);
print instance.count;
print instance.init(52).count;
startValue can't be negative
0
52
class Vehicle {
init(type) {
this.type = type;
}
}
class Car {
init(make, model) {
this.make = make;
this.model = model;
this.wheels = "four";
}
describe() {
print this.make + " " + this.model +
" with " + this.wheels + " wheels";
}
}
var vehicle = Vehicle("Generic");
print "Generic " + vehicle.type;
var myCar = Car("Toyota", "Corolla");
myCar.describe();
Generic Generic
Toyota Corolla with four wheels
Full original stage (English) - EB9 · In this stage, you'll handle return statements within constructors, ensuring they follow Lox's special rules for initializers.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Person {
init() {
print "world";
return;
}
}
Person();
$ ./your_program.sh run test.lox
world
class ThingDefault {
init() {
this.x = "foo";
this.y = 42;
return this;
}
}
var out = ThingDefault();
print out;
[line 5] Error at 'return': Can't return a value from an initializer.
class Foo {
init() {
return "something else";
}
}
Foo();
[line 3] Error at 'return': Can't return a value from an initializer.
class Foo {
init() {
return this.callback();
}
callback() {
return "callback";
}
}
Foo();
Full original stage (English) - MF6 · In this stage, you'll add support for class inheritance, allowing users to create class hierarchies in their Lox programs.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Doughnut {}
class BostonCream < Doughnut {}
print Doughnut();
print BostonCream();
$ ./your_program.sh run test.lox
Doughnut instance
BostonCream instance
{
class A {}
// B is a subclass of A
class B < A {}
// C is also a subclass of A
class C < A {}
print A();
print B();
print C();
}
A instance
B instance
C instance
class Vehicle {}
// Car is a subclass of Vehicle
class Car < Vehicle {}
// Sedan is a subclass of Car
class Sedan < Car {}
print Vehicle();
print Car();
print Sedan();
{
// Truck is a subclass of Vehicle
class Truck < Vehicle {}
print Truck();
}
Vehicle instance
Car instance
Sedan instance
Truck instance
Full original stage (English) - KY1 · In this stage, you'll add support for method inheritance, allowing subclasses to use methods defined in their parent classes.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Doughnut {
cook() {
print "Fry until golden brown.";
}
}
// BostonCream is a subclass of Doughnut
class BostonCream < Doughnut {}
// BostonCream class should inherit the cook
// method from Doughnut class
BostonCream().cook();
$ ./your_program.sh run test.lox
Fry until golden brown.
class Root {
getName() {
print "Root class";
}
}
class Parent < Root {
parentMethod() {
print "Method defined in Parent";
}
}
class Child < Parent {
childMethod() {
print "Method defined in Child";
}
}
var root = Root();
var parent = Parent();
var child = Child();
// Root methods are available to all
root.getName();
parent.getName();
child.getName();
// Parent methods are available to Parent and Child
parent.parentMethod();
child.parentMethod();
// Child methods are only available to Child
child.childMethod();
Root class
Root class
Root class
Method defined in Parent
Method defined in Parent
Method defined in Child
Full original stage (English) - KA5 · In this stage, you'll add support for method overriding, allowing subclasses to provide their own implementations of inherited methods.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class A {
method() {
print "A method";
}
}
// B inherits method `method` from A
// and overrides it with a new implementation
class B < A {
method() {
print "B method";
}
}
var b = B();
b.method(); // expect: B method
$ ./your_program.sh run test.lox
B method
class Base {
init(a) {
this.a = a;
}
}
// Constructors can also be overridden
class Derived < Base {
init(a, b) {
this.a = a;
this.b = b;
}
}
var derived = Derived(89, 32);
print derived.a;
print derived.b;
89
32
class Animal {
speak() {
return "Animal speaks";
}
makeSound() {
return "Generic sound";
}
communicate() {
return this.speak() + " : " + this.makeSound();
}
}
class Dog < Animal {
speak() {
return "Dog speaks";
}
makeSound() {
return "Woof";
}
}
class Puppy < Dog {
speak() {
return "Puppy speaks";
}
}
var animal = Animal();
var dog = Dog();
var puppy = Puppy();
print animal.communicate();
print dog.communicate();
print puppy.communicate();
Animal speaks : Generic sound
Dog speaks : Woof
Puppy speaks : Woof
Full original stage (English) - AB0 · In this stage, you'll add validation for class inheritance, ensuring that class hierarchies are valid and providing clear error messages when they're not.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
// A class can't inherit from itself.
class Foo < Foo {} // expect compile error
$ ./your_program.sh run test.lox
[line 2] Error at 'Foo': A class can't inherit from itself.
fun A() {}
// A class can only inherit from a class.
class B < A {} // expect runtime error
print A();
print B();
Superclass must be a class.
[line 4]
var A = "class";
// A class can only inherit from a class
class B < A {} // expect runtime error
print B();
Full original stage (English) - QI0 · In this stage, you'll add support for the super keyword, allowing methods to call overridden methods from their parent class.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Doughnut {
cook() {
print "Fry until golden brown.";
}
}
// Super can be used to call the overridden method
// of the parent class
class BostonCream < Doughnut {
cook() {
super.cook();
}
}
BostonCream().cook();
$ ./your_program.sh run test.lox
Fry until golden brown.
class Base {
method() {
print "Base.method()";
}
}
class Parent < Base {
method() {
super.method();
}
}
class Child < Parent {
method() {
super.method();
}
}
var parent = Parent();
parent.method();
var child = Child();
child.method();
Base.method()
Base.method()
Full original stage (English) - IB9 · In this stage, you'll add validation for the super keyword, ensuring it's only used in appropriate contexts and providing clear error messages when it's not.
Code and test examples
Compare these source examples with your implementation. Commands and reference output are shown in their original notation.
class Foo {
cook() {
// Foo is not a subclass
super.cook(); // expect compile error
}
}
$ ./your_program.sh run test.lox
[line 4] Error at 'super': Can't use 'super' in a class with no superclass.
// super can't be used outside of a class
super.notEvenInAClass(); // expect compile error
[line 2] Error at 'super': Can't use 'super' outside of a class.
class A {}
class B < A {
method() {
// super must be followed by `.`
// and an expression
super; // expect compile error
}
}
[line 7] Error at ';': Expect '.' after 'super'.
Full original stage (English)
SynQ discussion
Show SynQ the input, your prediction and what actually happened. Ask which intermediate value to inspect first.
Learning path
Project brief
Project brief
Show token output, a syntax tree and the value for (2 + 3) * 4. Add a comparison, a lexical error, an unclosed parenthesis and a mixed-type arithmetic operation.
Acceptance criteria
The expression evaluates to 20 and 2 + 3 * 4 to 14. Attribute the three failures to the correct phase. Preserve an example of the diagnostic from each phase.
Explain your result
Why does the parser accept some expressions that the evaluator cannot run?
Project rubric
There are four checks, worth one point each. The project is complete when all four are evidenced. Save the source, run commands and observations together.
- Runs from a clean project with the documented command.
- Matches the expected reference result below.
- A second input and one boundary case have recorded expected and actual results.
- Explains the design decision below using a trace, intermediate value or measured observation.
Check your understanding
What value does 2 + 3 * 4 produce in Lox?
- 14
- 20
- 24
Reveal the answer
14. Multiplication binds more tightly than addition; the root of the expression tree is addition.
Sources and licences
Course adaptation and teaching notes by Digital Qazaqstan. Original project material by CodeCrafters.
interpreter
MIT License
Copyright (c) 2022 CodeCrafters
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Свой интерпретатор Lox
Что вы создадите
Преобразуйте программу в токены, разберите выражения и вычислите значения. Состояние, функции и классы доступны как расширения.
Перед началом
Для разработчиков, знакомых с рекурсией, строками, числами и логическими значениями.
Каталог программы
Стартовые проекты
Учебный маршрут
Практические модули
- Лексемы и ошибки сканера
- Дерево разбора выражений
- Вычисление выражений
Дополнительные модули
Дополнительные модули доступны отдельно внизу. Для базового проекта достаточно обязательных уроков.
- Состояние и управление
- Функции, замыкания и связывание
- Классы и наследование
Итоговое задание
Лексемы и ошибки сканера
Разбор примера и самостоятельная проверка
Разберите var x = 12; и сохраните лексему, тип и значение каждого токена. Добавьте неизвестный символ во вторую строку, проверьте номер ошибки и завершающий EOF.
Этапы реализации
- RY8 · В пустом файле выдайте только завершающий токен EOF.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
$ ./your_program.sh tokenize test.lox
EOF null
Исходное описание этапа (английский) - OL4 · Распознайте левую и правую круглую скобку как разные токены.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
(()
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Исходное описание этапа (английский) - OE8 · Распознайте обе фигурные скобки.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
{{}}
$ ./your_program.sh tokenize test.lox
LEFT_BRACE { null
LEFT_BRACE { null
RIGHT_BRACE } null
RIGHT_BRACE } null
EOF null
Исходное описание этапа (английский) - XC5 · Сопоставьте односимвольные знаки с их типами токенов.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
({*.,+*})
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_BRACE { null
STAR * null
DOT . null
COMMA , null
PLUS + null
STAR * null
RIGHT_BRACE } null
RIGHT_PAREN ) null
EOF null
Исходное описание этапа (английский) - EA6 · Сообщите о неизвестном символе с номером строки и продолжите сканирование.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
,.$(#
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: $
[line 1] Error: Unexpected character: #
COMMA , null
DOT . null
LEFT_PAREN ( null
EOF null
Исходное описание этапа (английский) - MP7 · Различайте присваивание = и равенство ==.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
={===}
$ ./your_program.sh tokenize test.lox
EQUAL = null
LEFT_BRACE { null
EQUAL_EQUAL == null
EQUAL = null
RIGHT_BRACE } null
EOF null
Исходное описание этапа (английский) - BU3 · Различайте ! и != по следующему символу.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
!!===
$ ./your_program.sh tokenize test.lox
BANG ! null
BANG_EQUAL != null
EQUAL_EQUAL == null
EOF null
Исходное описание этапа (английский) - ET2 · Распознайте четыре оператора сравнения, включая <= и >=.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
<<=>>=
$ ./your_program.sh tokenize test.lox
LESS < null
LESS_EQUAL <= null
GREATER > null
GREATER_EQUAL >= null
EOF null
Исходное описание этапа (английский) - ML2 · Различайте / и комментарий // до конца строки.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
()// Comment
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
/()
$ ./your_program.sh tokenize test.lox
SLASH / null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Исходное описание этапа (английский) - ER2 · Пропустите пробельные символы и обновите номер строки.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
(<|TAB|>
<|SPACE|>)
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Исходное описание этапа (английский) - TZ7 · Привяжите ошибки разных строк к их собственным номерам.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
#<|SPACE|>(
)<|TAB|>@
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: #
[line 2] Error: Unexpected character: @
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Исходное описание этапа (английский) - UE7 · Для строки сохраните лексему и значение без кавычек. Проверьте незакрытую строку.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"foo baz"
$ ./your_program.sh tokenize test.lox
STRING "foo baz" foo baz
EOF null
"bar
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unterminated string.
EOF null
Исходное описание этапа (английский) - KJ0 · Распознайте целые и дробные лексемы и выведите числовой литерал.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
42
$ ./your_program.sh tokenize test.lox
NUMBER 42 42.0
EOF null
1234.1234
$ ./your_program.sh tokenize test.lox
NUMBER 1234.1234 1234.1234
EOF null
Исходное описание этапа (английский) - EY7 · Сканируйте имя целиком, учитывая допустимые начальные и последующие знаки.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
foo bar _hello
$ ./your_program.sh tokenize test.lox
IDENTIFIER foo null
IDENTIFIER bar null
IDENTIFIER _hello null
EOF null
Исходное описание этапа (английский) - PQ5 · Отличите зарезервированные слова от обычных имён.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
and
$ ./your_program.sh tokenize test.lox
AND and null
EOF null
Исходное описание этапа (английский)
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Учебный маршрут
Дерево разбора выражений
Разбор примера и самостоятельная проверка
Нарисуйте деревья для 2 + 3 * 4 и (2 + 3) * 4. В корнях будут разные операторы. Выведите оба дерева из программы, уберите одну закрывающую скобку и проверьте место ошибки.
Этапы реализации
- SC2 · Создайте узлы дерева для true, false и nil.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
true
$ ./your_program.sh parse test.lox
true
Исходное описание этапа (английский) - RA8 · Превратите числовой токен в узел литерала с его значением.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
42.47
$ ./your_program.sh parse test.lox
42.47
Исходное описание этапа (английский) - TH5 · Постройте узел строкового литерала.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"hello"
$ ./your_program.sh parse test.lox
hello
Исходное описание этапа (английский) - XE6 · Разберите вложенное выражение в скобках как группировку.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
("foo")
$ ./your_program.sh parse test.lox
(group foo)
Исходное описание этапа (английский) - MQ1 · Разберите префиксные ! и минус, включая цепочку операторов.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
!true
$ ./your_program.sh parse test.lox
(! true)
Исходное описание этапа (английский) - WA9 · Свяжите умножение и деление с их операндами на уровне factor.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
16 * 38 / 58
$ ./your_program.sh parse test.lox
(/ (* 16.0 38.0) 58.0)
Исходное описание этапа (английский) - YF2 · Обработайте сложение и вычитание с более низким приоритетом.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
52 + 80 - 94
$ ./your_program.sh parse test.lox
(- (+ 52.0 80.0) 94.0)
Исходное описание этапа (английский) - UH4 · Разберите отношения после арифметики.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
83 < 99 < 115
$ ./your_program.sh parse test.lox
(< (< 83.0 99.0) 115.0)
Исходное описание этапа (английский) - HT8 · Разберите == и != с правильным приоритетом.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"baz" == "baz"
$ ./your_program.sh parse test.lox
(== baz baz)
Исходное описание этапа (английский) - WZ8 · Сообщите о пропущенном операнде или закрывающей скобке.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
(72 +)
$ ./your_program.sh parse test.lox
[line 1] Error at ')': Expect expression.
Исходное описание этапа (английский)
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Учебный маршрут
Вычисление выражений
Разбор примера и самостоятельная проверка
Два дерева дают 14 и 20. Добавьте конкатенацию строк, затем замените одну строку числом. Сравните ошибку разбора с ошибкой типов во время исполнения, зафиксируйте поток вывода и код завершения.
Этапы реализации
- IZ6 · Вычислите литералы true, false и nil.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
true
$ ./your_program.sh evaluate test.lox
true
Исходное описание этапа (английский) - LV1 · Верните значения строк и чисел в формате Lox.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"hello world!"
$ ./your_program.sh evaluate test.lox
hello world!
Исходное описание этапа (английский) - OQ9 · Вычислите внутреннее выражение узла группировки.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
("hello world!")
$ ./your_program.sh evaluate test.lox
hello world!
Исходное описание этапа (английский) - DC1 · Вычислите числовое отрицание и логическое ! по правилам истинности Lox.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
-(73)
$ ./your_program.sh evaluate test.lox
-73
Исходное описание этапа (английский) - BP3 · Вычислите произведение и частное.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
(18 * 3 / (3 * 6))
$ ./your_program.sh evaluate test.lox
3
Исходное описание этапа (английский) - JY2 · Вычислите сумму и разность чисел.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
20 + 74 - (-(14 - 33))
$ ./your_program.sh evaluate test.lox
75
Исходное описание этапа (английский) - JX8 · Для + соедините две строки по порядку.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"hello" + " world!"
$ ./your_program.sh evaluate test.lox
hello world!
Исходное описание этапа (английский) - ET4 · Сравните числовые значения операторами отношений.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
10 > 5
$ ./your_program.sh evaluate test.lox
true
Исходное описание этапа (английский) - HW7 · Реализуйте равенство по типу и значению, включая nil.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
156 == (89 + 67)
$ ./your_program.sh evaluate test.lox
true
Исходное описание этапа (английский) - GJ9 · Для унарного минуса с нечисловым значением верните ошибку времени исполнения.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
-"hello world!"
$ ./your_program.sh evaluate test.lox
Operand must be a number.
[line 1]
Исходное описание этапа (английский) - YU6 · Проверьте типы пары операндов при числовой операции.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"foo" / 42
$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]
Исходное описание этапа (английский) - CQ1 · Отклоните недопустимую комбинацию строки и числа при +.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
17 + "bar"
$ ./your_program.sh evaluate test.lox
Operands must be two numbers or two strings.
[line 1]
Исходное описание этапа (английский) - IB5 · Сообщите об ошибке типа при сравнении, требующем двух чисел.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
17 > "bar"
$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]
Исходное описание этапа (английский)
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Учебный маршрут
Состояние и управление
Разбор примера и самостоятельная проверка
Перекройте внешнюю переменную внутри блока, выведите оба значения. Просуммируйте циклом 1, 2 и 3 до результата 6. По записи присваиваний отличите ошибку области видимости от ошибки цикла.
Этапы реализации
- XY1 · Исполните print и выведите значение выражения.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print "Hello, World!";
$ ./your_program.sh run test.lox
Hello, World!
print;
Исходное описание этапа (английский) - OE4 · Исполните несколько print в порядке программы.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print "Hello, World!";
print 42;
$ ./your_program.sh run test.lox
Hello, World!
42
print "world" + "baz" + "bar";
print 27 - 26;
print "bar" == "quz";
worldbazbar
1
false
print "hello"; print true;
print false;
print "bar"; print 43;
hello
true
false
bar
43
print 81;
print 81 + 46;
print 81 + 46 + 19;
81
127
146
print true != true;
print "36
10
78
";
print "There should be an empty line above this.";
false
36
10
78
There should be an empty line above this.
Исходное описание этапа (английский) - FI3 · Разберите самостоятельное выражение с точкой с запятой.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
"foo" + "bar";
print "baz";
$ ./your_program.sh run test.lox
baz
(37 + 42 - 21) > (76 - 37) * 2;
print !false;
"baz" + "hello" + "quz" + "bar" == "bazhelloquzbar";
print !false;
true
true
27 - 60 >= -99 * 2 / 99 + 76;
true == true;
("world" == "bar") == ("baz" != "hello");
print true;
true
print "the expression below is invalid";
49 + "baz";
print "this should not be printed";
the expression below is invalid
Operands must be two numbers or two strings.
[line 2]
print "79" + "baz";
print false * (18 + 84);
79baz
Operands must be numbers.
[line 2]
Исходное описание этапа (английский) - YG2 · Добавьте объявление var и чтение имени из окружения.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var a = "foo";
print a;
$ ./your_program.sh run test.lox
foo
var world = 10;
print world;
10
var bar = 99;
var foo = 99;
print bar + foo;
var quz = 99;
print bar + foo + quz;
198
297
var foo = (8 * (62 + 62)) / 4 + 62;
print foo;
310
var quz = 76;
var baz = quz;
print baz + quz;
152
Исходное описание этапа (английский) - SV7 · При чтении необъявленного имени сообщите об ошибке.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print a;
$ ./your_program.sh run test.lox
Undefined variable 'a'.
[line 1]
print 22;
print x;
22
Undefined variable 'x'.
[line 2]
var baz = 96;
print hello;
Undefined variable 'hello'.
[line 2]
var hello = 85;
var result = (hello + bar) / world;
print result;
Undefined variable 'bar'.
[line 2]
var quz = 20;
var world = 51;
var hello = 56;
print quz + world + he
Undefined variable 'he'.
[line 4]
Исходное описание этапа (английский) - BC1 · Вычислите и сохраните начальное значение переменной.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var a;
print a;
$ ./your_program.sh run test.lox
nil
var foo;
print foo;
nil
var baz = "foo";
var bar;
print bar;
var baz = 69;
var world;
var quz;
print world;
var quz = 73 + 26 * 20;
print quz;
var hello = 26 * 20;
print quz + hello;
var foo;
print foo;
593
1113
nil
Исходное описание этапа (английский) - DW9 · Примените правила повторного объявления переменной.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var a = 1;
var a = 2;
print a;
$ ./your_program.sh run test.lox
2
var baz = "before";
print baz;
var baz = "after";
print baz;
before
after
var hello = "after";
var hello = "before";
var hello = hello;
print hello;
before
var world = 2;
print world;
var world = 3;
print world;
var hello = 5;
print hello;
var world = hello;
print world;
2
3
5
5
var baz = bar;
Undefined variable 'bar'.
[line 1]
Исходное описание этапа (английский) - PL3 · Запишите результат выражения в уже объявленную переменную.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var a;
var b = 2;
var a = b = 1;
print a;
$ ./your_program.sh run test.lox
1
var quz;
quz = 1;
print quz;
print quz = 2;
print quz;
1
2
2
var hello = 93;
var bar = 93;
bar = hello;
hello = bar;
print hello + bar;
186
var quz;
var hello;
quz = hello = 16 + 34 * 92;
print quz;
print hello;
3144
3144
var hello = 65;
var baz;
var quz;
hello = baz = quz = hello * 2;
print hello;
print baz;
print baz;
130
130
130
Исходное описание этапа (английский) - VR5 · Исполните последовательность инструкций в фигурных скобках.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
{
var foo = "before";
print foo;
}
{
var foo = "after";
print foo;
}
$ ./your_program.sh run test.lox
before
after
{
var hello = "baz";
print hello;
}
baz
{
var world = "before";
print world;
}
{
var world = "after";
print world;
}
before
after
{
var hello = 88;
{
var foo = 88;
print foo;
}
print hello;
}
88
88
{
var bar = 11;
var world = 11;
{
print bar + world;
}
[line 6] Error at end: Expect '}' .
Исходное описание этапа (английский) - FB4 · Разрешайте имена из вложенной области через внешнюю цепочку окружений.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
{
var world = "before";
{
var world = "after";
print world;
}
print world;
}
$ ./your_program.sh run test.lox
after
before
var baz = (91 * 16) - 61;
{
var world = "quz" + "89";
print world;
}
print baz;
quz89
1395
{
var quz = "before";
{
var quz = "after";
print quz;
}
print quz;
}
after
before
var bar = "global bar";
var world = "global world";
var hello = "global hello";
{
var bar = "outer bar";
var world = "outer world";
{
var bar = "inner bar";
print bar;
print world;
print hello;
}
print bar;
print world;
print hello;
}
print bar;
print world;
print hello;
inner bar
outer world
global hello
outer bar
outer world
global hello
global bar
global world
global hello
{
var hello = "outer hello";
{
var hello = "inner hello";
print hello;
}
print hello;
}
print hello;
inner hello
outer hello
Undefined variable 'hello'.
[line 9]
Исходное описание этапа (английский) - NE3 · Выполните тело if при истинном условии.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
if (true) print "good";
$ ./your_program.sh run test.lox
good
if (true) print "bar";
bar
if (true) {
print "block body";
}
block body
var a = false;
if (a = true) {
print (a == true);
}
true
var stage = "unknown";
var age = 50;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
adult
eligible for voting: true
Исходное описание этапа (английский) - ST5 · Выберите ветвь else при ложном условии.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
if (true) print "if branch"; else print "else branch";
$ ./your_program.sh run test.lox
if branch
if branch
var age = 21;
if (age > 18) print "adult"; else print "child";
adult
if (false) {
print "if block";
} else print "else statement";
if (false) print "if statement"; else {
print "else block";
}
else statement
else block
var celsius = 67;
var fahrenheit = 0;
var isHot = false;
{
fahrenheit = celsius * 9 / 5 + 32;
print celsius; print fahrenheit;
if (celsius > 30) {
isHot = true;
print "It's a hot day. Stay hydrated!";
} else {
print "It's cold today. Wear a jacket!";
}
if (isHot) { print "Remember to use sunscreen!"; }
}
67
152.6
It's a hot day. Stay hydrated!
Remember to use sunscreen!
Исходное описание этапа (английский) - FH8 · Обработайте цепочку else if.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
if (false) print "if branch"; else if (false) print "else-if branch";
$ ./your_program.sh run test.lox
if (true) print "if branch"; else if (false) print "else-if branch";
if branch
if (true) {
print "hello";
} else if (true) print "hello";
if (true) print "hello"; else if (true) {
print "hello";
}
hello
hello
var age = 88;
var stage = "unknown";
if (age < 18) { stage = "child"; }
else if (age >= 18) { stage = "adult"; }
else if (age >= 65) { stage = "senior"; }
else if (age >= 100) { stage = "centenarian"; }
print stage;
adult
var age = 67;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
else { print "eligible for voting: false"; }
if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) { print "eligible for driving: learner's permit"; }
else { print "eligible for driving: full license"; }
if (age < 21) { print "eligible for drinking (US): false"; }
else { print "eligible for drinking (US): true"; }
eligible for voting: true
eligible for driving: full license
eligible for drinking (US): true
Исходное описание этапа (английский) - XJ4 · Сопоставьте else с нужным вложенным if.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
if (true) if (true) print "nested true";
$ ./your_program.sh run test.lox
nested true
nested true
if (true) {
if (false) print "quz"; else print "quz";
}
quz
var stage = "unknown";
var age = 29;
if (age < 18) {
if (age < 13) { stage = "child"; }
else if (age < 16) { stage = "young teenager"; }
else { stage = "teenager"; }
}
else if (age < 65) {
if (age < 30) { stage = "young adult"; }
else if (age < 50) { stage = "adult"; }
else { stage = "middle-aged adult"; }
}
else { stage = "senior"; }
print stage;
var isAdult = age >= 18;
if (isAdult) {
print "eligible for voting: true";
if (age < 25) {
print "first-time voter: likely";
}
else { print "first-time voter: unlikely"; }
}
else { print "eligible for voting: false"; }
if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) {
print "eligible for driving: learner's permit";
if (age < 17) { print "supervised driving required"; }
else { print "unsupervised driving allowed with restrictions"; }
}
else { print "eligible for driving: full license"; }
if (age < 21) { print "eligible for drinking (US): false"; }
else {
print "eligible for drinking (US): true";
if (age < 25) { print "remember: drink responsibly!"; }
}
young adult
eligible for voting: true
first-time voter: unlikely
eligible for driving: full license
eligible for drinking (US): true
if (true) if (false) print "world"; else print "baz";
baz
Исходное описание этапа (английский) - WK8 · Реализуйте короткое замыкание or.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print nil or "ok";
$ ./your_program.sh run test.lox
ok
if (false or "ok") print "baz";
if (nil or "ok") print "baz";
if (false or false) print "world";
if (true or "world") print "world";
if (24 or "bar") print "bar";
if ("bar" or "bar") print "bar";
baz
baz
world
bar
bar
print 41 or true;
print false or 41;
print false or false or true;
print false or false;
print false or false or false;
print true or true or true or true;
41
41
true
false
false
true
var a = "hello";
var b = "hello";
(a = false) or (b = true) or (a = "hello");
print a;
print b;
false
true
var stage = "unknown";
var age = 23;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
adult
eligible for voting: true
Исходное описание этапа (английский) - JX4 · Реализуйте короткое замыкание and.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print false and "ok";
$ ./your_program.sh run test.lox
false
if (false and "bad") print "foo";
if (nil and "bad") print "foo";
if (true and "hello") print "hello";
if (97 and "baz") print "baz";
if ("baz" and "baz") print "baz";
if ("" and "bar") print "bar";
hello
baz
baz
bar
print false and 1;
print true and 1;
print 23 and "hello" and false;
print 23 and true;
print 23 and "hello" and 23;
false
1
false
true
23
var a = "quz";
var b = "quz";
(a = true) and (b = false) and (a = "bad");
print a;
print b;
true
false
var stage = "unknown";
var age = 14;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
child
eligible for voting: false
Исходное описание этапа (английский) - QY3 · Повторяйте тело while с новой проверкой условия.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var foo = 0;
while (foo < 3) print foo = foo + 1;
$ ./your_program.sh run test.lox
1
2
3
1
2
3
var quz = 0;
while (quz < 3) {
print quz;
quz = quz + 1;
}
0
1
2
while (false) {
print "should not print";
}
var product = 1;
var i = 1;
while (i <= 5) {
product = product * i;
i = i + 1;
}
print "Product of numbers 1 to 5: "; print product;
Product of numbers 1 to 5:
120
var n = 10;
var fm = 0;
var fn = 1;
var index = 0;
while (index < n) {
print fm;
var temp = fm;
fm = fn;
fn = temp + fn;
index = index + 1;
}
0
1
1
2
3
5
8
13
21
34
Исходное описание этапа (английский) - BW6 · Учтите инициализацию, условие и шаг for.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
for (var baz = 0; baz < 3;) print baz = baz + 1;
$ ./your_program.sh run test.lox
1
2
3
1
2
3
for (var world = 0; world < 3; world = world + 1) {
print world;
}
0
1
2
var world = 0;
for (; world < 2; world = world + 1) print world;
for (var foo = 0; foo < 2;) {
print foo;
foo = foo + 1;
}
0
1
0
1
var quz = "after";
{
var quz = "before";
for (var quz = 0; quz < 1; quz = quz + 1) {
print quz;
var quz = -1;
print quz;
}
}
{
for (var quz = 0; quz > 0; quz = quz + 1) {}
var quz = "after";
print quz;
for (quz = 0; quz < 1; quz = quz + 1) {
print quz;
}
}
0
-1
after
0
Исходное описание этапа (английский) - VT1 · Покажите синтаксическую ошибку в неверной конструкции управления.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
for (;;) var foo;
$ ./your_program.sh run test.lox
[line 1] Error at 'var': Expect expression.
if (true) "ok"; else var foo;
[line 1] Error at 'var': Expect expression.
for (var a = 1; {}; a = a + 1) {}
[line 2] Error at '{': Expect expression.
[line 2] Error at ')': Expect ';' after expression.
for (var a = 1; a < 2; {}) {}
[line 2] Error at '{': Expect expression.
for ({}; a < 2; a = a + 1) {}
Исходное описание этапа (английский)
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Учебный маршрут
Функции, замыкания и связывание
Разбор примера и самостоятельная проверка
Верните из функции замыкание-счётчик, создайте два счётчика и вызовите их независимо. Переместите return за пределы функции и проверьте диагностику контекста.
Этапы реализации
- AV4 · Зарегистрируйте встроенную функцию времени в учебном окружении.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print clock();
$ ./your_program.sh run test.lox
1731411035
print clock() + 75;
1731411035
print clock() / 1000;
1731410
var startTime = clock();
var timeoutSeconds = 2;
// Check if less than 2 seconds have elapsed
if ((clock() >= startTime) and (clock() <= (startTime + timeoutSeconds))) {
print "Operation in progress...";
} else {
print "Operation timed out!";
}
Operation in progress...
// Countdown from 3 seconds
var startTime = clock();
var totalDuration = 3; // 3 seconds countdown
var lastCheck = startTime;
var completed = false;
while (!completed) {
var currentTime = clock();
var elapsedTime = currentTime - startTime;
var remainingTime = totalDuration - elapsedTime;
// Update progress every second
if (currentTime >= lastCheck + 1) {
if (remainingTime >= 2) {
print "Plenty of time remaining: ";
print remainingTime;
} else if (remainingTime >= 1) {
print "Getting closer: ";
print remainingTime;
} else if (remainingTime > 0) {
print "Almost there: ";
print remainingTime;
}
lastCheck = currentTime;
}
// Check for completion
if (elapsedTime >= totalDuration) {
completed = true;
print "Countdown complete!";
} else if (elapsedTime < 0) {
// Handle clock overflow or system time changes
print "Time error detected!";
completed = true;
}
}
Plenty of time remaining:
2
Getting closer:
1
Countdown complete!
Исходное описание этапа (английский) - PG8 · Определите и вызовите функцию без аргументов.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
fun bar() { print 10; }
bar();
$ ./your_program.sh run test.lox
10
fun foo() {
print 7;
}
foo();
7
fun f() {}
f();
fun foo() {}
print foo;
<fn foo>
fun cumulative_sum() {
var n = 10; // Fixed value
var total = 0;
var i = 1;
while (i <= n) {
total = total + i;
i = i + 1;
}
print "The cumulative sum from 1 to 10 is: ";
print total;
}
cumulative_sum();
The cumulative sum from 1 to 10 is:
55
Исходное описание этапа (английский) - LB6 · Свяжите переданные аргументы с параметрами функции.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
fun foo(a) { print a; }
foo(10);
$ ./your_program.sh run test.lox
10
fun f1(a) {
print a;
}
f1(76);
76
fun f3(a, b, c) { print a + b + c; }
f3(24, 24, 24);
72
fun f8(a, b, c, d, e, f, g, h) { print a - b + c * d + e - f + g - h; }
f8(51, 51, 51, 51, 51, 51, 51, 51);
2601
fun calculateGrade(score, bonus) {
var finalScore = score + bonus;
if (finalScore >= 90) {
print "A";
} else if (finalScore >= 80) {
print "B";
} else if (finalScore >= 70) {
print "C";
} else if (finalScore >= 60) {
print "D";
} else {
print "F";
}
}
var score = 81;
var bonus = 3;
print "Grade for given score is: ";
calculateGrade(score, bonus);
Grade for given score is:
B
Исходное описание этапа (английский) - PX4 · Обнаружьте ошибку объявления или вызова функции при разборе.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
clock(;
$ ./your_program.sh run test.lox
[line 2] Error at ';': Expect expression.
print clock(;
[line 1] Error at ';': Expect expression.
print clock)));
[line 1] Error at ')': Expect ';' after value.
fun f() 74;
print f();
[line 2] Error at '74': Expect '{' before function body.
fun foo(a, b c, d, e, f) {}
foo();
[line 2] Error at 'c': Expect ')' after parameters.
Исходное описание этапа (английский) - RD2 · Верните значение через return и прекратите выполнение тела.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
fun foo() { return 10; }
print foo();
$ ./your_program.sh run test.lox
10
fun fib(n) {
if (n < 2) return n;
return fib(n - 2) + fib(n - 1);
}
var start = clock();
print fib(10) == 55;
print (clock() - start) < 5; // 5 seconds
true
true
fun f() {
if (false) return "no"; else return "ok";
}
print f();
ok
fun f() {
while (!true) return "ok";
}
print f();
nil
fun f() {
return;
print "bad";
}
print f();
Исходное описание этапа (английский) - EY3 · Передайте функцию как значение другой функции.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
fun makeGreeter() {
fun greet(name) {
print "Hello " + name;
}
return greet;
}
var sayHello = makeGreeter();
sayHello("Bob");
$ ./your_program.sh run test.lox
Hello Bob
Hello Bob
fun returnArg(arg) {
return arg;
}
fun returnFunCallWithArg(func, arg) {
return returnArg(func)(arg);
}
fun printArg(arg) {
print arg;
}
returnFunCallWithArg(printArg, "foo");
foo
fun square(x) {
return x * x;
}
// This higher-order function applies a
// function N times to a starting value x.
fun applyTimesN(N, f, x) {
var i = 0;
while (i < N) {
x = f(x);
i = i + 1;
}
return x;
}
// 6 is squared once
print applyTimesN(1, square, 6);
// 6 is squared twice
print applyTimesN(2, square, 6);
// 6 is squared thrice
print applyTimesN(3, square, 6);
36
1296
1679616
fun makeFilter() {
fun filter(n) {
if (n < 42) {
return false;
}
return true;
}
return filter;
}
// This function applies a function to a list of numbers
fun applyToNumbers(f, count) {
var n = 0;
while (n < count) {
if (f(n)) {
print n;
}
n = n + 1;
}
}
var greaterThanX = makeFilter();
print "Numbers >= 42:";
applyToNumbers(greaterThanX, 42 + 5);
Numbers >= 42:
42
43
44
45
46
Исходное описание этапа (английский) - FJ7 · Обработайте вызов неподходящего значения или неверное число аргументов.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
85();
$ ./your_program.sh run test.lox
Can only call functions and classes.
[line 1]
"not a function"();
Can only call functions and classes.
[line 1]
fun f(a, b) {
print a;
print b;
}
f(1, 2, 3, 4);
Expected 2 arguments but got 4.
[line 6]
fun f(a, b) {}
f(1);
Expected 2 arguments but got 1.
[line 3]
false();
Исходное описание этапа (английский) - BZ4 · Создайте отдельное окружение каждого вызова.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var a = 38;
fun printAndModify() {
print a;
var a = 95;
print a;
}
print a;
a = 68;
printAndModify();
$ ./your_program.sh run test.lox
38
68
95
38
68
95
var count = 3;
fun tick() {
if (count > 0) {
print count;
count = count - 1;
return false;
}
print "Blast off!";
return true;
}
while (!tick()) {}
3
2
1
Blast off!
var counter = 89;
fun incrementCounter(amount) {
counter = counter + amount;
print counter;
}
{
counter = 83;
incrementCounter(6);
print counter;
}
print counter;
89
89
89
var x = 1;
var y = 2;
fun printBoth() {
if (x < y) {
print "x is less than y:";
print x;
print y;
} else {
print "x is not less than y:";
print x;
print y;
}
}
{
var x = 10;
{
var y = 20;
var i = 0;
while (i < 3) {
x = x + 1;
y = y - 1;
print "Local x: ";
print x;
print "Local y: ";
print y;
i = i + 1;
}
if (x > y) {
print "Local x > y";
}
printBoth();
}
}
Local x:
11
Local y:
19
Local x:
12
Local y:
18
Local x:
13
Local y:
17
x is less than y:
1
2
Исходное описание этапа (английский) - GG6 · Сохраните захваченную переменную после выхода из внешней функции.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter();
counter();
$ ./your_program.sh run test.lox
1
2
1
2
{
var threshold = 50;
fun isEven(n) {
if (n == 0) return true;
if (n > threshold) return false;
return isOdd(n - 1);
}
fun isOdd(n) {
if (n == 0) return false;
if (n > threshold) return false;
return isEven(n - 1);
}
print isEven(61);
}
false
fun makeLogger(prefix) {
var logCount = 0;
fun log(message) {
logCount = logCount + 1;
print prefix + ": " + message;
if (logCount > 6) {
print prefix + ": Too many log lines!";
logCount = 0;
}
}
return log;
}
var debugLog = makeLogger("debug");
var errorLog = makeLogger("error");
debugLog("Starting");
debugLog("Processing");
debugLog("Finishing");
debugLog("Extra line");
errorLog("Failed!");
errorLog("Retrying...");
debug: Starting
debug: Processing
debug: Finishing
debug: Extra line
error: Failed!
error: Retrying...
fun makeAccumulator(label) {
var sum = 0;
var count = 0;
fun accumulate(value) {
sum = sum + value;
count = count + 1;
print label;
print count;
print sum;
print sum;
if (count > 3) {
print "reset";
sum = 0;
count = 0;
}
return sum;
}
return accumulate;
}
var acc1 = makeAccumulator("First:");
var acc2 = makeAccumulator("Second:");
acc1(2);
acc1(6);
acc1(3);
acc1(4);
acc2(6);
acc2(4);
First:
1
2
2
First:
2
8
8
First:
3
11
11
First:
4
15
15
reset
Second:
1
6
6
Second:
2
10
10
Исходное описание этапа (английский) - DE8 · Свяжите обращение к имени с его лексическим объявлением.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var variable = "global";
{
fun f() {
print variable;
}
f();
var variable = "local";
f();
}
$ ./your_program.sh run test.lox
global
global
fun global() {
print "global";
}
{
fun f() {
global();
}
f();
fun global() {
print "local";
}
f();
}
global
global
var x = "global";
fun outer() {
var x = "outer";
fun middle() {
fun inner() {
print x;
}
inner();
var x = "middle";
inner();
}
middle();
}
outer();
outer
outer
var count = 0;
{
fun makeCounter() {
fun counter() {
count = count + 1;
print count;
}
return counter;
}
var counter1 = makeCounter();
counter1();
counter1();
var count = 0;
counter1();
}
1
2
3
Исходное описание этапа (английский) - PT7 · Выявите чтение локальной переменной в её собственном инициализаторе.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
var a = "value";
var a = a; // This is allowed in global scope
print a; // Should print "value"
$ ./your_program.sh run test.lox
value
var a = "outer";
{
var a = a; // Error: Can't read local variable in its own initializer
}
[line 3] Error at 'a': Can't read local variable in its own initializer.
fun returnArg(arg) {
return arg;
}
var b = "global";
{
var a = "first";
var b = returnArg(b); // Error: Can't read local variable in its own initializer
print b;
}
var b = b + " updated";
print b;
[line 8] Error at 'b': Can't read local variable in its own initializer.
fun outer() {
var a = "outer";
fun inner() {
var a = a; // Error: Can't read local variable in its own initializer
print a;
}
inner();
}
outer();
[line 5] Error at 'a': Can't read local variable in its own initializer.
Исходное описание этапа (английский) - PZ7 · Выявите повторное объявление локальной переменной в одной области.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
{
var a = "value";
var a = "other";
}
$ ./your_program.sh run test.lox
[line 3] Error at 'a': Already a variable with this name in this scope.
fun foo(a) {
var a;
}
[line 2] Error at 'a': Already a variable with this name in this scope.
fun foo(arg, arg) {
"body";
}
[line 1] Error at 'arg': Already a variable with this name in this scope.
var a = "1";
print a;
var a;
print a;
var a = "2";
print a;
{
var a = "1";
var a = "2";
print a;
}
[line 12] Error at 'a': Already a variable with this name in this scope.
Исходное описание этапа (английский) - EH3 · Выявите return вне тела функции.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
fun foo() {
return "at function scope is ok";
}
return;
$ ./your_program.sh run test.lox
[line 6] Error at 'return': Can't return from top-level code.
fun foo() {
if (true) {
return "early return";
}
for (var i = 0; i < 10; i = i + 1) {
return "loop return";
}
}
if (true) {
return "conditional return";
}
[line 12] Error at 'return': Can't return from top-level code.
{
return "not allowed in a block either";
}
fun allowed() {
if (true) {
return "this is fine";
}
return;
}
[line 3] Error at 'return': Can't return from top-level code.
fun outer() {
fun inner() {
return "ok";
}
return "also ok";
}
if (true) {
fun nested() {
return;
}
return "not ok";
}
[line 15] Error at 'return': Can't return from top-level code.
Исходное описание этапа (английский)
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Учебный маршрут
Классы и наследование
Разбор примера и самостоятельная проверка
Определите speak() в классе, переопределите его в подклассе и вызовите super.speak(). Зафиксируйте выбранную реализацию и ошибку при обращении к super вне подкласса.
Этапы реализации
- VF4 · Объявите класс и привяжите его к имени.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Spaceship {}
print Spaceship;
$ ./your_program.sh run test.lox
Spaceship
// Multiple class declarations with empty body
class Robot {}
class Wizard {}
print Robot;
print Wizard;
print "Both classes successfully printed";
Robot
Wizard
Both classes successfully printed
{
// Class declaration inside blocks should work
class Dinosaur {}
print "Inside block: Dinosaur exists";
print Dinosaur;
}
print "Accessing out-of-scope class:";
print Dinosaur; // expect runtime error
Inside block: Dinosaur exists
Dinosaur
Accessing out-of-scope class:
Undefined variable 'Dinosaur'.
[line 8]
// Class declaration inside function should work
fun foo() {
class Superhero {}
print "Class declared inside function";
print Superhero;
}
foo();
print "Function called successfully";
Class declared inside function
Superhero
Function called successfully
Исходное описание этапа (английский) - YK8 · Создайте экземпляр класса при его вызове.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Spaceship {}
var falcon = Spaceship();
print falcon;
$ ./your_program.sh run test.lox
Spaceship instance
// Creating multiple instances of the same class
class Robot {}
var r1 = Robot();
var r2 = Robot();
print "Created multiple robots:";
print r1;
print r2;
Created multiple robots:
Robot instance
Robot instance
class Wizard {}
class Dragon {}
// Instantiating classes in a function should work
fun createCharacters() {
var merlin = Wizard();
var smaug = Dragon();
print "Characters created in fantasy world:";
print merlin;
print smaug;
return merlin;
}
var mainCharacter = createCharacters();
// An instance of a class should be truthy
if (mainCharacter) {
print "The main character is:";
print mainCharacter;
} else {
print "Failed to create a main character.";
}
Characters created in fantasy world:
Wizard instance
Dragon instance
The main character is:
Wizard instance
class Superhero {}
var count = 0;
while (count < 3) {
var hero = Superhero();
print "Hero created:";
print hero;
count = count + 1;
}
print "All heroes created!";
Hero created:
Superhero instance
Hero created:
Superhero instance
Hero created:
Superhero instance
All heroes created!
Исходное описание этапа (английский) - YF3 · Реализуйте чтение и запись полей экземпляра через точку.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
// Basic property setting and getting
class Spaceship {}
var falcon = Spaceship();
falcon.name = "Millennium Falcon";
falcon.speed = 75.5;
print "Ship details:";
print falcon.name;
print falcon.speed;
$ ./your_program.sh run test.lox
Ship details:
Millennium Falcon
75.5
// Multiple properties and conditional access
class Robot {}
var r2d2 = Robot();
r2d2.model = "Astromech";
r2d2.operational = false;
if (r2d2.operational) {
print r2d2.model;
r2d2.mission = "Navigate hyperspace";
print r2d2.mission;
}
(No output because the condition is false)
// Multiple instances with properties
class Superhero {}
var batman = Superhero();
var superman = Superhero();
batman.name = "Batman";
batman.called = 18;
superman.name = "Superman";
superman.called = 66;
print "Times " + superman.name + " was called: ";
print superman.called;
print "Times " + batman.name + " was called: ";
print batman.called;
Times Superman was called:
66
Times Batman was called:
18
// Property manipulation in functions
class Wizard {}
var gandalf = Wizard();
gandalf.color = "Grey";
gandalf.power = nil;
print gandalf.color;
fun promote(wizard) {
wizard.color = "White";
if (true) {
wizard.power = 100;
} else {
wizard.power = 0;
}
}
promote(gandalf);
print gandalf.color;
print gandalf.power;
Grey
White
100
Исходное описание этапа (английский) - QR2 · Найдите метод класса и вызовите его для экземпляра.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Robot {
beep() {
print "Beep boop!";
}
}
var r2d2 = Robot();
r2d2.beep();
Robot().beep();
$ ./your_program.sh run test.lox
Beep boop!
Beep boop!
{
class Foo {
returnSelf() {
return Foo;
}
}
print Foo().returnSelf(); // expect: Foo
}
Foo
class Wizard {
castSpell(spell) {
print "Casting a magical spell: " + spell;
}
}
class Dragon {
breatheFire(fire, intensity) {
print "Breathing " + fire + " with intensity: "
+ intensity;
}
}
// Methods on different class instances
var merlin = Wizard();
var smaug = Dragon();
// Conditional method calling
if (true) {
var action = merlin.castSpell;
action("Fireball");
} else {
var action = smaug.breatheFire;
action("Fire", "100");
}
Casting a magical spell: Fireball
class Superhero {
useSpecialPower(hero) {
print "Using power: " + hero.specialPower;
}
hasSpecialPower(hero) {
return hero.specialPower;
}
giveSpecialPower(hero, power) {
hero.specialPower = power;
}
}
// Methods in functions
fun performHeroics(hero, superheroClass) {
if (superheroClass.hasSpecialPower(hero)) {
superheroClass.useSpecialPower(hero);
} else {
print "No special power available";
}
}
var superman = Superhero();
var heroClass = Superhero();
if (true) {
heroClass.giveSpecialPower(superman, "Flight");
} else {
heroClass.giveSpecialPower(superman, "Strength");
}
performHeroics(superman, heroClass);
Using power: Flight
Исходное описание этапа (английский) - YD7 · Свяжите this с получателем вызова метода.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Spaceship {
identify() {
print this;
}
}
Spaceship().identify();
$ ./your_program.sh run test.lox
Spaceship instance
class Calculator {
add(a, b) {
return a + b + this.memory;
}
}
var calc = Calculator();
calc.memory = 82;
print calc.add(92, 1);
175
class Animal {
makeSound() {
print this.sound;
}
identify() {
print this.species;
}
}
var dog = Animal();
dog.sound = "Woof";
dog.species = "Dog";
var cat = Animal();
cat.sound = "Meow";
cat.species = "Cat";
// Swap methods between instances
cat.makeSound = dog.makeSound;
dog.identify = cat.identify;
cat.makeSound();
dog.identify();
Woof
Cat
class Wizard {
getSpellCaster() {
fun castSpell() {
print this;
print "Casting spell as " + this.name;
}
return castSpell;
}
}
var wizard = Wizard();
wizard.name = "Merlin";
wizard.getSpellCaster()();
Wizard instance
Casting spell as Merlin
Исходное описание этапа (английский) - DG2 · Выявите this за пределами допустимого контекста.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
print this;
$ ./your_program.sh run test.lox
[line 1] Error at 'this': Can't use 'this' outside of a class.
fun notAMethod() {
print this;
}
[line 2] Error at 'this': Can't use 'this' outside of a class.
class Person {
sayName() {
print this();
}
}
Person().sayName();
Can only call functions and classes.
[line 3]
class Confused {
method() {
fun inner(instance) {
var feeling = "confused";
print this.feeling;
}
return inner;
}
}
var instance = Confused();
var m = instance.method();
m(instance);
Undefined property 'feeling'.
[line 5]
Исходное описание этапа (английский) - OU5 · Автоматически вызывайте init при создании экземпляра.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Default {
init() {
this.x = "bar";
this.y = 91;
}
}
print Default().x;
print Default().y;
$ ./your_program.sh run test.lox
bar
91
class Robot {
init(model, function) {
this.model = model;
this.function = function;
}
}
print Robot("R2-D2", "Astromech").model;
R2-D2
class Counter {
init(startValue) {
if (startValue < 0) {
print "startValue can't be negative";
this.count = 0;
} else {
this.count = startValue;
}
}
}
var instance = Counter(-52);
print instance.count;
print instance.init(52).count;
startValue can't be negative
0
52
class Vehicle {
init(type) {
this.type = type;
}
}
class Car {
init(make, model) {
this.make = make;
this.model = model;
this.wheels = "four";
}
describe() {
print this.make + " " + this.model +
" with " + this.wheels + " wheels";
}
}
var vehicle = Vehicle("Generic");
print "Generic " + vehicle.type;
var myCar = Car("Toyota", "Corolla");
myCar.describe();
Generic Generic
Toyota Corolla with four wheels
Исходное описание этапа (английский) - EB9 · Примените ограничения return внутри конструктора.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Person {
init() {
print "world";
return;
}
}
Person();
$ ./your_program.sh run test.lox
world
class ThingDefault {
init() {
this.x = "foo";
this.y = 42;
return this;
}
}
var out = ThingDefault();
print out;
[line 5] Error at 'return': Can't return a value from an initializer.
class Foo {
init() {
return "something else";
}
}
Foo();
[line 3] Error at 'return': Can't return a value from an initializer.
class Foo {
init() {
return this.callback();
}
callback() {
return "callback";
}
}
Foo();
Исходное описание этапа (английский) - MF6 · Свяжите подкласс с объявленным базовым классом.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Doughnut {}
class BostonCream < Doughnut {}
print Doughnut();
print BostonCream();
$ ./your_program.sh run test.lox
Doughnut instance
BostonCream instance
{
class A {}
// B is a subclass of A
class B < A {}
// C is also a subclass of A
class C < A {}
print A();
print B();
print C();
}
A instance
B instance
C instance
class Vehicle {}
// Car is a subclass of Vehicle
class Car < Vehicle {}
// Sedan is a subclass of Car
class Sedan < Car {}
print Vehicle();
print Car();
print Sedan();
{
// Truck is a subclass of Vehicle
class Truck < Vehicle {}
print Truck();
}
Vehicle instance
Car instance
Sedan instance
Truck instance
Исходное описание этапа (английский) - KY1 · Ищите унаследованный метод по цепочке классов.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Doughnut {
cook() {
print "Fry until golden brown.";
}
}
// BostonCream is a subclass of Doughnut
class BostonCream < Doughnut {}
// BostonCream class should inherit the cook
// method from Doughnut class
BostonCream().cook();
$ ./your_program.sh run test.lox
Fry until golden brown.
class Root {
getName() {
print "Root class";
}
}
class Parent < Root {
parentMethod() {
print "Method defined in Parent";
}
}
class Child < Parent {
childMethod() {
print "Method defined in Child";
}
}
var root = Root();
var parent = Parent();
var child = Child();
// Root methods are available to all
root.getName();
parent.getName();
child.getName();
// Parent methods are available to Parent and Child
parent.parentMethod();
child.parentMethod();
// Child methods are only available to Child
child.childMethod();
Root class
Root class
Root class
Method defined in Parent
Method defined in Parent
Method defined in Child
Исходное описание этапа (английский) - KA5 · Учитывайте переопределение метода подклассом.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class A {
method() {
print "A method";
}
}
// B inherits method `method` from A
// and overrides it with a new implementation
class B < A {
method() {
print "B method";
}
}
var b = B();
b.method(); // expect: B method
$ ./your_program.sh run test.lox
B method
class Base {
init(a) {
this.a = a;
}
}
// Constructors can also be overridden
class Derived < Base {
init(a, b) {
this.a = a;
this.b = b;
}
}
var derived = Derived(89, 32);
print derived.a;
print derived.b;
89
32
class Animal {
speak() {
return "Animal speaks";
}
makeSound() {
return "Generic sound";
}
communicate() {
return this.speak() + " : " + this.makeSound();
}
}
class Dog < Animal {
speak() {
return "Dog speaks";
}
makeSound() {
return "Woof";
}
}
class Puppy < Dog {
speak() {
return "Puppy speaks";
}
}
var animal = Animal();
var dog = Dog();
var puppy = Puppy();
print animal.communicate();
print dog.communicate();
print puppy.communicate();
Animal speaks : Generic sound
Dog speaks : Woof
Puppy speaks : Woof
Исходное описание этапа (английский) - AB0 · Выявите ошибочный базовый класс или наследование класса от самого себя.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
// A class can't inherit from itself.
class Foo < Foo {} // expect compile error
$ ./your_program.sh run test.lox
[line 2] Error at 'Foo': A class can't inherit from itself.
fun A() {}
// A class can only inherit from a class.
class B < A {} // expect runtime error
print A();
print B();
Superclass must be a class.
[line 4]
var A = "class";
// A class can only inherit from a class
class B < A {} // expect runtime error
print B();
Исходное описание этапа (английский) - QI0 · Найдите метод базового класса через super с правильным получателем.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Doughnut {
cook() {
print "Fry until golden brown.";
}
}
// Super can be used to call the overridden method
// of the parent class
class BostonCream < Doughnut {
cook() {
super.cook();
}
}
BostonCream().cook();
$ ./your_program.sh run test.lox
Fry until golden brown.
class Base {
method() {
print "Base.method()";
}
}
class Parent < Base {
method() {
super.method();
}
}
class Child < Parent {
method() {
super.method();
}
}
var parent = Parent();
parent.method();
var child = Child();
child.method();
Base.method()
Base.method()
Исходное описание этапа (английский) - IB9 · Отклоните super вне подкласса и в других недопустимых контекстах.
Примеры кода и проверок
Сверьте свою реализацию с примерами. Команды и эталонные результаты приведены в исходной записи.
class Foo {
cook() {
// Foo is not a subclass
super.cook(); // expect compile error
}
}
$ ./your_program.sh run test.lox
[line 4] Error at 'super': Can't use 'super' in a class with no superclass.
// super can't be used outside of a class
super.notEvenInAClass(); // expect compile error
[line 2] Error at 'super': Can't use 'super' outside of a class.
class A {}
class B < A {
method() {
// super must be followed by `.`
// and an expression
super; // expect compile error
}
}
[line 7] Error at ';': Expect '.' after 'super'.
Исходное описание этапа (английский)
Вопрос для SynQ
Покажите SynQ входные данные, ваш прогноз и фактический результат. Спросите, какое промежуточное значение проверить первым.
Учебный маршрут
Итоговое задание
Итоговое задание
Покажите токены, дерево разбора и значение (2 + 3) * 4. Добавьте сравнение, лексическую ошибку, незакрытую скобку и арифметику со смешанными типами.
Критерии проверки
Первое выражение даёт 20, а 2 + 3 * 4 даёт 14. Отнесите каждую из трёх ошибок к правильной фазе и сохраните её диагностику.
Объясните результат
Почему разбор может успешно закончиться у выражения, которое затем не удаётся вычислить?
Оценивание проекта
Четыре критерия дают по одному баллу. Для завершения проекта подтвердите все четыре. Сохраните вместе исходники, команды запуска и результаты.
- Запускается из чистой копии проекта по указанной команде.
- Даёт эталонный результат, указанный в критериях.
- Для второго входа и одного граничного случая записаны ожидаемые и фактические значения.
- Проектное решение ниже объяснено с опорой на трассировку, промежуточное значение или измерение.
Проверьте себя
Чему равно 2 + 3 * 4 в Lox?
- 14
- 20
- 24
Показать ответ
14. Умножение имеет более высокий приоритет. В корне дерева находится сложение.
Источники и лицензии
Учебная адаптация и пояснения Digital Qazaqstan. Исходные практикумы подготовлены CodeCrafters.
interpreter
MIT License
Copyright (c) 2022 CodeCrafters
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Lox интерпретаторын жасау
Жоба нәтижесі
Бағдарлама мәтінін токендерге бөліп, өрнектерді талдап, мәнін есептеңіз. Күй, функциялар және кластар қосымша бөлімдерде беріледі.
Бастамас бұрын
Рекурсияны, жол, сан және логикалық мәндерді білетін әзірлеушілерге арналған.
Бағдарлама каталогы
Бастапқы жобалар
Оқу жолы
Тәжірибелік модульдер
- Лексемалар мен сканер қателері
- Өрнектің талдау ағашы
- Өрнектерді есептеу
Таңдау модульдері
Таңдау модульдері төменде бөлек берілген. Негізгі жобаны аяқтауға міндетті сабақтар жеткілікті.
- Күй және басқару
- Функциялар, тұйықталу және байланыстыру
- Кластар және мұрагерлік
Қорытынды тапсырма
Лексемалар мен сканер қателері
Мысал және өзіндік тексеру
var x = 12; жолын талдап, әр токеннің лексемасын, түрін және мәнін сақтаңыз. Екінші жолға белгісіз таңба енгізіңіз. Қате жолының нөмірін және соңғы EOF токенін тексеріңіз.
Іске асыру кезеңдері
- RY8 · Бос файл үшін тек аяқтаушы EOF токенін шығарыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
$ ./your_program.sh tokenize test.lox
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - OL4 · Ашылатын және жабылатын дөңгелек жақшаны екі бөлек токен деп таныңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
(()
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - OE8 · Фигуралы жақшаның екі түрін де таныңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
{{}}
$ ./your_program.sh tokenize test.lox
LEFT_BRACE { null
LEFT_BRACE { null
RIGHT_BRACE } null
RIGHT_BRACE } null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - XC5 · Бір таңбалық белгілерді токен түрлерімен сәйкестендіріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
({*.,+*})
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
LEFT_BRACE { null
STAR * null
DOT . null
COMMA , null
PLUS + null
STAR * null
RIGHT_BRACE } null
RIGHT_PAREN ) null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - EA6 · Белгісіз таңба қатесін жол нөмірімен беріп, оқуды жалғастырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
,.$(#
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: $
[line 1] Error: Unexpected character: #
COMMA , null
DOT . null
LEFT_PAREN ( null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - MP7 · Меншіктеу = мен теңдік == белгілерін ажыратыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
={===}
$ ./your_program.sh tokenize test.lox
EQUAL = null
LEFT_BRACE { null
EQUAL_EQUAL == null
EQUAL = null
RIGHT_BRACE } null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - BU3 · Келесі таңба арқылы ! пен != белгілерін ажыратыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
!!===
$ ./your_program.sh tokenize test.lox
BANG ! null
BANG_EQUAL != null
EQUAL_EQUAL == null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - ET2 · <= және >= кіретін төрт салыстыру операторын таныңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
<<=>>=
$ ./your_program.sh tokenize test.lox
LESS < null
LESS_EQUAL <= null
GREATER > null
GREATER_EQUAL >= null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - ML2 · / және жол соңына дейінгі // түсіндірмесін ажыратыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
()// Comment
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
/()
$ ./your_program.sh tokenize test.lox
SLASH / null
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - ER2 · Бос орын таңбаларын өткізіп, жол нөмірін жаңартыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
(<|TAB|>
<|SPACE|>)
$ ./your_program.sh tokenize test.lox
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - TZ7 · Әр жолдағы қатені сол жолдың нөмірімен беріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
#<|SPACE|>(
)<|TAB|>@
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unexpected character: #
[line 2] Error: Unexpected character: @
LEFT_PAREN ( null
RIGHT_PAREN ) null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - UE7 · Жол лексемасын және тырнақшасыз мәнін сақтаңыз. Жабылмаған жолды тексеріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"foo baz"
$ ./your_program.sh tokenize test.lox
STRING "foo baz" foo baz
EOF null
"bar
$ ./your_program.sh tokenize test.lox
[line 1] Error: Unterminated string.
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - KJ0 · Бүтін және бөлшек лексемаларды танып, сандық литералды беріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
42
$ ./your_program.sh tokenize test.lox
NUMBER 42 42.0
EOF null
1234.1234
$ ./your_program.sh tokenize test.lox
NUMBER 1234.1234 1234.1234
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - EY7 · Атаудың бастапқы және кейінгі рұқсатты таңбаларын ескеріп, оны тұтас оқыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
foo bar _hello
$ ./your_program.sh tokenize test.lox
IDENTIFIER foo null
IDENTIFIER bar null
IDENTIFIER _hello null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - PQ5 · Түйін сөздерді қарапайым атаулардан ажыратыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
and
$ ./your_program.sh tokenize test.lox
AND and null
EOF null
Кезеңнің толық түпнұсқасы (ағылшын тілінде)
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.
Оқу жолы
Өрнектің талдау ағашы
Мысал және өзіндік тексеру
2 + 3 * 4 және (2 + 3) * 4 ағаштарын сызыңыз. Түбір операторлары әртүрлі. Екі ағашты бағдарламадан шығарып, жабушы жақшаны алып тастағанда қатенің орнын тексеріңіз.
Іске асыру кезеңдері
- SC2 · true, false және nil үшін ағаш түйіндерін жасаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
true
$ ./your_program.sh parse test.lox
true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - RA8 · Сан токенін өз мәні бар литерал түйініне айналдырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
42.47
$ ./your_program.sh parse test.lox
42.47
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - TH5 · Жол литералының түйінін құрыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"hello"
$ ./your_program.sh parse test.lox
hello
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - XE6 · Жақша ішіндегі өрнекті топтау түйіні ретінде талдаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
("foo")
$ ./your_program.sh parse test.lox
(group foo)
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - MQ1 · Префикстік ! және минусты, соның ішінде оператор тізбегін талдаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
!true
$ ./your_program.sh parse test.lox
(! true)
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - WA9 · factor деңгейінде көбейту мен бөлуді операндтарымен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
16 * 38 / 58
$ ./your_program.sh parse test.lox
(/ (* 16.0 38.0) 58.0)
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - YF2 · Қосу мен азайтуды төменірек басымдықта өңдеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
52 + 80 - 94
$ ./your_program.sh parse test.lox
(- (+ 52.0 80.0) 94.0)
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - UH4 · Қатынас операторларын арифметикадан кейін талдаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
83 < 99 < 115
$ ./your_program.sh parse test.lox
(< (< 83.0 99.0) 115.0)
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - HT8 · == және != операторларын дұрыс басымдықпен талдаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"baz" == "baz"
$ ./your_program.sh parse test.lox
(== baz baz)
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - WZ8 · Операндтың не жабушы жақшаның жоқтығын хабарлаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
(72 +)
$ ./your_program.sh parse test.lox
[line 1] Error at ')': Expect expression.
Кезеңнің толық түпнұсқасы (ағылшын тілінде)
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.
Оқу жолы
Өрнектерді есептеу
Мысал және өзіндік тексеру
Екі ағаш 14 және 20 береді. Екі жолды біріктіріп, біреуін санмен алмастырыңыз. Талдау қатесі мен орындау кезіндегі тип қатесін салыстырып, шығыс ағыны мен аяқталу кодын жазыңыз.
Іске асыру кезеңдері
- IZ6 · true, false және nil литералдарының мәнін есептеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
true
$ ./your_program.sh evaluate test.lox
true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - LV1 · Жол мен сан мәндерін Lox пішімінде беріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"hello world!"
$ ./your_program.sh evaluate test.lox
hello world!
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - OQ9 · Топтау түйінінің ішкі өрнегін есептеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
("hello world!")
$ ./your_program.sh evaluate test.lox
hello world!
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - DC1 · Сан терістеуін және логикалық ! мәнін Lox ақиқаттық ережесімен есептеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
-(73)
$ ./your_program.sh evaluate test.lox
-73
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - BP3 · Көбейтінді мен бөліндіні есептеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
(18 * 3 / (3 * 6))
$ ./your_program.sh evaluate test.lox
3
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - JY2 · Сандардың қосындысы мен айырмасын есептеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
20 + 74 - (-(14 - 33))
$ ./your_program.sh evaluate test.lox
75
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - JX8 · + операторы екі жолды ретімен біріктірсін.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"hello" + " world!"
$ ./your_program.sh evaluate test.lox
hello world!
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - ET4 · Сан мәндерін қатынас операторларымен салыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
10 > 5
$ ./your_program.sh evaluate test.lox
true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - HW7 · nil мәнін қоса, тип пен мән бойынша теңдікті іске асырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
156 == (89 + 67)
$ ./your_program.sh evaluate test.lox
true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - GJ9 · Сан емес мәнге унарлық минус қолданылса, орындалу қатесін беріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
-"hello world!"
$ ./your_program.sh evaluate test.lox
Operand must be a number.
[line 1]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - YU6 · Сандық амал кезінде екі операндтың типін тексеріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"foo" / 42
$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - CQ1 · + ішінде жол мен санның рұқсатсыз тіркесін қабылдамаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
17 + "bar"
$ ./your_program.sh evaluate test.lox
Operands must be two numbers or two strings.
[line 1]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - IB5 · Екі сан қажет салыстыруда тип сәйкес келмесе, қате беріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
17 > "bar"
$ ./your_program.sh evaluate test.lox
Operands must be numbers.
[line 1]
Кезеңнің толық түпнұсқасы (ағылшын тілінде)
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.
Оқу жолы
Күй және басқару
Мысал және өзіндік тексеру
Сыртқы айнымалыны блок ішінде көлеңкелеп, екі мәнді шығарыңыз. Циклде 1, 2 және 3-ті қосып, 6 алыңыз. Меншіктеу жазбасы арқылы ауқым қатесін цикл қатесінен ажыратыңыз.
Іске асыру кезеңдері
- XY1 · print орындап, өрнек мәнін шығарыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print "Hello, World!";
$ ./your_program.sh run test.lox
Hello, World!
print;
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - OE4 · Бірнеше print командасын бағдарлама ретімен орындаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print "Hello, World!";
print 42;
$ ./your_program.sh run test.lox
Hello, World!
42
print "world" + "baz" + "bar";
print 27 - 26;
print "bar" == "quz";
worldbazbar
1
false
print "hello"; print true;
print false;
print "bar"; print 43;
hello
true
false
bar
43
print 81;
print 81 + 46;
print 81 + 46 + 19;
81
127
146
print true != true;
print "36
10
78
";
print "There should be an empty line above this.";
false
36
10
78
There should be an empty line above this.
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - FI3 · Соңында нүктелі үтірі бар жеке өрнекті талдаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
"foo" + "bar";
print "baz";
$ ./your_program.sh run test.lox
baz
(37 + 42 - 21) > (76 - 37) * 2;
print !false;
"baz" + "hello" + "quz" + "bar" == "bazhelloquzbar";
print !false;
true
true
27 - 60 >= -99 * 2 / 99 + 76;
true == true;
("world" == "bar") == ("baz" != "hello");
print true;
true
print "the expression below is invalid";
49 + "baz";
print "this should not be printed";
the expression below is invalid
Operands must be two numbers or two strings.
[line 2]
print "79" + "baz";
print false * (18 + 84);
79baz
Operands must be numbers.
[line 2]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - YG2 · var жариялауын және атауды ортадан оқуды қосыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var a = "foo";
print a;
$ ./your_program.sh run test.lox
foo
var world = 10;
print world;
10
var bar = 99;
var foo = 99;
print bar + foo;
var quz = 99;
print bar + foo + quz;
198
297
var foo = (8 * (62 + 62)) / 4 + 62;
print foo;
310
var quz = 76;
var baz = quz;
print baz + quz;
152
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - SV7 · Жарияланбаған атауды оқығанда қате хабарлаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print a;
$ ./your_program.sh run test.lox
Undefined variable 'a'.
[line 1]
print 22;
print x;
22
Undefined variable 'x'.
[line 2]
var baz = 96;
print hello;
Undefined variable 'hello'.
[line 2]
var hello = 85;
var result = (hello + bar) / world;
print result;
Undefined variable 'bar'.
[line 2]
var quz = 20;
var world = 51;
var hello = 56;
print quz + world + he
Undefined variable 'he'.
[line 4]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - BC1 · Айнымалының бастапқы мәнін есептеп, сақтаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var a;
print a;
$ ./your_program.sh run test.lox
nil
var foo;
print foo;
nil
var baz = "foo";
var bar;
print bar;
var baz = 69;
var world;
var quz;
print world;
var quz = 73 + 26 * 20;
print quz;
var hello = 26 * 20;
print quz + hello;
var foo;
print foo;
593
1113
nil
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - DW9 · Айнымалыны қайта жариялау ережесін қолданыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var a = 1;
var a = 2;
print a;
$ ./your_program.sh run test.lox
2
var baz = "before";
print baz;
var baz = "after";
print baz;
before
after
var hello = "after";
var hello = "before";
var hello = hello;
print hello;
before
var world = 2;
print world;
var world = 3;
print world;
var hello = 5;
print hello;
var world = hello;
print world;
2
3
5
5
var baz = bar;
Undefined variable 'bar'.
[line 1]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - PL3 · Өрнек нәтижесін бұрын жарияланған айнымалыға жазыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var a;
var b = 2;
var a = b = 1;
print a;
$ ./your_program.sh run test.lox
1
var quz;
quz = 1;
print quz;
print quz = 2;
print quz;
1
2
2
var hello = 93;
var bar = 93;
bar = hello;
hello = bar;
print hello + bar;
186
var quz;
var hello;
quz = hello = 16 + 34 * 92;
print quz;
print hello;
3144
3144
var hello = 65;
var baz;
var quz;
hello = baz = quz = hello * 2;
print hello;
print baz;
print baz;
130
130
130
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - VR5 · Фигуралы жақшадағы нұсқауларды ретімен орындаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
{
var foo = "before";
print foo;
}
{
var foo = "after";
print foo;
}
$ ./your_program.sh run test.lox
before
after
{
var hello = "baz";
print hello;
}
baz
{
var world = "before";
print world;
}
{
var world = "after";
print world;
}
before
after
{
var hello = 88;
{
var foo = 88;
print foo;
}
print hello;
}
88
88
{
var bar = 11;
var world = 11;
{
print bar + world;
}
[line 6] Error at end: Expect '}' .
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - FB4 · Ішкі ауқымдағы атауларды сыртқы орталар тізбегі арқылы анықтаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
{
var world = "before";
{
var world = "after";
print world;
}
print world;
}
$ ./your_program.sh run test.lox
after
before
var baz = (91 * 16) - 61;
{
var world = "quz" + "89";
print world;
}
print baz;
quz89
1395
{
var quz = "before";
{
var quz = "after";
print quz;
}
print quz;
}
after
before
var bar = "global bar";
var world = "global world";
var hello = "global hello";
{
var bar = "outer bar";
var world = "outer world";
{
var bar = "inner bar";
print bar;
print world;
print hello;
}
print bar;
print world;
print hello;
}
print bar;
print world;
print hello;
inner bar
outer world
global hello
outer bar
outer world
global hello
global bar
global world
global hello
{
var hello = "outer hello";
{
var hello = "inner hello";
print hello;
}
print hello;
}
print hello;
inner hello
outer hello
Undefined variable 'hello'.
[line 9]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - NE3 · Шарт ақиқат болса, if денесін орындаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
if (true) print "good";
$ ./your_program.sh run test.lox
good
if (true) print "bar";
bar
if (true) {
print "block body";
}
block body
var a = false;
if (a = true) {
print (a == true);
}
true
var stage = "unknown";
var age = 50;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
adult
eligible for voting: true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - ST5 · Шарт жалған болса, else тармағын таңдаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
if (true) print "if branch"; else print "else branch";
$ ./your_program.sh run test.lox
if branch
if branch
var age = 21;
if (age > 18) print "adult"; else print "child";
adult
if (false) {
print "if block";
} else print "else statement";
if (false) print "if statement"; else {
print "else block";
}
else statement
else block
var celsius = 67;
var fahrenheit = 0;
var isHot = false;
{
fahrenheit = celsius * 9 / 5 + 32;
print celsius; print fahrenheit;
if (celsius > 30) {
isHot = true;
print "It's a hot day. Stay hydrated!";
} else {
print "It's cold today. Wear a jacket!";
}
if (isHot) { print "Remember to use sunscreen!"; }
}
67
152.6
It's a hot day. Stay hydrated!
Remember to use sunscreen!
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - FH8 · else if тізбегін өңдеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
if (false) print "if branch"; else if (false) print "else-if branch";
$ ./your_program.sh run test.lox
if (true) print "if branch"; else if (false) print "else-if branch";
if branch
if (true) {
print "hello";
} else if (true) print "hello";
if (true) print "hello"; else if (true) {
print "hello";
}
hello
hello
var age = 88;
var stage = "unknown";
if (age < 18) { stage = "child"; }
else if (age >= 18) { stage = "adult"; }
else if (age >= 65) { stage = "senior"; }
else if (age >= 100) { stage = "centenarian"; }
print stage;
adult
var age = 67;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
else { print "eligible for voting: false"; }
if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) { print "eligible for driving: learner's permit"; }
else { print "eligible for driving: full license"; }
if (age < 21) { print "eligible for drinking (US): false"; }
else { print "eligible for drinking (US): true"; }
eligible for voting: true
eligible for driving: full license
eligible for drinking (US): true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - XJ4 · else тармағын тиісті ішкі if шартымен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
if (true) if (true) print "nested true";
$ ./your_program.sh run test.lox
nested true
nested true
if (true) {
if (false) print "quz"; else print "quz";
}
quz
var stage = "unknown";
var age = 29;
if (age < 18) {
if (age < 13) { stage = "child"; }
else if (age < 16) { stage = "young teenager"; }
else { stage = "teenager"; }
}
else if (age < 65) {
if (age < 30) { stage = "young adult"; }
else if (age < 50) { stage = "adult"; }
else { stage = "middle-aged adult"; }
}
else { stage = "senior"; }
print stage;
var isAdult = age >= 18;
if (isAdult) {
print "eligible for voting: true";
if (age < 25) {
print "first-time voter: likely";
}
else { print "first-time voter: unlikely"; }
}
else { print "eligible for voting: false"; }
if (age < 16) { print "eligible for driving: false"; }
else if (age < 18) {
print "eligible for driving: learner's permit";
if (age < 17) { print "supervised driving required"; }
else { print "unsupervised driving allowed with restrictions"; }
}
else { print "eligible for driving: full license"; }
if (age < 21) { print "eligible for drinking (US): false"; }
else {
print "eligible for drinking (US): true";
if (age < 25) { print "remember: drink responsibly!"; }
}
young adult
eligible for voting: true
first-time voter: unlikely
eligible for driving: full license
eligible for drinking (US): true
if (true) if (false) print "world"; else print "baz";
baz
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - WK8 · or үшін қысқартылған есептеуді іске асырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print nil or "ok";
$ ./your_program.sh run test.lox
ok
if (false or "ok") print "baz";
if (nil or "ok") print "baz";
if (false or false) print "world";
if (true or "world") print "world";
if (24 or "bar") print "bar";
if ("bar" or "bar") print "bar";
baz
baz
world
bar
bar
print 41 or true;
print false or 41;
print false or false or true;
print false or false;
print false or false or false;
print true or true or true or true;
41
41
true
false
false
true
var a = "hello";
var b = "hello";
(a = false) or (b = true) or (a = "hello");
print a;
print b;
false
true
var stage = "unknown";
var age = 23;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
adult
eligible for voting: true
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - JX4 · and үшін қысқартылған есептеуді іске асырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print false and "ok";
$ ./your_program.sh run test.lox
false
if (false and "bad") print "foo";
if (nil and "bad") print "foo";
if (true and "hello") print "hello";
if (97 and "baz") print "baz";
if ("baz" and "baz") print "baz";
if ("" and "bar") print "bar";
hello
baz
baz
bar
print false and 1;
print true and 1;
print 23 and "hello" and false;
print 23 and true;
print 23 and "hello" and 23;
false
1
false
true
23
var a = "quz";
var b = "quz";
(a = true) and (b = false) and (a = "bad");
print a;
print b;
true
false
var stage = "unknown";
var age = 14;
if (age < 18) { stage = "child"; }
if (age >= 18) { stage = "adult"; }
print stage;
var isAdult = age >= 18;
if (isAdult) { print "eligible for voting: true"; }
if (!isAdult) { print "eligible for voting: false"; }
child
eligible for voting: false
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - QY3 · Әр жолы шартты қайта тексеріп, while денесін қайталаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var foo = 0;
while (foo < 3) print foo = foo + 1;
$ ./your_program.sh run test.lox
1
2
3
1
2
3
var quz = 0;
while (quz < 3) {
print quz;
quz = quz + 1;
}
0
1
2
while (false) {
print "should not print";
}
var product = 1;
var i = 1;
while (i <= 5) {
product = product * i;
i = i + 1;
}
print "Product of numbers 1 to 5: "; print product;
Product of numbers 1 to 5:
120
var n = 10;
var fm = 0;
var fn = 1;
var index = 0;
while (index < n) {
print fm;
var temp = fm;
fm = fn;
fn = temp + fn;
index = index + 1;
}
0
1
1
2
3
5
8
13
21
34
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - BW6 · for циклінің инициализациясы, шарты және қадамын ескеріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
for (var baz = 0; baz < 3;) print baz = baz + 1;
$ ./your_program.sh run test.lox
1
2
3
1
2
3
for (var world = 0; world < 3; world = world + 1) {
print world;
}
0
1
2
var world = 0;
for (; world < 2; world = world + 1) print world;
for (var foo = 0; foo < 2;) {
print foo;
foo = foo + 1;
}
0
1
0
1
var quz = "after";
{
var quz = "before";
for (var quz = 0; quz < 1; quz = quz + 1) {
print quz;
var quz = -1;
print quz;
}
}
{
for (var quz = 0; quz > 0; quz = quz + 1) {}
var quz = "after";
print quz;
for (quz = 0; quz < 1; quz = quz + 1) {
print quz;
}
}
0
-1
after
0
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - VT1 · Қате басқару құрылымындағы синтаксистік қатені көрсетіңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
for (;;) var foo;
$ ./your_program.sh run test.lox
[line 1] Error at 'var': Expect expression.
if (true) "ok"; else var foo;
[line 1] Error at 'var': Expect expression.
for (var a = 1; {}; a = a + 1) {}
[line 2] Error at '{': Expect expression.
[line 2] Error at ')': Expect ';' after expression.
for (var a = 1; a < 2; {}) {}
[line 2] Error at '{': Expect expression.
for ({}; a < 2; a = a + 1) {}
Кезеңнің толық түпнұсқасы (ағылшын тілінде)
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.
Оқу жолы
Функциялар, тұйықталу және байланыстыру
Мысал және өзіндік тексеру
Функциядан санауыш тұйықталуын қайтарыңыз. Екі санауыш жасап, бөлек шақырыңыз. return нұсқауын функция сыртына шығарып, қате орта туралы хабарды тексеріңіз.
Іске асыру кезеңдері
- AV4 · Оқу ортасында кірістірілген уақыт функциясын тіркеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print clock();
$ ./your_program.sh run test.lox
1731411035
print clock() + 75;
1731411035
print clock() / 1000;
1731410
var startTime = clock();
var timeoutSeconds = 2;
// Check if less than 2 seconds have elapsed
if ((clock() >= startTime) and (clock() <= (startTime + timeoutSeconds))) {
print "Operation in progress...";
} else {
print "Operation timed out!";
}
Operation in progress...
// Countdown from 3 seconds
var startTime = clock();
var totalDuration = 3; // 3 seconds countdown
var lastCheck = startTime;
var completed = false;
while (!completed) {
var currentTime = clock();
var elapsedTime = currentTime - startTime;
var remainingTime = totalDuration - elapsedTime;
// Update progress every second
if (currentTime >= lastCheck + 1) {
if (remainingTime >= 2) {
print "Plenty of time remaining: ";
print remainingTime;
} else if (remainingTime >= 1) {
print "Getting closer: ";
print remainingTime;
} else if (remainingTime > 0) {
print "Almost there: ";
print remainingTime;
}
lastCheck = currentTime;
}
// Check for completion
if (elapsedTime >= totalDuration) {
completed = true;
print "Countdown complete!";
} else if (elapsedTime < 0) {
// Handle clock overflow or system time changes
print "Time error detected!";
completed = true;
}
}
Plenty of time remaining:
2
Getting closer:
1
Countdown complete!
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - PG8 · Аргументсіз функцияны анықтап, шақырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
fun bar() { print 10; }
bar();
$ ./your_program.sh run test.lox
10
fun foo() {
print 7;
}
foo();
7
fun f() {}
f();
fun foo() {}
print foo;
<fn foo>
fun cumulative_sum() {
var n = 10; // Fixed value
var total = 0;
var i = 1;
while (i <= n) {
total = total + i;
i = i + 1;
}
print "The cumulative sum from 1 to 10 is: ";
print total;
}
cumulative_sum();
The cumulative sum from 1 to 10 is:
55
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - LB6 · Берілген аргументтерді функция параметрлерімен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
fun foo(a) { print a; }
foo(10);
$ ./your_program.sh run test.lox
10
fun f1(a) {
print a;
}
f1(76);
76
fun f3(a, b, c) { print a + b + c; }
f3(24, 24, 24);
72
fun f8(a, b, c, d, e, f, g, h) { print a - b + c * d + e - f + g - h; }
f8(51, 51, 51, 51, 51, 51, 51, 51);
2601
fun calculateGrade(score, bonus) {
var finalScore = score + bonus;
if (finalScore >= 90) {
print "A";
} else if (finalScore >= 80) {
print "B";
} else if (finalScore >= 70) {
print "C";
} else if (finalScore >= 60) {
print "D";
} else {
print "F";
}
}
var score = 81;
var bonus = 3;
print "Grade for given score is: ";
calculateGrade(score, bonus);
Grade for given score is:
B
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - PX4 · Талдау кезінде функцияны жариялау не шақыру синтаксисіндегі қатені табыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
clock(;
$ ./your_program.sh run test.lox
[line 2] Error at ';': Expect expression.
print clock(;
[line 1] Error at ';': Expect expression.
print clock)));
[line 1] Error at ')': Expect ';' after value.
fun f() 74;
print f();
[line 2] Error at '74': Expect '{' before function body.
fun foo(a, b c, d, e, f) {}
foo();
[line 2] Error at 'c': Expect ')' after parameters.
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - RD2 · return арқылы мән қайтарып, дененің орындалуын тоқтатыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
fun foo() { return 10; }
print foo();
$ ./your_program.sh run test.lox
10
fun fib(n) {
if (n < 2) return n;
return fib(n - 2) + fib(n - 1);
}
var start = clock();
print fib(10) == 55;
print (clock() - start) < 5; // 5 seconds
true
true
fun f() {
if (false) return "no"; else return "ok";
}
print f();
ok
fun f() {
while (!true) return "ok";
}
print f();
nil
fun f() {
return;
print "bad";
}
print f();
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - EY3 · Функцияны басқа функцияға мән ретінде беріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
fun makeGreeter() {
fun greet(name) {
print "Hello " + name;
}
return greet;
}
var sayHello = makeGreeter();
sayHello("Bob");
$ ./your_program.sh run test.lox
Hello Bob
Hello Bob
fun returnArg(arg) {
return arg;
}
fun returnFunCallWithArg(func, arg) {
return returnArg(func)(arg);
}
fun printArg(arg) {
print arg;
}
returnFunCallWithArg(printArg, "foo");
foo
fun square(x) {
return x * x;
}
// This higher-order function applies a
// function N times to a starting value x.
fun applyTimesN(N, f, x) {
var i = 0;
while (i < N) {
x = f(x);
i = i + 1;
}
return x;
}
// 6 is squared once
print applyTimesN(1, square, 6);
// 6 is squared twice
print applyTimesN(2, square, 6);
// 6 is squared thrice
print applyTimesN(3, square, 6);
36
1296
1679616
fun makeFilter() {
fun filter(n) {
if (n < 42) {
return false;
}
return true;
}
return filter;
}
// This function applies a function to a list of numbers
fun applyToNumbers(f, count) {
var n = 0;
while (n < count) {
if (f(n)) {
print n;
}
n = n + 1;
}
}
var greaterThanX = makeFilter();
print "Numbers >= 42:";
applyToNumbers(greaterThanX, 42 + 5);
Numbers >= 42:
42
43
44
45
46
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - FJ7 · Шақырылмайтын мәнді және қате аргумент санын өңдеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
85();
$ ./your_program.sh run test.lox
Can only call functions and classes.
[line 1]
"not a function"();
Can only call functions and classes.
[line 1]
fun f(a, b) {
print a;
print b;
}
f(1, 2, 3, 4);
Expected 2 arguments but got 4.
[line 6]
fun f(a, b) {}
f(1);
Expected 2 arguments but got 1.
[line 3]
false();
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - BZ4 · Әр шақыруға бөлек орта құрыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var a = 38;
fun printAndModify() {
print a;
var a = 95;
print a;
}
print a;
a = 68;
printAndModify();
$ ./your_program.sh run test.lox
38
68
95
38
68
95
var count = 3;
fun tick() {
if (count > 0) {
print count;
count = count - 1;
return false;
}
print "Blast off!";
return true;
}
while (!tick()) {}
3
2
1
Blast off!
var counter = 89;
fun incrementCounter(amount) {
counter = counter + amount;
print counter;
}
{
counter = 83;
incrementCounter(6);
print counter;
}
print counter;
89
89
89
var x = 1;
var y = 2;
fun printBoth() {
if (x < y) {
print "x is less than y:";
print x;
print y;
} else {
print "x is not less than y:";
print x;
print y;
}
}
{
var x = 10;
{
var y = 20;
var i = 0;
while (i < 3) {
x = x + 1;
y = y - 1;
print "Local x: ";
print x;
print "Local y: ";
print y;
i = i + 1;
}
if (x > y) {
print "Local x > y";
}
printBoth();
}
}
Local x:
11
Local y:
19
Local x:
12
Local y:
18
Local x:
13
Local y:
17
x is less than y:
1
2
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - GG6 · Сыртқы функция аяқталғаннан кейін ұсталған айнымалыны сақтаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
fun makeCounter() {
var i = 0;
fun count() {
i = i + 1;
print i;
}
return count;
}
var counter = makeCounter();
counter();
counter();
$ ./your_program.sh run test.lox
1
2
1
2
{
var threshold = 50;
fun isEven(n) {
if (n == 0) return true;
if (n > threshold) return false;
return isOdd(n - 1);
}
fun isOdd(n) {
if (n == 0) return false;
if (n > threshold) return false;
return isEven(n - 1);
}
print isEven(61);
}
false
fun makeLogger(prefix) {
var logCount = 0;
fun log(message) {
logCount = logCount + 1;
print prefix + ": " + message;
if (logCount > 6) {
print prefix + ": Too many log lines!";
logCount = 0;
}
}
return log;
}
var debugLog = makeLogger("debug");
var errorLog = makeLogger("error");
debugLog("Starting");
debugLog("Processing");
debugLog("Finishing");
debugLog("Extra line");
errorLog("Failed!");
errorLog("Retrying...");
debug: Starting
debug: Processing
debug: Finishing
debug: Extra line
error: Failed!
error: Retrying...
fun makeAccumulator(label) {
var sum = 0;
var count = 0;
fun accumulate(value) {
sum = sum + value;
count = count + 1;
print label;
print count;
print sum;
print sum;
if (count > 3) {
print "reset";
sum = 0;
count = 0;
}
return sum;
}
return accumulate;
}
var acc1 = makeAccumulator("First:");
var acc2 = makeAccumulator("Second:");
acc1(2);
acc1(6);
acc1(3);
acc1(4);
acc2(6);
acc2(4);
First:
1
2
2
First:
2
8
8
First:
3
11
11
First:
4
15
15
reset
Second:
1
6
6
Second:
2
10
10
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - DE8 · Атаудың қолданылуын тиісті лексикалық жариялаумен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var variable = "global";
{
fun f() {
print variable;
}
f();
var variable = "local";
f();
}
$ ./your_program.sh run test.lox
global
global
fun global() {
print "global";
}
{
fun f() {
global();
}
f();
fun global() {
print "local";
}
f();
}
global
global
var x = "global";
fun outer() {
var x = "outer";
fun middle() {
fun inner() {
print x;
}
inner();
var x = "middle";
inner();
}
middle();
}
outer();
outer
outer
var count = 0;
{
fun makeCounter() {
fun counter() {
count = count + 1;
print count;
}
return counter;
}
var counter1 = makeCounter();
counter1();
counter1();
var count = 0;
counter1();
}
1
2
3
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - PT7 · Жергілікті айнымалының өз инициализаторында оқылуын табыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
var a = "value";
var a = a; // This is allowed in global scope
print a; // Should print "value"
$ ./your_program.sh run test.lox
value
var a = "outer";
{
var a = a; // Error: Can't read local variable in its own initializer
}
[line 3] Error at 'a': Can't read local variable in its own initializer.
fun returnArg(arg) {
return arg;
}
var b = "global";
{
var a = "first";
var b = returnArg(b); // Error: Can't read local variable in its own initializer
print b;
}
var b = b + " updated";
print b;
[line 8] Error at 'b': Can't read local variable in its own initializer.
fun outer() {
var a = "outer";
fun inner() {
var a = a; // Error: Can't read local variable in its own initializer
print a;
}
inner();
}
outer();
[line 5] Error at 'a': Can't read local variable in its own initializer.
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - PZ7 · Бір ауқымда жергілікті айнымалының қайта жариялануын табыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
{
var a = "value";
var a = "other";
}
$ ./your_program.sh run test.lox
[line 3] Error at 'a': Already a variable with this name in this scope.
fun foo(a) {
var a;
}
[line 2] Error at 'a': Already a variable with this name in this scope.
fun foo(arg, arg) {
"body";
}
[line 1] Error at 'arg': Already a variable with this name in this scope.
var a = "1";
print a;
var a;
print a;
var a = "2";
print a;
{
var a = "1";
var a = "2";
print a;
}
[line 12] Error at 'a': Already a variable with this name in this scope.
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - EH3 · Функция денесінен тыс return қолданылуын табыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
fun foo() {
return "at function scope is ok";
}
return;
$ ./your_program.sh run test.lox
[line 6] Error at 'return': Can't return from top-level code.
fun foo() {
if (true) {
return "early return";
}
for (var i = 0; i < 10; i = i + 1) {
return "loop return";
}
}
if (true) {
return "conditional return";
}
[line 12] Error at 'return': Can't return from top-level code.
{
return "not allowed in a block either";
}
fun allowed() {
if (true) {
return "this is fine";
}
return;
}
[line 3] Error at 'return': Can't return from top-level code.
fun outer() {
fun inner() {
return "ok";
}
return "also ok";
}
if (true) {
fun nested() {
return;
}
return "not ok";
}
[line 15] Error at 'return': Can't return from top-level code.
Кезеңнің толық түпнұсқасы (ағылшын тілінде)
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.
Оқу жолы
Кластар және мұрагерлік
Мысал және өзіндік тексеру
Класта speak() анықтап, ішкі класта қайта жазыңыз және super.speak() шақырыңыз. Қай әдіс орындалғанын, ішкі кластан тыс super үшін қатені тексеріңіз.
Іске асыру кезеңдері
- VF4 · Класты жариялап, оны атауымен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Spaceship {}
print Spaceship;
$ ./your_program.sh run test.lox
Spaceship
// Multiple class declarations with empty body
class Robot {}
class Wizard {}
print Robot;
print Wizard;
print "Both classes successfully printed";
Robot
Wizard
Both classes successfully printed
{
// Class declaration inside blocks should work
class Dinosaur {}
print "Inside block: Dinosaur exists";
print Dinosaur;
}
print "Accessing out-of-scope class:";
print Dinosaur; // expect runtime error
Inside block: Dinosaur exists
Dinosaur
Accessing out-of-scope class:
Undefined variable 'Dinosaur'.
[line 8]
// Class declaration inside function should work
fun foo() {
class Superhero {}
print "Class declared inside function";
print Superhero;
}
foo();
print "Function called successfully";
Class declared inside function
Superhero
Function called successfully
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - YK8 · Класс шақырылғанда оның данасын жасаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Spaceship {}
var falcon = Spaceship();
print falcon;
$ ./your_program.sh run test.lox
Spaceship instance
// Creating multiple instances of the same class
class Robot {}
var r1 = Robot();
var r2 = Robot();
print "Created multiple robots:";
print r1;
print r2;
Created multiple robots:
Robot instance
Robot instance
class Wizard {}
class Dragon {}
// Instantiating classes in a function should work
fun createCharacters() {
var merlin = Wizard();
var smaug = Dragon();
print "Characters created in fantasy world:";
print merlin;
print smaug;
return merlin;
}
var mainCharacter = createCharacters();
// An instance of a class should be truthy
if (mainCharacter) {
print "The main character is:";
print mainCharacter;
} else {
print "Failed to create a main character.";
}
Characters created in fantasy world:
Wizard instance
Dragon instance
The main character is:
Wizard instance
class Superhero {}
var count = 0;
while (count < 3) {
var hero = Superhero();
print "Hero created:";
print hero;
count = count + 1;
}
print "All heroes created!";
Hero created:
Superhero instance
Hero created:
Superhero instance
Hero created:
Superhero instance
All heroes created!
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - YF3 · Нүкте арқылы дана өрістерін оқу мен жазуды іске асырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
// Basic property setting and getting
class Spaceship {}
var falcon = Spaceship();
falcon.name = "Millennium Falcon";
falcon.speed = 75.5;
print "Ship details:";
print falcon.name;
print falcon.speed;
$ ./your_program.sh run test.lox
Ship details:
Millennium Falcon
75.5
// Multiple properties and conditional access
class Robot {}
var r2d2 = Robot();
r2d2.model = "Astromech";
r2d2.operational = false;
if (r2d2.operational) {
print r2d2.model;
r2d2.mission = "Navigate hyperspace";
print r2d2.mission;
}
(No output because the condition is false)
// Multiple instances with properties
class Superhero {}
var batman = Superhero();
var superman = Superhero();
batman.name = "Batman";
batman.called = 18;
superman.name = "Superman";
superman.called = 66;
print "Times " + superman.name + " was called: ";
print superman.called;
print "Times " + batman.name + " was called: ";
print batman.called;
Times Superman was called:
66
Times Batman was called:
18
// Property manipulation in functions
class Wizard {}
var gandalf = Wizard();
gandalf.color = "Grey";
gandalf.power = nil;
print gandalf.color;
fun promote(wizard) {
wizard.color = "White";
if (true) {
wizard.power = 100;
} else {
wizard.power = 0;
}
}
promote(gandalf);
print gandalf.color;
print gandalf.power;
Grey
White
100
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - QR2 · Класс әдісін тауып, дана үшін шақырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Robot {
beep() {
print "Beep boop!";
}
}
var r2d2 = Robot();
r2d2.beep();
Robot().beep();
$ ./your_program.sh run test.lox
Beep boop!
Beep boop!
{
class Foo {
returnSelf() {
return Foo;
}
}
print Foo().returnSelf(); // expect: Foo
}
Foo
class Wizard {
castSpell(spell) {
print "Casting a magical spell: " + spell;
}
}
class Dragon {
breatheFire(fire, intensity) {
print "Breathing " + fire + " with intensity: "
+ intensity;
}
}
// Methods on different class instances
var merlin = Wizard();
var smaug = Dragon();
// Conditional method calling
if (true) {
var action = merlin.castSpell;
action("Fireball");
} else {
var action = smaug.breatheFire;
action("Fire", "100");
}
Casting a magical spell: Fireball
class Superhero {
useSpecialPower(hero) {
print "Using power: " + hero.specialPower;
}
hasSpecialPower(hero) {
return hero.specialPower;
}
giveSpecialPower(hero, power) {
hero.specialPower = power;
}
}
// Methods in functions
fun performHeroics(hero, superheroClass) {
if (superheroClass.hasSpecialPower(hero)) {
superheroClass.useSpecialPower(hero);
} else {
print "No special power available";
}
}
var superman = Superhero();
var heroClass = Superhero();
if (true) {
heroClass.giveSpecialPower(superman, "Flight");
} else {
heroClass.giveSpecialPower(superman, "Strength");
}
performHeroics(superman, heroClass);
Using power: Flight
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - YD7 · this мәнін әдіс шақырылатын данамен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Spaceship {
identify() {
print this;
}
}
Spaceship().identify();
$ ./your_program.sh run test.lox
Spaceship instance
class Calculator {
add(a, b) {
return a + b + this.memory;
}
}
var calc = Calculator();
calc.memory = 82;
print calc.add(92, 1);
175
class Animal {
makeSound() {
print this.sound;
}
identify() {
print this.species;
}
}
var dog = Animal();
dog.sound = "Woof";
dog.species = "Dog";
var cat = Animal();
cat.sound = "Meow";
cat.species = "Cat";
// Swap methods between instances
cat.makeSound = dog.makeSound;
dog.identify = cat.identify;
cat.makeSound();
dog.identify();
Woof
Cat
class Wizard {
getSpellCaster() {
fun castSpell() {
print this;
print "Casting spell as " + this.name;
}
return castSpell;
}
}
var wizard = Wizard();
wizard.name = "Merlin";
wizard.getSpellCaster()();
Wizard instance
Casting spell as Merlin
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - DG2 · this мәнінің жарамсыз ортада қолданылуын табыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
print this;
$ ./your_program.sh run test.lox
[line 1] Error at 'this': Can't use 'this' outside of a class.
fun notAMethod() {
print this;
}
[line 2] Error at 'this': Can't use 'this' outside of a class.
class Person {
sayName() {
print this();
}
}
Person().sayName();
Can only call functions and classes.
[line 3]
class Confused {
method() {
fun inner(instance) {
var feeling = "confused";
print this.feeling;
}
return inner;
}
}
var instance = Confused();
var m = instance.method();
m(instance);
Undefined property 'feeling'.
[line 5]
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - OU5 · Дана құрылғанда init әдісін автоматты түрде шақырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Default {
init() {
this.x = "bar";
this.y = 91;
}
}
print Default().x;
print Default().y;
$ ./your_program.sh run test.lox
bar
91
class Robot {
init(model, function) {
this.model = model;
this.function = function;
}
}
print Robot("R2-D2", "Astromech").model;
R2-D2
class Counter {
init(startValue) {
if (startValue < 0) {
print "startValue can't be negative";
this.count = 0;
} else {
this.count = startValue;
}
}
}
var instance = Counter(-52);
print instance.count;
print instance.init(52).count;
startValue can't be negative
0
52
class Vehicle {
init(type) {
this.type = type;
}
}
class Car {
init(make, model) {
this.make = make;
this.model = model;
this.wheels = "four";
}
describe() {
print this.make + " " + this.model +
" with " + this.wheels + " wheels";
}
}
var vehicle = Vehicle("Generic");
print "Generic " + vehicle.type;
var myCar = Car("Toyota", "Corolla");
myCar.describe();
Generic Generic
Toyota Corolla with four wheels
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - EB9 · Конструктор ішіндегі return шектеулерін қолданыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Person {
init() {
print "world";
return;
}
}
Person();
$ ./your_program.sh run test.lox
world
class ThingDefault {
init() {
this.x = "foo";
this.y = 42;
return this;
}
}
var out = ThingDefault();
print out;
[line 5] Error at 'return': Can't return a value from an initializer.
class Foo {
init() {
return "something else";
}
}
Foo();
[line 3] Error at 'return': Can't return a value from an initializer.
class Foo {
init() {
return this.callback();
}
callback() {
return "callback";
}
}
Foo();
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - MF6 · Ішкі класты жарияланған базалық класымен байланыстырыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Doughnut {}
class BostonCream < Doughnut {}
print Doughnut();
print BostonCream();
$ ./your_program.sh run test.lox
Doughnut instance
BostonCream instance
{
class A {}
// B is a subclass of A
class B < A {}
// C is also a subclass of A
class C < A {}
print A();
print B();
print C();
}
A instance
B instance
C instance
class Vehicle {}
// Car is a subclass of Vehicle
class Car < Vehicle {}
// Sedan is a subclass of Car
class Sedan < Car {}
print Vehicle();
print Car();
print Sedan();
{
// Truck is a subclass of Vehicle
class Truck < Vehicle {}
print Truck();
}
Vehicle instance
Car instance
Sedan instance
Truck instance
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - KY1 · Мұраланған әдісті кластар тізбегінен іздеңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Doughnut {
cook() {
print "Fry until golden brown.";
}
}
// BostonCream is a subclass of Doughnut
class BostonCream < Doughnut {}
// BostonCream class should inherit the cook
// method from Doughnut class
BostonCream().cook();
$ ./your_program.sh run test.lox
Fry until golden brown.
class Root {
getName() {
print "Root class";
}
}
class Parent < Root {
parentMethod() {
print "Method defined in Parent";
}
}
class Child < Parent {
childMethod() {
print "Method defined in Child";
}
}
var root = Root();
var parent = Parent();
var child = Child();
// Root methods are available to all
root.getName();
parent.getName();
child.getName();
// Parent methods are available to Parent and Child
parent.parentMethod();
child.parentMethod();
// Child methods are only available to Child
child.childMethod();
Root class
Root class
Root class
Method defined in Parent
Method defined in Parent
Method defined in Child
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - KA5 · Әдісті ішкі кластың қайта анықтауын ескеріңіз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class A {
method() {
print "A method";
}
}
// B inherits method `method` from A
// and overrides it with a new implementation
class B < A {
method() {
print "B method";
}
}
var b = B();
b.method(); // expect: B method
$ ./your_program.sh run test.lox
B method
class Base {
init(a) {
this.a = a;
}
}
// Constructors can also be overridden
class Derived < Base {
init(a, b) {
this.a = a;
this.b = b;
}
}
var derived = Derived(89, 32);
print derived.a;
print derived.b;
89
32
class Animal {
speak() {
return "Animal speaks";
}
makeSound() {
return "Generic sound";
}
communicate() {
return this.speak() + " : " + this.makeSound();
}
}
class Dog < Animal {
speak() {
return "Dog speaks";
}
makeSound() {
return "Woof";
}
}
class Puppy < Dog {
speak() {
return "Puppy speaks";
}
}
var animal = Animal();
var dog = Dog();
var puppy = Puppy();
print animal.communicate();
print dog.communicate();
print puppy.communicate();
Animal speaks : Generic sound
Dog speaks : Woof
Puppy speaks : Woof
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - AB0 · Жарамсыз базалық класты немесе кластың өзінен мұралануын анықтаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
// A class can't inherit from itself.
class Foo < Foo {} // expect compile error
$ ./your_program.sh run test.lox
[line 2] Error at 'Foo': A class can't inherit from itself.
fun A() {}
// A class can only inherit from a class.
class B < A {} // expect runtime error
print A();
print B();
Superclass must be a class.
[line 4]
var A = "class";
// A class can only inherit from a class
class B < A {} // expect runtime error
print B();
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - QI0 · Дұрыс дананы сақтап, базалық класс әдісін super арқылы табыңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Doughnut {
cook() {
print "Fry until golden brown.";
}
}
// Super can be used to call the overridden method
// of the parent class
class BostonCream < Doughnut {
cook() {
super.cook();
}
}
BostonCream().cook();
$ ./your_program.sh run test.lox
Fry until golden brown.
class Base {
method() {
print "Base.method()";
}
}
class Parent < Base {
method() {
super.method();
}
}
class Child < Parent {
method() {
super.method();
}
}
var parent = Parent();
parent.method();
var child = Child();
child.method();
Base.method()
Base.method()
Кезеңнің толық түпнұсқасы (ағылшын тілінде) - IB9 · Ішкі кластан тыс және жарамсыз ортадағы super қолданысын қабылдамаңыз.
Код пен тексеру мысалдары
Өз бағдарламаңызды мысалдармен салыстырыңыз. Командалар мен үлгі нәтижелер бастапқы жазылымда берілген.
class Foo {
cook() {
// Foo is not a subclass
super.cook(); // expect compile error
}
}
$ ./your_program.sh run test.lox
[line 4] Error at 'super': Can't use 'super' in a class with no superclass.
// super can't be used outside of a class
super.notEvenInAClass(); // expect compile error
[line 2] Error at 'super': Can't use 'super' outside of a class.
class A {}
class B < A {
method() {
// super must be followed by `.`
// and an expression
super; // expect compile error
}
}
[line 7] Error at ';': Expect '.' after 'super'.
Кезеңнің толық түпнұсқасы (ағылшын тілінде)
SynQ-ға сұрақ
SynQ-ға кіріс деректі, өз болжамыңызды және нақты нәтижені көрсетіңіз. Алдымен қай аралық мәнді тексеру керегін сұраңыз.
Оқу жолы
Қорытынды тапсырма
Қорытынды тапсырма
(2 + 3) * 4 өрнегінің токендерін, талдау ағашын және мәнін көрсетіңіз. Салыстыруды, лексикалық қатені, жабылмаған жақшаны және түрлі типтері бар арифметикалық амалды қосыңыз.
Қабылдау шарттары
Бірінші өрнек 20, ал 2 + 3 * 4 өрнегі 14 береді. Үш қатенің әрқайсысы қай кезеңде табылатынын анықтап, сол кезеңнің хабарын сақтаңыз.
Нәтижені түсіндіріңіз
Неліктен талдағыш қабылдаған кейбір өрнектерді орындау кезінде есептеу мүмкін болмайды?
Жобаны бағалау
Төрт өлшемнің әрқайсысы бір ұпай береді. Жобаны аяқтау үшін төртеуін де дәлелдеңіз. Кодты, іске қосу командаларын және нәтижелерді бірге сақтаңыз.
- Құжатталған команда арқылы жобаның таза көшірмесінен іске қосылады.
- Төмендегі шартта көрсетілген эталон нәтижені береді.
- Екінші кіріс пен бір шекаралық жағдай үшін күтілетін және нақты нәтиже жазылған.
- Төмендегі жобалық шешім орындалу ізіне, аралық мәнге не өлшеуге сүйеніп түсіндірілген.
Өзіңізді тексеріңіз
Lox тілінде 2 + 3 * 4 өрнегі қандай мән береді?
- 14
- 20
- 24
Жауапты көрсету
14. Көбейтудің басымдығы жоғары. Өрнек ағашының түбірі — қосу.
Дереккөздер мен лицензиялар
Оқу материалын бейімдеп, түсіндірмелерді дайындаған Digital Qazaqstan. Бастапқы практикумдардың авторы CodeCrafters.
interpreter
MIT License
Copyright (c) 2022 CodeCrafters
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.