Procedures, functions and structured programming · Procedimientos, funciones y programación estructurada
| English | Español |
|---|---|
| subroutines/ˈsʌbruːtiːnz/ | subrutinas |
| function/ˈfʌŋkʃn/ | función |
| procedure/prəˈsiːdʒə/ | procedimiento |
| structured programming/ˈstrʌktʃəd ˈprəʊɡræmɪŋ/ | programación estructurada |
| decomposition/ˌdiːkɒmpəˈzɪʃn/ | descomposición |
| parameters/pəˈræmɪtəz/ | parámetros |
| arguments/ˈɑːɡjuːmənts/ | argumentos |
| signature/ˈsɪɡnɪtʃə/ | firma |
| pass by value/pæs baɪ ˈvæljuː/ | paso por valor |
| pass by reference/pæs baɪ ˈrefrəns/ | paso por referencia |
| global variable/ˈɡləʊbl ˈveərɪəbl/ | variable global |
| local variable/ˈləʊkl ˈveərɪəbl/ | variable local |
| scope/skəʊp/ | alcance |
A tape of routines anyone could borrow
- By 1951 the EDSAC team in Cambridge kept a library of subroutines on punched paper tape: square roots, printing, logarithms. Any program could read one in and call it.
- The hard part was getting back. David Wheeler's trick, the "Wheeler jump", stored the return address so a routine could return to wherever it had been called from.
- Every function call you write today does the same thing, and every language library descends from that tape.
- This lesson is procedures and functions: how to define them, how to pass values in and out, and how to write one the way Paper 2 marks it.
Una cinta de rutinas que cualquiera podría tomar prestada
- Para 1951, el equipo EDSAC en Cambridge mantenía una biblioteca de subrutinas en cintas de papel perforado: raíces cuadradas, impresión, logaritmos. Cualquier programa podía leer una y llamarla.
- La parte difícil era saber cómo volver. El truco de David Wheeler, el "salto de Wheeler", almacenaba la dirección de retorno para que una rutina pudiera regresar a donde había sido llamada.
- Cada llamada a función que escribes hoy hace lo mismo, y cada biblioteca de lenguaje desciende de esa cinta.
- Esta lección trata sobre procedimientos y funciones: cómo definirlas, cómo pasar valores dentro y fuera, y cómo escribir una tal como la califica Paper 2.
Procedures and functions
- Structured programming 结构化编程 builds a program from small named subroutines 子程序, each with one job.
- A procedure 过程 is a named block that does an action and returns nothing:
PROCEDURE Greet(Name : STRING) … ENDPROCEDURE, run withCALL Greet("Ada"). - A function 函数 returns a value that becomes part of an expression:
FUNCTION Square(X : INTEGER) RETURNS INTEGER … RETURN X * X … ENDFUNCTION, used asResult ← Square(5) + 1.
A procedure does something; a function hands back a value
Procedimientos y funciones
- La programación estructurada construye un programa a partir de pequeñas subrutinas nombradas, cada una con un solo trabajo.
- Un procedimiento es un bloque nombrado que realiza una acción y no devuelve nada:
PROCEDURE Greet(Name : STRING) … ENDPROCEDURE, se ejecuta conCALL Greet("Ada"). - Una función devuelve un valor que forma parte de una expresión:
FUNCTION Square(X : INTEGER) RETURNS INTEGER … RETURN X * X … ENDFUNCTION, se usa comoResult ← Square(5) + 1.

