Programming paradigms · Paradigmas de programação
| English | Português |
|---|---|
| paradigm/ˈpærədaɪm/ | paradigma |
| low-level/ləʊ ˈlevl/ | baixo nível |
| imperative/ɪmˈperətɪv/ | imperativo |
| declarative/dɪˈklærətɪv/ | declarativo |
| functional/ˈfʌŋkʃənl/ | funcional |
| pure functions/pjʊə ˈfʌŋkʃnz/ | funções puras |
| logic/ˈlɒdʒɪk/ | lógica |
The same program, written four ways
- Ask for all customers in the UK and a C programmer writes a loop over an array. A Haskell programmer writes a filter. A Prolog programmer states a rule and asks a question. An SQL user writes
SELECT * FROM Customer WHERE Country = 'UK'. - Only the first says how · como to do it. The others say what · o quê is wanted and leave the how to the machine, which is free to reorder the work, use an index, or run it on eight cores.
- Neither is better in general. What differs is which decisions the language takes away from you, and that is exactly what a paradigm 范式 is.
- This lesson is the paradigms the syllabus names: low-level 低级, imperative 命令式 and · e declarative 声明式.
Low-level programming
- Low-level programming works close to the hardware, in machine code or assembly language, with direct access to registers, memory addresses and individual instructions.
- Benefits: maximum control · controle and · e speed · velocidade, and the smallest possible code, which matters when there are only kilobytes of memory.
- Drawbacks: it is architecture-specific, so it must be rewritten for a different processor, and it is slow to write and hard to maintain.
- Used where the hardware must be commanded exactly: device drivers, firmware, embedded controllers, and the innermost loop of a real-time system.
- Practise immediate, direct, indirect, indexed and relative addressing in the assembly-language lesson. Its worked trace shows why the same operand can produce different results.
Which are true of low-level programming? Select all · todos that apply. · Quais são verdadeiras sobre a programação de baixo nível? Selecione todas as que se aplicam.
Control is bought with effort: assembly is slow to write and hard to maintain, which is why it is confined to drivers and firmware. · O controle tem custo: assembly é lento para escrever e difícil de manter, razão pela qual é restrita a drivers e firmware.
Imperative programming
- Imperative programming, also called procedural, is a sequence of commands that change the program's state: assignments, conditionals, loops and calls to procedures.
- The programmer specifies how · como the result is to be computed, step by step. The variables holding the state are the point.
- It is the style of Python, C, Java and pseudocode, and it is what almost everyone learns first.

