Solucionario
Soluciones de referencia para los ejercicios de cada día. Intenta resolverlos por tu cuenta antes de consultar aquí.
Nota: estas soluciones son orientativas. Puede haber varias formas correctas de resolver cada ejercicio.
Día 1 · Hola, mundo
solucion.fa
escribir("Hola, Forja") Día 2 · Variables
solucion.fa
variable nombre = "Ana"
escribir(nombre) Día 3 · Tipos
solucion.fa
variable precio = 19.99
escribir(precio) Día 4 · Operadores
solucion.fa
escribir(6 * 7) // 42 Día 5 · Condicionales
solucion.fa
variable edad = 15
si (edad >= 18) {
escribir("Mayor")
} sino {
escribir("Menor")
} Día 6 · Bucles
solucion.fa
variable i = 1
mientras (i <= 3) {
escribir(i)
i = i + 1
} Día 7 · Funciones
solucion.fa
funcion suma(a, b) {
retornar a + b
}
escribir(suma(3, 4)) // 7 Día 8 · Texto
solucion.fa
variable saludo = "Hola, " + "Forja"
escribir(saludo) Día 9 · Arreglos
solucion.fa
variable numeros = [5, 10, 15]
escribir(numeros[1]) // 10 Día 10 · Mapas
solucion.fa
variable persona = { "nombre": "Ana", "edad": 30 }
escribir(persona["edad"]) // 30 Día 11 · Clases
solucion.fa
clase Rectangulo {
ancho
alto
constructor(ancho, alto) {
este.ancho = ancho
este.alto = alto
}
funcion area() {
retornar este.ancho * este.alto
}
}
variable r = nuevo Rectangulo(4.0, 5.0)
escribir(r.area()) // 20.0 Día 12 · Tipos enumerados
solucion.fa
constante ACTIVO = 0
constante INACTIVO = 1
constante SUSPENDIDO = 2
variable estado = SUSPENDIDO
si (estado == ACTIVO) {
escribir("Activo")
} sino si (estado == INACTIVO) {
escribir("Inactivo")
} sino {
escribir("Suspendido")
} Día 13 · Pattern matching
solucion.fa
funcion area(f) {
variable tipo = f["tipo"]
si (tipo == "circulo") {
retornar 3.1416 * f["radio"] * f["radio"]
} sino si (tipo == "rectangulo") {
retornar f["ancho"] * f["alto"]
} sino {
retornar 0.0
}
}
variable forma = {"tipo": "rectangulo", "ancho": 3.0, "alto": 4.0}
escribir(area(forma)) // 12.0 Día 14 · Genéricos
solucion.fa
funcion ultimo<T>(lista) {
retornar lista[longitud(lista) - 1]
}
escribir(ultimo([1, 2, 3])) // 3
escribir(ultimo(["a", "b"])) // b Día 15 · Traits
solucion.fa
rasgo Area {
funcion area()
}
clase Cuadrado {
lado
constructor(lado) {
este.lado = lado
}
}
implementa Area para Cuadrado {
funcion area() {
retornar este.lado * este.lado
}
} Día 16 · Resultado y Opción
solucion.fa
funcion dividir(a, b) {
si (b == 0.0) {
retornar Error("división por cero")
}
retornar Ok(a / b)
}
coincidir (dividir(10.0, 2.0)) {
caso Ok(v) -> { escribir(v) }
caso Error(e) -> { escribir(e) }
} Día 17 · Módulos
saludos.fa
funcion bienvenida(nombre) {
retornar "Bienvenido, " + nombre
} main.fa
importar "saludos"
funcion main() {
escribir(bienvenida("Ana"))
} Día 18 · Archivos
solucion.fa
importar "std/archivo"
funcion main() {
variable texto = ""
variable i = 1
mientras (i <= 5) {
texto = texto + a_texto(i) + "\n"
i = i + 1
}
escribir_archivo("numeros.txt", texto)
escribir(leer_archivo("numeros.txt"))
} Día 19 · JSON
solucion.fa
importar "std/json"
funcion main() {
variable libro = { "titulo": "Forja", "anio": 2025 }
escribir(stringificar(libro))
} Día 20 · Pruebas
solucion.fa
funcion es_par(n) {
retornar n % 2 == 0
}
@test
funcion test_par() {
asegurar(es_par(4))
}
@test
funcion test_impar() {
asegurar(es_par(3) == falso)
} Día 21 · Ownership
solucion.fa
funcion sumar_todos(numeros) {
variable total = 0
variable i = 0
mientras (i < longitud(numeros)) {
total = total + numeros[i]
i = i + 1
}
retornar total
}
variable datos = [1, 2, 3]
escribir(sumar_todos(&datos)) // 6
escribir(datos[0]) // 1 (sigue válido) Día 22 · Concurrencia
solucion.fa
importar "std/io"
funcion main() {
variable tx, rx = canal()
variable h1 = hilo { tx.enviar(1) retornar 0 }
variable h2 = hilo { tx.enviar(2) retornar 0 }
variable suma = rx.recibir() + rx.recibir()
h1.unir()
h2.unir()
escribir(suma) // 3
} Día 23 · Iteradores
solucion.fa
importar "std/io"
importar "std/colecciones"
funcion es_par(x) { retornar x % 2 == 0 }
funcion cuadrar(x) { retornar x * x }
funcion sumar(acc, x) { retornar acc + x }
funcion main() {
variable numeros = [1, 2, 3, 4, 5, 6]
variable pares = filtrar(numeros, &es_par)
variable cuadrados = mapa(pares, &cuadrar)
variable total = reducir(cuadrados, &sumar, 0)
escribir(total) // 56
} Día 24 · GUI
solucion.fa
importar "gui"
funcion al_pulsar() {
escribir("clic")
}
funcion main() {
tema_material("#6750A4", columna([
texto_grande("Demo"),
texto_mediano("Pulsa el botón"),
boton("Pulsar", &al_pulsar)
]))
} Día 25 · GUI avanzada
solucion.fa
importar "gui"
variable contador = 0
funcion incrementar() { contador = contador + 1 }
funcion decrementar() { contador = contador - 1 }
funcion main() {
tema_material("#1565C0", columna([
etiqueta_dinamica("contador"),
boton("+", &incrementar),
boton("−", &decrementar)
]))
} Día 26 · Red
solucion.fa
importar "std/servidor_web"
funcion responder(peticion) {
retornar "OK"
}
funcion main() {
variable servidor = crear_servidor(3000)
obtener(servidor, "/", &responder)
iniciar_servidor(servidor)
} Día 27 · SQLite
solucion.fa
importar "std/sqlite"
funcion main() {
variable db = sqlite.abrir("tareas.db")
sqlite.ejecutar(db, "CREATE TABLE IF NOT EXISTS tareas (id INTEGER, descripcion TEXT)")
sqlite.ejecutar(db, "INSERT INTO tareas VALUES (1, 'Comprar')")
sqlite.ejecutar(db, "INSERT INTO tareas VALUES (2, 'Estudiar')")
variable filas = sqlite.consultar(db, "SELECT descripcion FROM tareas")
variable i = 0
mientras (i < longitud(filas)) {
escribir(filas[i]["descripcion"])
i = i + 1
}
} Día 28 · Paquetes
terminal
forja nuevo mi_proyecto
cd mi_proyecto
forja add utilidades 1.2.0
forja install Día 29 · Rendimiento
solucion.fa
funcion main() {
variable suma = 0
variable i = 1
mientras (i <= 1000000) {
suma = suma + i
i = i + 1
}
escribir(suma)
} Día 30 · Proyecto final
El proyecto final es abierto: se evalúa con la rúbrica del capítulo. Una solución de referencia completa combina:
- Una clase
Tareay constantes para elEstado(por ejemploPENDIENTE,EN_CURSO,HECHA). - Persistencia con
std/sqlite. - Interfaz con
gui(columna, tarjeta, botones). - Manejo de errores con
Resultado. - Pruebas con
forja test.
Consejo: consulta la galería de ejemplos para ver apps completas de referencia.