Un procedimiento hace algo; una función devuelve un valor
The call stack: push on call, pop on return · La pila de llamadas: apilado en la llamada, desapilado al retorno
Calling a subroutine pushes a new frame on top; returning pops it and hands a value back to the caller. The call that is running is always the frame on top. · Llamar a una subrutina apila un nuevo marco en la parte superior; retornar lo desapila y devuelve un valor al llamador. La llamada que se está ejecutando es siempre el marco en la parte superior.
The key difference between a procedure and a function is that a function: · La diferencia clave entre un procedimiento y una función es que una función:
A function returns a value (used in an expression); a procedure performs an action and returns nothing. · Una función devuelve un valor (usado en una expresión); un procedimiento realiza una acción y no retorna nada.
A function Square(x) returns · retornos x * x. What does the call Square(5) return? · Una función Square(x) returns · retornos x * x. ¿Qué retorna la llamada Square(5)?
5 × 5 = 25 — the value the function hands back to its caller (the frame popped off the call stack). · 5 × 5 = 25 — el valor que la función le entrega a su llamador (el marco desapilado de la pila de llamadas).
Where each is appropriate
- A procedure where the same group of steps is needed at several points: validate an input, print a menu, swap two values. The steps are written once and called by name.
- A function where a single value must be calculated and then used in an expression: a total, a
TRUE/FALSEresult, the larger of two numbers. The return value replaces the call. - Use a subroutine when logic appears in more than one place, when a block has a clear named purpose, when the program is complex enough to need decomposition 分解, or when you want to test one piece on its own.
Dónde es apropiado cada uno
- Un procedimiento cuando se necesitan los mismos pasos en varios puntos: validar una entrada, imprimir un menú, intercambiar dos valores. Los pasos se escriben una vez y se llaman por nombre.
- Una función cuando se debe calcular un único valor y luego usarlo en una expresión: un total, un resultado
TRUE/FALSE, el mayor de dos números. El valor de retorno reemplaza a la llamada. - Usa una subrutina cuando la lógica aparece en más de un lugar, cuando un bloque tiene un propósito nombrado claro, cuando el programa es lo suficientemente complejo como para necesitar descomposición, o cuando quieres probar una pieza por sí sola.
A good reason to write a subroutine is that: · Una buena razón para escribir una subrutina es que:
Subroutines remove duplication, give a named purpose, and can be tested in isolation. · Las subrutinas eliminan la duplicación, dan un propósito nombrado y pueden probarse de forma aislada.
Parameters, arguments and the interface
- Parameters 参数 are the variables a subroutine declares to receive values; the values the caller supplies are the arguments 实参.
- The header is the first line:
PROCEDURE Name(Param : TYPE)orFUNCTION Name(Param : TYPE) RETURNS TYPE. The interface, or signature 签名, is the name, the parameters in order with their types, and the return type: everything a caller must know. - The return value is what a function passes back with
RETURN.
Parámetros, argumentos e interfaz
- Los parámetros son las variables que declara una subrutina para recibir valores; los valores que proporciona el llamador son los argumentos.
- El encabezado es la primera línea:
PROCEDURE Name(Param : TYPE)oFUNCTION Name(Param : TYPE) RETURNS TYPE. La interfaz, o firma, es el nombre, los parámetros en orden con sus tipos, y el tipo de retorno: todo lo que el llamador debe saber. - El valor de retorno es lo que una función pasa de vuelta con
RETURN.
Match each term to what it means. · Asocia cada término con lo que significa.
Function vs procedure = returns a value or not; by value vs by reference = copy or original. · Función vs procedimiento = devuelve un valor o no; por valor vs por referencia = copia o original.
Worked example: describe each term in a header
FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN.FUNCTION: a subroutine that returns a value.Pass2: the identifier used to call it.Count: the parameter, the identifier that receives the argument passed in.INTEGER: the data type of that parameter.RETURNS BOOLEAN: the data type of the value the function returns. Five parts, one mark each.
Ejemplo resuelto: describe cada término en un encabezado
FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN.FUNCTION: una subrutina que devuelve un valor.Pass2: el identificador usado para llamarla.Count: el parámetro, el identificador que recibe el argumento pasado.INTEGER: el tipo de datos de ese parámetro.RETURNS BOOLEAN: el tipo de datos del valor que devuelve la función. Cinco partes, una marca cada una.
In FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN, the identifier Count is the ____. · En FUNCTION Pass2(Count : INTEGER) RETURNS BOOLEAN, el identificador Count es el ____.
The parameter receives the argument the caller passes in and is used inside the function like a local variable. · El parámetro recibe el argumento que el llamador pasa y se usa dentro de la función como una variable local.
Pass by value and pass by reference
- Pass by value 传值: the routine receives a copy, so changes inside it do not reach the caller. Use it for inputs the routine only reads.
- Pass by reference 传引用: the routine receives a reference to the caller's own variable, so changes do reach the caller. Use it when the routine must update the argument, as in
Swap. - Cambridge writes the mode in the header,
BYVALorBYREF, before each parameter. If neither is written,BYVALis assumed.
A copy, or a link to the caller's variable
Paso por valor y paso por referencia
- Paso por valor: la rutina recibe una copia, por lo que los cambios internos no llegan al llamador. Úsalo para entradas que la rutina solo lee.
- Paso por referencia: la rutina recibe una referencia a la variable propia del llamador, por lo que los cambios sí llegan al llamador. Úsalo cuando la rutina debe actualizar el argumento, como en
Swap. - Cambridge escribe el modo en el encabezado,
BYVALoBYREF, antes de cada parámetro. Si no se escribe ninguno, se asumeBYVAL.

