Informatec Digital » Programme » 8 Amazing Tricks Using Logical Operators in Programming
- Logical operators are essential in programming for making decisions and controlling the flow of execution.
- Short-circuiting AND and OR optimizes efficiency by avoiding unnecessary evaluations.
- They facilitate the creation of complex queries in databases through combinations of conditions.
- They are fundamental in functional programming, allowing the composition of functions in a declarative manner.
1. Logical Operators in Programming
- AND (&&): Returns true if both operands are true.
- OR (||): Returns true if at least one of the operands is true.
- NOT (!): Inverts the truth value of the operand.
2. The Power of Short Circuit in Logic Operators
function esAdulto(edad) {
return edad && edad >= 18;
}
console.log(esAdulto(0)); // false
console.log(esAdulto(20)); // true
function saludar(nombre) {
nombre = nombre || "invitado";
console.log("Hola, " + nombre + "!");
}
saludar(); // Hola, invitado!
saludar("María"); // Hola, María!
3. Logical Operators in Control Structures
Simplifying Complex Conditionals
def puede_conducir(edad, tiene_licencia, esta_sobrio):
return edad >= 18 and tiene_licencia and esta_sobrio
# Uso
if puede_conducir(25, True, True):
print("Puedes conducir")
else:
print("No puedes conducir")
Using Logical Operators in Loops
def buscar_elemento(lista, elemento):
i = 0
while i < len(lista) and lista != elemento:
i += 1
return i if i < len(lista) else -1
# Uso
mi_lista =
print(buscar_elemento(mi_lista, 5)) # 2
print(buscar_elemento(mi_lista, 6)) # -1
4. Bitwise Logical Operators
The XOR Trick for Swapping Variables
void intercambiar(int *a, int *b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
// Uso
int x = 5, y = 10;
intercambiar(&x, &y);
printf("x = %d, y = %d\n", x, y); // x = 10, y = 5
Parity Checking with Logical Operators
bool es_par(int n) {
return !(n & 1);
}
// Uso
printf("%d es %s\n", 4, es_par(4) ? "par" : "impar"); // 4 es par
printf("%d es %s\n", 7, es_par(7) ? "par" : "impar"); // 7 es impar
5. Logical Operators in Functional Programming
Composition of Functions with Logical Operators
const esMayorDeEdad = edad => edad >= 18;
const tienePermiso = usuario => usuario.tienePermiso;
const puedeAcceder = usuario => esMayorDeEdad(usuario.edad) && tienePermiso(usuario);
// Uso
const usuario1 = { edad: 20, tienePermiso: true };
const usuario2 = { edad: 17, tienePermiso: true };
console.log(puedeAcceder(usuario1)); // true
console.log(puedeAcceder(usuario2)); // false
Logical Operators in Reactive Programming
import { fromEvent, merge } from 'rxjs';
import { map, filter } from 'rxjs/operators';
const clicks = fromEvent(document, 'click');
const moves = fromEvent(document, 'mousemove');
const clicksOrMoves = merge(
clicks.pipe(map(() => 'click')),
moves.pipe(map(() => 'move'))
);
clicksOrMoves.pipe(
filter(event => event === 'click' || (event === 'move' && Math.random() < 0.1))
).subscribe(console.log);
6. Performance Optimization with Logical Operators
Lazy Evaluation with Logical Operators
def operacion_costosa():
print("Ejecutando operación costosa...")
return True
def operacion_rapida():
print("Ejecutando operación rápida...")
return False
# Sin evaluación perezosa
if operacion_rapida() and operacion_costosa():
print("Ambas operaciones son verdaderas")
# Con evaluación perezosa
if operacion_costosa() and operacion_rapida():
print("Ambas operaciones son verdaderas")
Simplifying Boolean Expressions
# Antes de la optimización
if (a and b) or (a and c) or (b and c):
print("Condición cumplida")
# Después de la optimización
if a or b or c:
print("Condición cumplida")
7. Logical Operators in Databases
Complex Queries with Logical Operators
SELECT nombre, edad, salario
FROM empleados
WHERE (edad > 30 AND salario > 50000) OR (experiencia > 5 AND departamento = 'IT');
Optimizing Queries with Logical Operators
-- Consulta potencialmente lenta
SELECT *
FROM productos
WHERE categoria = 'electrónica' OR precio > 1000;
-- Consulta optimizada
SELECT *
FROM productos
WHERE categoria = 'electrónica'
UNION
SELECT *
FROM productos
WHERE precio > 1000 AND categoria != 'electrónica&#';
8. Logical Operators in Parallel and Concurrent Programming
Synchronization with Atomic Logic Operators
#include <stdatomic.h>
atomic_bool recurso_disponible = ATOMIC_VAR_INIT(true);
void usar_recurso() {
while (!atomic_compare_exchange_weak(&recurso_disponible, &(bool){true}, false)) {
// Esperar
}
// Usar el recurso
atomic_store(&recurso_disponible, true);
}
Logical Operators in Consensus Algorithms
def es_lider(nodo):
return nodo.termino_actual >= max(otros_nodos.termino_actual) y \
nodo.log_actualizado and \
nodo.votos_recibidos > len(otros_nodos) / 2
Conclusion
- Simplify control structures
- Optimize performance using techniques such as lazy evaluation
- Create complex queries in databases
- Facilitate functional and reactive programming
- Coordinate execution in parallel and concurrent systems
FAQ
- AND (&&): Returns true if both operands are true.
- OR (||): Returns true if at least one of the operands is true.
- NOT (!): Inverts the truth value of the operand.
- Using short-circuiting to avoid unnecessary evaluations.
- Simplifying complex boolean expressions.
- Implementing lazy evaluation to delay expensive calculations.
SELECT * FROM productos WHERE (precio > 100 AND categoria = 'electrónica') OR (descuento > 0.5)
- Compose more complex functions from simpler functions.
- Implement flow control structures in a declarative manner.
- Filter and transform data collections.
const numeros = ;
const pares = numeros.filter(n => n % 2 === 0);