Programação declarativa: fatos, regras e objetivos
Introduzido| English | Significado |
|---|---|
| fact/fækt/ | fato |
| declarative programming/dɪˈklærətɪv ˈprəʊɡræmɪŋ/ | programação declarativa |
| rule/ruːl/ | regra |
| goal/ɡəʊl/ | objetivo |
| backtrack/ˈbæktræk/ | retrocesso |
| unification/ˌjuːnɪfɪˈkeɪʃn/ | unificação |
Ask who can borrow a camera
- A media club keeps facts about its members and completed training. It wants to ask who can borrow a camera without writing a new loop for every question.
- Declarative programming 声明式编程 describes facts, rules and a goal 目标. A logic engine searches for values that make the goal true. The programmer still has to write correct rules; the engine does not read minds or club noticeboards.
Facts state what is known
- A fact 事实 is an assertion in the knowledge base. In
member(aya)., the predicatememberrelates one person to club membership.trained(aya, camera).relates a person to a piece of equipment. - This lesson uses Prolog-style notation: lowercase names are constants or predicates; uppercase names are variables. A full stop ends each fact or rule.
member(aya).
member(ben).
member(chen).
trained(aya, camera).
trained(chen, camera).
trained(ben, audio).
Dados os fatos member(ben). e trained(ben, audio)., qual das afirmações abaixo é um fato fornecido?
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
member(ben). é dado diretamente. A base de conhecimento não inclui treinamento em câmera para Ben, e can_borrow é um objetivo que uma regra deve provar.
A rule combines conditions
- A rule 规则 states when a conclusion holds. Read
:-as “if” and the comma as AND: a person may borrow a camera if they are a member and have camera training. Personnames the same variable in all three places. The engine must find one value that satisfies both conditions, not one member and a different trained person.
can_borrow(Person, camera) :- member(Person), trained(Person, camera).

Na regra can_borrow(Person, camera) :- member(Person), trained(Person, camera)., a vírgula entre as duas condições significa ____.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Tanto a filiação quanto o treinamento em câmera devem ser verdadeiros para a mesma Pessoa.
A goal asks a question
- The goal
?- can_borrow(aya, camera).asks for a yes/no result. The engine matches the rule and checksmember(aya)andtrained(aya, camera): both facts exist, so the goal succeeds. - The goal
?- can_borrow(Person, camera).asks for bindings of the variable. With this knowledge base, the answers arePerson = ayaandPerson = chen. These are goals to reason about; the displayed blocks are notation, not a runnable playground.
Os membros do clube são Aya, Ben e Chen. Aya e Chen têm treinamento em câmera; Ben tem apenas treinamento em áudio. A regra can_borrow(Person, camera) exige tanto a filiação quanto o treinamento em câmera. Quem satisfaz can_borrow(Person, camera)?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Aya e Chen possuem ambos os fatos necessários. Ben tem apenas treinamento em áudio.
A variável Person em member(Person) pode ter um valor diferente de Person em trained(Person, camera) durante uma prova.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Todas as ocorrências da mesma variável devem manter o mesmo vínculo nessa prova.
Worked example: trace a failed candidate
- Start with
Person = ben.member(ben)succeeds.trained(ben, camera)fails: the available training fact is for audio, which does not match camera. - The engine backtracks 回溯 to try another candidate,
Person = chen. Both conditions succeed. If more answers are requested, it continues searching; if no candidates remain, there are no more answers.
One binding must satisfy both conditions
Trace a fixed two-condition rule through supplied facts. A failed candidate can lead to another binding; a missing fact leaves a goal unproved.
Rastreie a busca restante após Aya já ter sido retornada.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
Ben é membro, mas carece de um fato correspondente de treinamento em câmera; o motor então tenta Chen.
Matching shares values across a rule
- Unification 合一 matches terms while consistently binding variables. Matching
trained(Person, camera)withtrained(chen, camera)bindsPersontochen; matching it withtrained(ben, audio)fails because the equipment differs. - A failed goal means it cannot be proved from these facts and rules. It does not prove that Ben has never used a camera in real life; the knowledge base may simply be incomplete.
A correspondência de trained(Person, camera) com trained(chen, camera) vincula Person a ____.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
O equipamento corresponde e o primeiro argumento fornece a associação chen.
Worked example: write a new rule
- Requirement: a mentor can help someone only when the mentor has camera training and the learner is a member. Add the rule below, then ask
?- can_help(aya, ben).. trained(aya, camera)andmember(ben)both exist, so the goal succeeds. This rule allows Aya to help herself too. If self-help must be excluded, the requirement needs another condition; do not invent it silently.
can_help(Mentor, Learner) :- trained(Mentor, camera), member(Learner).
Dados trained(aya, camera). e member(ben)., e a regra can_help(Mentor, Learner) :- trained(Mentor, camera), member(Learner)., can_help(aya, ben) tem sucesso?
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Aya tem treinamento de câmera e Ben é um membro; Ben não precisa ter treinamento de câmera para ser um aprendiz.
Marks that slip away
- A fact states something known; a rule derives a conclusion when its conditions hold; a goal asks whether a conclusion can be proved or which values make it true.
- Keep repeated variables consistent.
member(X), trained(Y, camera)would let an untrained member qualify because someone else has training. Changing a variable name can change the rule's meaning.
From a requirement to a proof
- Write facts, translate each requirement into a rule, and pose a goal. Trace each variable binding through every condition and try alternatives when a candidate fails.
- Here only Aya and Chen may borrow a camera. Ben's audio training is not camera training. Results follow from the supplied knowledge base, not a guess about real people.
O clube adiciona o fato trained(ben, camera). à base de conhecimento. Agora, quantas pessoas satisfazem can_borrow(Person, camera)?
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Ben já é membro e agora tem treinamento em câmera, portanto o objetivo tem três soluções: Aya, Ben e Chen. A regra não mudou; um novo fato alterou as respostas.
Uma meta falhada prova que o evento correspondente nunca ocorreu fora deste banco de conhecimento.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
Falha significa que a meta não pode ser provada a partir dos fatos e regras disponíveis.