Una copia, o un enlace a la variable del llamador
Worked example: what is output?
Xis a reference toA, soAbecomes 8.Yis a copy ofB, so doublingYleavesBat 3.- The output is
8, 3. Had the header saidBYVAL X,Awould still be 5.
Ejemplo resuelto: ¿qué se imprime?
PROCEDURE Adjust(BYREF X : INTEGER, BYVAL Y : INTEGER)
X <- X + Y
Y <- Y * 2
ENDPROCEDURE
A <- 5
B <- 3
CALL Adjust(A, B)
OUTPUT A, B
Xes una referencia aA, así queAse convierte en 8.Yes una copia deB, así que duplicarYdejaBen 3.- La salida es
8, 3. Si el encabezado dijeraBYVAL X,Aseguiría siendo 5.
In the worked example, what is the value of A after CALL Adjust(A, B)? · En el ejemplo resuelto, ¿cuál es el valor de A después de CALL Adjust(A, B)?
X is passed BYREF, so X ← X + Y adds 3 to the caller's A: 5 + 3 = 8. B stays 3 because Y was a copy. · X se pasa BYREF, así que X ← X + Y suma 3 al A del llamador: 5 + 3 = 8. B permanece 3 porque Y fue una copia.
Local and global variables
- A local variable 局部变量 is declared inside a subroutine and exists only while it runs; a global variable 全局变量 is declared outside and is visible everywhere. The region where a name is visible is its scope 作用域.
- Locals are preferred: the same identifier can be reused elsewhere without a clash, the value cannot be changed accidentally by other parts of the program, the memory is released on return, and the subroutine is self-contained.
- A local is created new on every call, so it cannot carry a value between calls. A routine that builds up a string over repeated calls needs that string to be global, or passed
BYREF.
A global is visible everywhere; a local lives only inside its own subroutine
Variables locales y globales
- Una variable local se declara dentro de una subrutina y existe solo mientras esta corre; una variable global se declara fuera y es visible en todas partes. La región donde un nombre es visible es su alcance.
- Se prefieren las locales: el mismo identificador puede reutilizarse en otro lugar sin colisión, el valor no puede cambiarse accidentalmente por otras partes del programa, la memoria se libera al retornar, y la subrutina está autocontenida.
- Una local se crea nueva en cada llamada, por lo que no puede llevar un valor entre llamadas. Una rutina que construye una cadena a través de llamadas repetidas necesita que esa cadena sea global, o se pase
BYREF.

Una global es visible en todas partes; una local vive solo dentro de su propia subrutina
A local variable exists only inside the subroutine where it is declared, while a global variable is visible everywhere in the program. · Una variable local existe solo dentro de la subrutina donde se declara, mientras que una variable global es visible en todas partes del programa.
Keeping variables local limits their scope, avoids name clashes, and makes a subroutine testable on its own — globals are best avoided. · Mantener las variables locales limita su alcance, evita colisiones de nombres y hace que una subrutina sea probable de forma independiente; los globales deben evitarse.
Which are benefits of using local variables? Select all · todos that apply. · ¿Cuáles son beneficios de usar variables locales? Selecciona todas las que correspondan.
A local is created fresh on every call, so it cannot keep a value between calls. That is the one job a global, or a BYREF parameter, does instead. · Un local se crea fresco en cada llamada, por lo que no puede mantener un valor entre llamadas. Ese es el único trabajo que hace un global, o un parámetro BYREF, en cambio.
Turning a procedure into a function
- Change
PROCEDUREtoFUNCTIONand addRETURNS <type>to the header. - Replace the
OUTPUT, or theBYREFparameter that carried the result out, with aRETURNstatement. - Change every call so the returned value is used:
Result ← Unpack(Text)instead ofCALL Unpack(Text, Result).
Convertir un procedimiento en una función
- Cambia
PROCEDUREporFUNCTIONy añadeRETURNS <type>al encabezado. - Reemplaza el
OUTPUT, o el parámetroBYREFque transportaba el resultado hacia afuera, con una instrucciónRETURN. - Cambia cada llamada para que el valor retornado se utilice:
Result ← Unpack(Text)en lugar deCALL Unpack(Text, Result).
To convert a procedure into a function you change the header to FUNCTION with RETURNS, replace the OUTPUT with RETURN, and change the calls to use the returned value. · Para convertir un procedimiento en una función, cambias el encabezado a FUNCTION con RETURNS, reemplazas el OUTPUT con RETURN, y cambias las llamadas para usar el valor devuelto.
Three changes, three marks: the header, the RETURN, and the calls. · Tres cambios, tres marcas: el encabezado, el RETURN, y las llamadas.
Worked example: writing a module for Paper 2
- A global array
Score : ARRAY[1:50] OF INTEGERholds test scores. Write a functionCountAbove(Limit : INTEGER)that returns how many scores are greater thanLimit.
- The scheme awards a mark per feature: the header with parameter and return type, the local declarations, the counter initialised before the loop, the loop over every element, the condition with the right comparison, the update inside it, the constructs closed, and one
RETURNafter the loop. - An unfinished module still scores for every correct part, so write all of them.
Each part of a module answer carries its own mark
Ejemplo resuelto: escribir un módulo para Paper 2
- Un array global
Score : ARRAY[1:50] OF INTEGERmantiene las puntuaciones de exámenes. Escribe una funciónCountAbove(Limit : INTEGER)que devuelva cuántas notas son mayores queLimit.
FUNCTION CountAbove(BYVAL Limit : INTEGER) RETURNS INTEGER
DECLARE Index, Count : INTEGER
Count <- 0
FOR Index <- 1 TO 50
IF Score[Index] > Limit THEN
Count <- Count + 1
ENDIF
NEXT Index
RETURN Count
ENDFUNCTION
- El esquema otorga una marca por característica: el encabezado con parámetro y tipo de retorno, las declaraciones locales, el contador inicializado antes del bucle, el bucle sobre cada elemento, la condición con la comparación correcta, la actualización dentro de ella, las construcciones cerradas, y un
RETURNdespués del bucle. - Un módulo incompleto aún obtiene puntaje por cada parte correcta, así que escríbelas todas.

