Nand To Tetris (Jack): Simple if conditional with equality testing giving this error - "Expected - or ~ or ( in term" - nand2tetris

class Main {
function void main() {
var String foo;
let foo = "bar";
if (foo == "bar") {
do Output.printString("true");
}
else {
do Output.printString("false");
}
return;
}
}
I get the error: Expected - or ~ or ( in term.
Full output:
code/nand2tetris » tools/JackCompiler.sh projects/09/Test
Compiling /Users/adamzerner/code/nand2tetris/projects/09/Test
In Main.jack (line 6): In subroutine main: Expected - or ~ or ( in term
code/nand2tetris »
What does the error mean?

The issue is that I used == instead of =. In Jack, equality is tested for using a single equals rather than a double or triple (double/triple equals is conventional in other languages).
See bullet point 7 in slide 22 of the Chapter 9 PDF for documentation saying that equality comparison is done with a single equals.
See SquareGame.jack line 40 in the course software for an example.
The following code compiles without error. It doesn't give the expected output, but the reason for that is a separate topic.
class Main {
function void main() {
var String foo;
let foo = "bar";
if (foo = "bar") {
do Output.printString("true");
}
else {
do Output.printString("false");
}
return;
}
}

Related

What is the point of diverging functions in Rust?

I have read several answers on SO already, and gathered these use-cases:
When a function panic!s
When a function has an infinite loop in it
But it is still unclear to me why we need to define the function like this:
fn func() -> ! {
panic!("Error!");
}
if it will work the same way as this (without the exclamation sign):
fn func() {
panic!("Error!");
}
and at the same time, why do we need to use ! in functions with infinite loops? It look like this signature doesn't bring any real usage information.
The main difference between these signatures boils down to the fact that ! can coerce into any other type, and thus is compatible with any other type (since this code path is never taken, we can assume it to be of any type we need). It's important when we have multiple possible code paths, such as if-else or match.
For example, consider the following (probably contrived, but hopefully clear enough) code:
fn assert_positive(v: i32) -> u32 {
match v.try_into() {
Ok(v) => v,
Err(_) => func(),
}
}
When func is declared to return !, this function compiles successfully. If we drop the return type, func will be declared as returning (), and the compilation breaks:
error[E0308]: `match` arms have incompatible types
--> src/main.rs:8:19
|
6 | / match v.try_into() {
7 | | Ok(v) => v,
| | - this is found to be of type `u32`
8 | | Err(_) => func(),
| | ^^^^^^ expected `u32`, found `()`
9 | | }
| |_____- `match` arms have incompatible types
You can also compare this with definition for Result::unwrap:
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
}
}
Here, unwrap_failed is returning !, so it unifies with whatever type is returned in Ok case.
The compiler knows that anything that follows a diverging expression (w.r.t. evaluation order) is unreachable. It can use this information to avoid false negatives when it comes to deciding whether a local variable is initialized or not.
Consider the following example:
use rand; // 0.8.4
fn main() {
let foo;
if rand::random::<bool>() {
foo = "Hello, world!";
} else {
diverge();
}
println!("{foo}");
}
fn diverge() {
panic!("Crash!");
}
We declare a variable foo, but we only initialize it in one branch of the if expression. This fails to compile with the following error:
error[E0381]: borrow of possibly-uninitialized variable: `foo`
--> src/main.rs:10:15
|
10 | println!("{foo}");
| ^^^^^ use of possibly-uninitialized `foo`
However, if we change the definition of our diverge function like this:
fn diverge() -> ! {
panic!("Crash!");
}
then the code successfully compiles. The compiler knows that if the else branch is taken, it will never reach the println! because diverge() diverges. Therefore, it's not an error that the else branch doesn't initialize foo.

how to use Generics in functions and pattern matching in rust?

I'm solving a little math problem called the Syracuse problem (3n+1 problem).
Thing is i want my function to work for 2 types, one is u64 the other is a struct that extends the size of u64 by containing 2 u64 that i called U128.
my u64 function looks like this
fn syracuse(n: u64) -> u64 {
match n % 2 {
0 => n / 2,
1 => 3 * n + 1,
_ => 1,
}
}
I've tried implementing a trait to my U128 and u64.
fn syracuse<T>(n: T) -> T where T : Add +Mul+Div+Rem + Basic0123 {
match n % Basic0123::two() {
Basic0123::zero() => n / Basic0123::two(),
Basic0123::one() => Basic0123::three() * n + Basic0123::one(),
_ => Basic0123::one(),
}
}
It doesn't compile, the pattern matching doesn't like this. I'm new to rust and i'm trying to understand if creating a function with generic typing is okay for this problem that only treats 2 different types the DRY way or i should just stick with simply rewriting the function for the U128 type?
I'm just going to assume most of the stuff in the comments has been dealt with and you're back to using the std::u128 primitive type rather than your own.
The proper way to implement the Syracuse conjecture on a generic type is as follows:
fn syracuse<T>(n: T) -> T
where T : Copy + Eq + Add<Output = T> + Mul<Output = T> + Div<Output = T> + Rem<Output = T> + From<u32> {
let zero:T = 0.into();
match n % 2.into() == zero {
true => n/(2.into()),
false => n * (3.into()) + 1.into()
}
}
In order of appearance:
Copy is required because we did not require Rem on &T, but on T
All the Output type specifications are so we do not implicitly change type - an operation on T will always map to T
We are requiring Eq so we can compare the result of the remainder
We are requiring From<u32> so we can into() every single numerical constant
A working version can be found here

