Ir para o conteúdo
ou

Software livre Brasil

 Voltar a Blogosfera d...
Tela cheia Sugerir um artigo

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

27 de Agosto de 2010, 0:00 , por Software Livre Brasil - 0sem comentários ainda | Ninguém está seguindo este artigo ainda.
Visualizado 338 vezes

### add intro link to intro post ###

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)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                0 (x)
              6 BINARY_MULTIPLY
              7 RETURN_VALUE        

>>> dis.dis(square2)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                0 (x)
              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


Fonte: http://pedrokroger.net/blog/2010/08/sicp-in-python-1-1-the-elements-of-programming/

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.