Cada parte de una respuesta de módulo lleva su propia marca
Put the parts of a Paper 2 module answer in the order they are written. · Coloca las partes de una respuesta de módulo Paper 2 en el orden en que se escriben.
Header, declare, loop, condition, update, return. Each part is a mark, even if another part is wrong. · Encabezado, declarar, bucle, condición, actualización, retorno. Cada parte es un punto, incluso si otra parte es incorrecta.
Marks that slip away
- A routine that must change the caller's variable needs
BYREFin its header; without itBYVALis assumed and the change is lost. - A function has one
RETURN, after the loop, andENDFUNCTION. ARETURNinside the loop ends it on the first element. DECLAREevery local, and initialise a counter or total to 0 before the loop.- "Efficient pseudocode" means moving work that does not change out of the loop, stopping a search at the first match, and not repeating a call whose result could be stored.
Marcas que se escapan
- Una rutina que debe cambiar la variable del llamador necesita
BYREFen su encabezado; sin él se asumeBYVALy el cambio se pierde. - Una función tiene un
RETURN, después del bucle, yENDFUNCTION. UnRETURNdentro del bucle lo termina en el primer elemento. - Declara (
DECLARE) cada local, e inicializa un contador o total a 0 antes del bucle. - "Pseudocódigo eficiente" significa mover el trabajo que no cambia fuera del bucle, detener una búsqueda en la primera coincidencia, y no repetir una llamada cuyo resultado pueda almacenarse.
To make a loop more efficient, a value that does not change with the loop counter should be: · Para hacer un bucle más eficiente, un valor que no cambia con el contador del bucle debería:
Hoisting a loop invariant out avoids recomputing the same value on every iteration. · Elevar un invariante del bucle evita recomputar el mismo valor en cada iteración.
You've got it
- a procedure does an action and is
CALLed; a function returns a value used in an expression - the header names the routine, its parameters with types and the return type; arguments are the values passed in
- BYVAL passes a copy (the default); BYREF lets the routine change the caller's variable
- prefer local variables; a local is new on every call, a global keeps its value
- a Paper 2 module: header, declarations, initialisation, loop, condition, update, closed constructs, one
RETURN
Lo has logrado
- un procedimiento realiza una acción y se llama con
CALL; una función devuelve un valor usado en una expresión - el encabezado nombra la rutina, sus parámetros con tipos y el tipo de retorno; los argumentos son los valores pasados
- BYVAL pasa una copia (el predeterminado); BYREF permite a la rutina cambiar la variable del llamador
- prefiere variables locales; una local es nueva en cada llamada, una global mantiene su valor
- un módulo Paper 2: encabezado, declaraciones, inicialización, bucle, condición, actualización, construcciones cerradas, un
RETURN