javascript for statement and operator in

There is a note in ecma-262 Specification:
The [In] grammar parameter is needed to avoid confusing the in operator in a relational expression with the in operator in a for statement.
so are there any ways to make
for (let i in x in y) {
console.log(i);
}
print something ?
Parentheses will make it parse more clearly:
for (let i in (x in y)) {
console.log(i);
}
But it actually parses fine without them. The disambiguation is needed for the other kind of for loop:
for (let a = b in c; false;); // does not parse
for (let a = (b in c); false;); // parses fine
The reason your snippet isn't printing anything is that x in y always results in a boolean, so it's not going to print anything unless you've defined enumerable properties on Boolean.prototype or Object.prototype:
Boolean.prototype.foo = 'bar';
for (let a in ('' in {})) {
console.log(a);
} // prints 'foo'

How to specify a return of an array of unknown size in Chapel

I tried to rely on type inference for a function with signature:
proc mode(data: [?]int)
but the compiler said it could not resolve the return type (which is a warning in in itself I guess given there are only two return statements). I tried:
proc mode(data: [?]int): [?]int
but the compiler then said there was an internal error:
internal error: CAL0057 chpl Version 1.13.1.518d486
What is the correct way of specifying that the length of an array returned by a function can only be known at run time?
If the domain/size of the array being returned cannot be described directly in the function prototype, I believe your best bet at present is to omit any description of the return type and lean on Chapel's type inference machinery to determine that you're returning an array (as you attempted). For instance, here is a procedure that reads in an array of previously unknown size and returns it:
proc readArrFromConsole() {
var len = stdin.read(int);
var X: [1..len] real;
for x in X do
x = stdin.read(real);
return X;
}
var A = readArrFromConsole();
writeln(A);
Running it and typing this at the console:
3 1.2 3.4 5.6
Generates:
1.2 3.4 5.6
Your question mentions multiple return statements, which opens up the question about how aggressively Chapel unifies types across distinct arrays. A simple example with multiple arrays of the same type (each with a unique domain, size, and bounds) seems to work:
proc createArr() {
var len = stdin.read(int);
if (len > 0) {
var X: [1..len] real;
return X;
} else {
var Y: [-1..1] real;
return Y;
}
}
var A = createArr();
writeln(A);
To understand why the compiler couldn't resolve the return type in your example may require more information about what your procedure body / return statements contained.
I've come across this from time to time in recursive functions, in situations where omitting the return type fails; in this case I create a record which is an array with its domain, e.g.:
record stringarray {
var D: domain(1);
var strs : [D] string;
}
and then define the recursive array to return one of those records:
proc repeats() : stringarray {
var reps: stringarray;
//...
for child in children do {
childreps = child.repeats();
for childrep in childreps do
reps.push_back(childrep);
}
//...
return reps;
}

Scala DSL and Block as function argument

How can i implement that DSL construction at Scala
def objeects(f: => Int):Int {
println(f)
// ??? evaluate every function, that f contain in the block.
}
manytimes {
1+1
2+1
3+1
}
At result we need get one computation for every functions as we pass in block to that method.
9
Your block is one function:
{
1+1 // calculate 2 and throw away
2+1 // calculate 3 and throw away
3+1 // return 4
}
This is simply how Scala syntax works, and you can't change it. Indeed, if you could, what would you expect to happen in this case?
manytimes {
val x = 1
val y = 2
x + y
}
Will
manytimes(1+1)(2+1)(3+1)
be good enough for your purposes?
After many hours of searching i found some really great components, that can help me solve my problem.
multifunc {
println(1)
println(2)
}
// output
Expr[c.universe.Tree](func.tree)
scala.this.Predef.println(2) // <-- it my case its the second and last elem
class scala.reflect.internal.Trees$Apply // <-- we can apply it as usual
class scala.reflect.internal.Trees$Block
tree<<
class scala.reflect.internal.Trees$EmptyTree$
<empty>
Macro for that:
import scala.language.experimental.macros
import scala.reflect.macros._
def multifunc[A](func: => A) = macro _multifunc[A]
def _multifunc [A](c: BlackboxContext)(
func: c.Expr[A]
): c.Expr[Unit] = {
import c.universe._
val tree = func.tree match {
case q"($i: $t) => $body" => q"""
println($body)
println($body.getClass)
$body
"""
case _ => q""
}
println(func.tree.children.last) // <-- accessor to AST children
println(func.tree.children.last.getClass)
println(func.tree.getClass)
println("tree<<")
println(tree.getClass)
println(tree)
c.Expr(tree)
}