Ir para o conteúdo
ou

• 2017 (1)
• 2015 (59)
• 2014 (32)
• 2013 (15)
• 2012 (55)
• 2011 (228)
• 2010 (475)
• 2009 (249)

# pedro kroger: SICP in Python: 1.1 The Elements of Programming

27 de Agosto de 2010, 0:00 | Ninguém está seguindo este artigo ainda. The first chapter is about building abstractions with functions. I think it’s remarkable that a book for beginners (pretty smart beginners, but still) introduces assignment only in the third chapter (on page 220).

A powerful language needs to have the following things to allow the combination of simple ideas to form complex ideas:

• primitive expressions: the simplest entities in a language. Things like numbers and arithmetic operations and functions
• means of combination: nesting combinations, such as square(2 * square(3 + 7))
• means of abstraction: “compound elements can be named and manipulated as units”

Expressions, combinations

def is the simplest mean of abstraction. The following code creates a function and associates it with a name:

```def square(x):
return x * x```

It’s important to make this distinction (creating a function and naming it). We can create a function without a name (an anonymous function) with lambda:

`lambda x: x * x`

And we can give it a name:

`square2 = lambda x: x * x`

And, in fact, we can see that Python will generate the same bytecode for both functions:

```>>> import dis
>>> dis.dis(square)
6 BINARY_MULTIPLY
7 RETURN_VALUE

>>> dis.dis(square2)
6 BINARY_MULTIPLY
7 RETURN_VALUE```

Having defined square, we can use it in combinations:

```square(2 + 5)
square(square(7 + square (3)))```

And we can use square as a building block:

```def sum_of_squares(x, y):
return square(x) + square(y)

sum_of_squares(3, 4)

def f(a):
return sum_of_squares(a + 1, a * 2)```

aoeu

### 0sem comentários ainda

Enviar um comentário

Os campos são obrigatórios.

Se você é um usuário registrado, pode se identificar e ser reconhecido automaticamente.