One command after another, each changing what is stored
Imperative (procedural) programming is based on: · A programação imperativa (procedural) baseia-se em:
Imperative code gives step-by-step commands (assignments, loops, calls) that change state. · Código imperativo dá comandos passo a passo (atribuições, laços, chamadas) que alteram o estado.
Declarative programming
- Declarative programming states what · o quê is to be computed, not how · como. The runtime works out the steps.
- Functional 函数式 programming composes pure functions 纯函数, which have no side effects: the same input always produces the same output, and nothing outside the function changes. Haskell and Lisp are the examples.
- Logic 逻辑式 programming states facts and rules, and an engine answers queries by inference. Prolog is the example.
- SQL is the declarative language nearly everyone has met: the query says which rows are wanted, and the database decides how to find them.
Programming concept lab · Laboratório de conceito de programação
Connect examples to the programming idea they show. · Conecte exemplos à ideia de programação que eles mostram.
Declarative programming means you specify: · Programação declarativa significa que você especifica:
Declarative code (functional, logic, SQL) states the goal; the runtime decides the steps. · Código declarativo (funcional, lógica, SQL) declara a meta; a execução decide os passos.
A pure function (functional programming): · Uma função pura (programação funcional):
Purity means no side effects and a deterministic result, which makes functional code easy to reason about. · Pureza significa sem efeitos colaterais e resultado determinístico, o que facilita raciocinar sobre código funcional.
Declarative paradigms (functional, logic, SQL) state WHAT to compute and let the runtime decide how, whereas imperative code spells out every step. · Paradigmas declarativos (funcional, lógica, SQL) declaram O QUE calcular e deixam a execução decidir como, enquanto código imperativo detalha cada passo.
A SQL query says which rows you want, not how to scan the tables — the opposite of step-by-step imperative code. · Uma consulta SQL diz quais linhas você quer, não como varrer as tabelas — o oposto de código imperativo passo a passo.
A pure function always gives the same output for the same input and has no ____. · Uma função pura sempre produz a mesma saída para a mesma entrada e não tem ____.
That is what lets it be tested in isolation, run in parallel safely and have its result cached. · É isso que permite testá-la isoladamente, executá-la em paralelo com segurança e ter seu resultado em cache.
Worked example: identify the paradigm
FOR i ← 1 TO n : total ← total + A[i] : NEXT i— imperative: a sequence of commands changing the state held intotal.SELECT Name FROM Customer WHERE Country = 'UK'— declarative: it says which rows are wanted and not how to search for them.LDD 200 : ADD 201 : STO 202— low-level: assembly instructions addressing memory locations directly.parent(X, Y) :- father(X, Y).— declarative, specifically logic programming: a rule from which the engine infers answers.- Name the paradigm and · e the feature of the code that shows it.
Match each fragment to its paradigm. · Combine cada fragmento com seu paradigma.
Commands changing state, a statement of what is wanted, instructions addressing memory, and a rule for inference. · Comandos que alteram estado, uma declaração do que se deseja, instruções acessando memória e uma regra para inferência.
Comparing them
| Paradigm | Says | Strength · Força | Typical use |
|---|---|---|---|
| low-level | exact instructions | control, speed, size | drivers, firmware |
| imperative | how, step by step | direct and familiar | general programming |
| declarative | what is wanted | concise, the runtime optimises | queries, rules, data transformation |
- Modern languages mix · misturar them. Python is imperative but has functional features; SQL sits inside programs written imperatively. A paradigm is a style, not a wall.
Match each paradigm to its core idea. · Combine cada paradigma com sua ideia central.
Imperative says how step by step; OO models objects; functional uses pure functions; declarative states the goal. · Imperativo diz como passo a passo; OO modela objetos; funcional usa funções puras; declarativo declara a meta.
What is the essential difference between imperative and declarative programming? · Qual é a diferença essencial entre programação imperativa e declarativa?
Because the declarative version does not fix the how, the runtime may reorder the work, use an index or parallelise it. · Porque a versão declarativa não fixa o como, a execução pode reorganizar o trabalho, usar um índice ou paralelizá-lo.
Worked example: why side effects matter
- A pure function has no side effects. Explain one benefit.
- Because the same input always gives the same output and nothing outside changes, a pure function can be tested in isolation: no setup, no hidden state to arrange.
- It can also be run in parallel · paralelo safely, since two calls cannot interfere with each other, and its result can be cached.
- The contrast: an imperative routine that updates a global variable behaves differently depending on what ran before it, which is what makes such bugs hard to find.
Marks that slip away
- Imperative says how · como; declarative says what · o quê. That contrast is the answer to most questions here.
- Low-level's drawback is that it is architecture-specific and hard to maintain, not that it is "old".
- A pure function has no side effects and gives the same output for the same input. Both halves are needed.
- SQL is declarative. It is the example the exam most often uses, so recognise it.
You've got it
- a paradigm is a style of structuring code, and modern languages mix several
- low-level: machine code or assembly, direct hardware access, maximum control and speed, but architecture-specific and hard to maintain
- imperative: a sequence of commands changing state, specifying how · como; the style of Python, C and pseudocode
- declarative: states what · o quê is wanted and leaves the how to the runtime, as functional programming with pure functions, logic programming with facts and rules, and SQL