好的计算机编程语言应具备的三个特性
- 基础单元表达式,计算机编程语言最最最基础单元,理应具备的表达式
- 组合的能力,能够通过基础单元表达式组合成更复杂的元素
- 抽象的能力,能通过复杂的元素抽象成更高层的单元
基础单元表达式
加 减 乘 除。
其实加 减 乘 除才是最牛逼的接口,左边和右边提供输入参数,最后返回计算结果,又是最基础的可以组合成更复杂单元的基础单元表达式接口。
SICP javascript版本,可以在网页版解释运行环境中写代码
在线快乐地编写javascript代码并运行
137 + 349;
486
1000 - 334;
666
5 * 99;
495
10 / 4;
2.5
2.7 + 10;
12.7
3 * 2 * (3 - 5 + 4) + 27 / 6 * 10;
Naming and the Environment
const pi = 3.14159;
const radius = 10;
pi * radius * radius;
314.159
const circumference = 2 * pi * radius;
circumference;
62.8318
Evaluating Operator Combinations
One of our goals in this chapter is to isolate issues about thinking procedurally.
(2 + 4 * 6) * (3 + 12);
== In general, we shall see that recursion is a very powerful technique for dealing with
hierarchical, treelike objects.==
Compound Functions
- Numbers and arithmetic operations are primitive data and functions.
- Nesting of combinations provides a means of combining operations.
- Constant declarations that associate names with values provide a limited means of abstraction.
function square(x)
{
return x*x;
}
square(21);
square(2 + 5);
function square(x)
{
return x*x;
}
square(21);
square(2 + 5);
square(square(3));
// x² + y² can be expressed as
// square(x) + square(y)
function sum_of_squares(x,y)
{
return square(x) + square(y);
}
sum_of_squares(3,4);
25
// now we can use sum_of_squares as a building block in constructing further functions.
function f(a)
{
return sum_of_squares(a + 1,a * 2);
}
f(5);
136
上述计算模型 square及sum_of_squares都可以是外部领域模型,所以一个大型系统可以由很多外部领域模型组合成复杂功能。
突然间恍然大悟上面这个计算机中的精灵图:EVAL计算出规则APPLY的结果,计算得到的结果又再次成为规则APPLY的输入,然后EVAL又再次计算得到规则APPLY的结果
Conditional Expressions and Predicates
function abs(x)
{
return x >= 0 ? x : -x;
}
abs(3);
abs(-43);
function greater_or_equal(x,y)
{
return x > y || x === y;
}
greater_or_equal(3,4);
greater_or_equal(4,4);
greater_or_equal(6,2);
function greater_or_equal(x,y)
{
return !( x < y);
}
练习题
10;
5 + 3 + 4;
9 - 1;
6 / 2;
2 * 4 + (4 - 6);
const a = 3;
const b = a + 1;
a + b + a * b;
a === b;
b > a && b < a * b ? b : a;
a === 4 ? 6 : b === 4 ? 6 + 7 + a : 25;
exercise 1.1 exercise 1.2 exercise 1.3
(5 + 4 + (2 - (3 - (6 + 4 / 5)))) / (3 * (6 - 2) * (2 - 7));
function square(x)
{
return x * x;
}
function square_of_the_larger_two(x,y,z)
{
return x > y ?
(y > z ? (square(x) + square(y)) : (square(x) + square(z)))
:
(x > z ? (square(x) + square(y)) : (square(y) + square(z)));
}
square_of_the_larger_two(2,3,4);
square_of_the_larger_two(2,1,3);