Instructor:
What should be the basic building blocks of computations?
Is this Scala?
def f (x: Int) : Int = var y: Int = 0 if x!=0 then y=1 else y=2 yend f
Is this C?
int f (int x) { int y; if (x!=0) y=1; else y=2; return y;}
def f (x: Int) : Int = val y: Int = if x!=0 then 1 else 2 yend f
int f (int x) { int y = if (x!=0) 1 else 2; return y;}
if ... else
def f (x: Int) : Int = var y: Int = (x!=0 ? 1 : 2) yend f
if ...
int f (int x) { int y = x ? 1 : 2; return y;}
def f (x: Int) : Int = val y: Int = { var xx = x var z=0 while (xx>0) do {xx=xx-1; z=z+1} z } yend f
int f (int x) { int y = { int xx=x; int z=0; while (xx>0) {xx--; z++;} return z; } return y;}
def g (x: Int) : Int = var xx = x var z = 0 while xx>0 do { xx=xx-1; z=z+1 } zend gdef f (x: Int) : Int = val y = g(x) yend f
int g (int x) { int xx=x; int z=0; while (xx>0) { xx--; z++; } return z;}int f (int x) { int y = g(x); return y;}
mov eax, 5add eax, 6mov ebx, eax
5+6
f (1 + 2 * "hello".length)
Scala does not have statements, everything is an expression!
printf("hello");^^^^^^^^^^^^^^^ expression^^^^^^^^^^^^^^^^ statement
return 1+x; ^^^ expression^^^^^^^^^^^ statement
int count = 0;while (1) { int ch = getchar(); switch (ch) { case -1: return count; case 'a': count = count + 1; default: continue; }}
Cannot use statements verbatim as part of expressions Use functions to turn statements into expressions
x++
x += 2
x = (y = 5)
x -= (y += 5)
class C { private int x = 0; private int y = 0; public int f(int z) { x = x-z; return x; } public int g() { y = y+5; return y; }}C c = new C();c.f(c.g()); // same as x -= (y += 5)
int x = 1;printf ("%d\n", ++x); ////
int x = 1;printf ("%d\n", x++); ////
x = 1 + (y = 5); //
int x = 1;printf ("%d\n", (x = x + 1) + x); //
int x = 1;printf ("%d\n", ++x); // pre increment, prints 2// value of x is now 2
int x = 1;printf ("%d\n", x++); // post increment, prints 1// value of x is now 2
x = 1 + (y = 5); // assigns 5 to y and 6 to x
int x = 1;printf ("%d\n", (x = x + 1) + x); // no "sequence point", undefined! // in OOP often disguised: o.f() + o.g()
Scala { e1; e2; ...; en }
{ e1; e2; ...; en }
{ e1 e2 ... en}
C ( e1, e2, ..., en )
( e1, e2, ..., en )
( e1, e2, ... en)
e1
en-1
en
string s; while(read_string(s), s.len() > 5) { // do something }
int main () { int x = 5; x *= 2; printf ("%d\n", x);}
int main () { int x = 5; printf ("%d\n", (x *= 2, x)); // behavior defined because comma operator introduces sequence point}
e1, e2, ... en
e1 ? e2 : e3