├── README.md
├── erratas.md
├── img
└── libro-01.jpg
├── material
├── capítulo_1
│ └── figuras
│ │ ├── 1.2blancoynegro.png
│ │ ├── 1.3blancoynegro.png
│ │ ├── 1.4blancoynegro.png
│ │ └── 1.5blancoynegro.png
├── capítulo_10
│ └── ejemplos
│ │ ├── funciones-identity.hs
│ │ ├── funciones-increment-2.hs
│ │ ├── funciones-increment.hs
│ │ ├── funciones-sumThreeNumber.hs
│ │ ├── funciones-sumTwoNumber.hs
│ │ ├── guards-ejemplo1.hs
│ │ ├── guards-ejemplo2.hs
│ │ ├── lista-fromNumberToListString.hs
│ │ ├── lista-fromNumbersToString.hs
│ │ ├── lista-sumList.hs
│ │ ├── pattern-matching-diferentes-posiciones.hs
│ │ ├── pattern-matching-f.hs
│ │ ├── pattern-matching-fibonacci.hs
│ │ ├── tupla-ejemplo1.hs
│ │ ├── tupla-ejemplo2.hs
│ │ └── tupla-ejemplo3.hs
├── capítulo_11
│ └── figuras
│ │ ├── 11.1.png
│ │ └── 11.2.png
├── capítulo_12
│ ├── ejemplos
│ │ ├── funciones-getFirstElement.py
│ │ ├── funciones-getFirstElement.rkt
│ │ ├── funciones-op.py
│ │ ├── funciones-op.rkt
│ │ ├── funciones-puras-copy-list-recursiva.py
│ │ ├── funciones-puras-copy-list.py
│ │ ├── funciones-puras-copy-list.rkt
│ │ ├── funciones-sum.py
│ │ ├── funciones-sum.rkt
│ │ ├── higher-order-function-filter.py
│ │ ├── higher-order-function-filter.rkt
│ │ ├── higher-order-function-increment.py
│ │ ├── higher-order-function-increment.rkt
│ │ ├── higher-order-function-map.py
│ │ ├── higher-order-function-map.rkt
│ │ ├── higher-order-function-reduce.py
│ │ ├── higher-order-function-reduce.rkt
│ │ ├── lazy-list-infinite.py
│ │ ├── lazy-list-infinite.rkt
│ │ ├── lista-ejemplo.py
│ │ ├── lista-ejemplo.rkt
│ │ ├── pattern-matching-checking-expr-and-result.rkt
│ │ ├── pattern-matching-checking-expr-struct.py
│ │ ├── pattern-matching-checking-expr-struct.rkt
│ │ ├── pattern-matching-evaluate-pattern.py
│ │ ├── recursividad-fact.py
│ │ ├── recursividad-fact.rkt
│ │ ├── recursividad-fib.py
│ │ ├── recursividad-fib.rkt
│ │ ├── recursividad-pow.py
│ │ ├── recursividad-pow.rkt
│ │ ├── transparencia-referencial-concat-list.py
│ │ └── transparencia-referencial-concat-list.rkt
│ └── figuras
│ │ ├── 12.1.png
│ │ ├── 12.2.png
│ │ ├── 12.3.png
│ │ ├── 12.4.png
│ │ ├── 12.5.png
│ │ ├── 12.6.png
│ │ ├── 12.7.png
│ │ ├── 12.8.png
│ │ └── 12.9.png
├── capítulo_13
│ ├── ejemplos
│ │ ├── estructura-de-tipo-ejemplo1.py
│ │ ├── estructura-de-tipo-ejemplo1.rkt
│ │ ├── estructura-de-tipo-operaciones-acceso.py
│ │ ├── estructura-de-tipo-operaciones-acceso.rkt
│ │ ├── generate-list.py
│ │ ├── generate-list.rkt
│ │ ├── hashtable-ejemplo1.py
│ │ ├── hashtable-ejemplo1.rkt
│ │ ├── hashtable-ejemplo2.py
│ │ ├── hashtable-ejemplo2.rkt
│ │ ├── hashtable-operaciones-búsqueda.py
│ │ ├── hashtable-operaciones-búsqueda.rkt
│ │ ├── hashtable-operaciones-eliminación.py
│ │ ├── hashtable-operaciones-eliminación.rkt
│ │ ├── hashtable-operaciones-inserción.py
│ │ ├── hashtable-operaciones-inserción.rkt
│ │ ├── operador-búsqueda.bak
│ │ ├── operador-búsqueda.py
│ │ ├── operador-búsqueda.rkt
│ │ ├── operador-eliminación.py
│ │ ├── operador-eliminación.rkt
│ │ ├── operador-filtrado.py
│ │ ├── operador-filtrado.rkt
│ │ ├── operador-inserción.py
│ │ ├── operador-inserción.rkt
│ │ ├── par-ejemplo1.py
│ │ ├── par-ejemplo1.rkt
│ │ ├── par-operaciones-acceso.py
│ │ ├── par-operaciones-acceso.rkt
│ │ ├── reverse-list.py
│ │ ├── reverse-list.rkt
│ │ ├── slicing.py
│ │ ├── tree-ejemplo1.py
│ │ ├── tree-ejemplo1.rkt
│ │ ├── tree-ejemplo2.py
│ │ ├── tree-ejemplo2.rkt
│ │ ├── tree-operaciones-búsqueda.py
│ │ ├── tree-operaciones-búsqueda.rkt
│ │ ├── tree-operaciones-cantidad-elementos.py
│ │ └── tree-operaciones-cantidad-elementos.rkt
│ └── figuras
│ │ ├── 13.1.png
│ │ ├── 13.2.png
│ │ ├── 13.3.png
│ │ ├── 13.4.png
│ │ └── 13.5.png
├── capítulo_14
│ ├── ejemplos
│ │ ├── hanoi.py
│ │ ├── hanoi.rkt
│ │ ├── huffman-encoding.rkt
│ │ ├── huffman.py
│ │ ├── huffman.rkt
│ │ ├── karp-rabin.py
│ │ ├── karp-rabin.rkt
│ │ ├── msort.py
│ │ ├── msort.rkt
│ │ ├── qsort.py
│ │ └── qsort.rkt
│ └── figuras
│ │ ├── 14-ejercicio.png
│ │ ├── 14.1.png
│ │ ├── 14.10.png
│ │ ├── 14.11.png
│ │ ├── 14.12.png
│ │ ├── 14.2.png
│ │ ├── 14.3.png
│ │ ├── 14.4.png
│ │ ├── 14.5.jpg
│ │ ├── 14.6.png
│ │ ├── 14.7.png
│ │ ├── 14.8.png
│ │ └── 14.9.png
├── capítulo_15
│ ├── ejemplos
│ │ ├── interpreter.rkt
│ │ ├── lexer.rkt
│ │ ├── parser.rkt
│ │ ├── test.rkt
│ │ └── while.rkt
│ └── figuras
│ │ ├── 15.1.PNG
│ │ ├── 15.2.PNG
│ │ ├── 15.3.PNG
│ │ ├── 15.4.PNG
│ │ └── 15.5.PNG
├── capítulo_3
│ └── figuras
│ │ └── 3.1.png
├── capítulo_5
│ └── figuras
│ │ ├── 5.1-blancoynegro.png
│ │ ├── 5.1.png
│ │ ├── 5.10.png
│ │ ├── 5.10blancoynegro.png
│ │ ├── 5.11.png
│ │ ├── 5.11blancoynegro.png
│ │ ├── 5.2.png
│ │ ├── 5.2blancoynegro.png
│ │ ├── 5.3.png
│ │ ├── 5.3blancoynegro.png
│ │ ├── 5.4.png
│ │ ├── 5.4blancoynegro.png
│ │ ├── 5.5.png
│ │ ├── 5.5blancoynegro.png
│ │ ├── 5.6.png
│ │ ├── 5.6blancoynegro.png
│ │ ├── 5.7.png
│ │ ├── 5.7blancoynegro.png
│ │ ├── 5.8.png
│ │ ├── 5.8blancoynegro.png
│ │ ├── 5.9.png
│ │ └── 5.9blancoynegro.png
├── capítulo_6
│ └── figuras
│ │ ├── 6.1.png
│ │ ├── 6.2.png
│ │ ├── 6.3.png
│ │ ├── 6.4.png
│ │ └── 6.4blancoynegro.png
├── capítulo_7
│ └── figuras
│ │ ├── 7.1.png
│ │ ├── 7.1blancoynegro.png
│ │ ├── 7.2.png
│ │ ├── 7.2blancoynegro.png
│ │ ├── 7.3.png
│ │ ├── 7.3blancoynegro.png
│ │ ├── 7.4.png
│ │ ├── 7.4blancoynegro.png
│ │ ├── 7.5.png
│ │ ├── 7.5blancoynegro.png
│ │ ├── 7.6.png
│ │ └── 7.6blancoynegro.png
├── capítulo_8
│ └── figuras
│ │ ├── 8.1.png
│ │ └── 8.1blancoynegro.png
├── capítulo_9
│ └── figuras
│ │ ├── 9.1.png
│ │ └── 9.1blancoynegro.png
└── ejercicios_resueltos
│ ├── capítulo_12
│ ├── ex-12-1.py
│ ├── ex-12-1.rkt
│ ├── ex-12-2.rkt
│ └── ex-12-3.hs
│ ├── capítulo_13
│ ├── ex-13-1.rkt
│ ├── ex-13-2.rkt
│ ├── ex-13-3.rkt
│ ├── ex-13-4.rkt
│ └── ex-13-5.rkt
│ ├── capítulo_14
│ ├── ex-14-1.rkt
│ ├── ex-14-2.rkt
│ └── ex-14-3.hs
│ └── capítulo_5
│ └── respuestas.md
└── recomendaciones.md
/README.md:
--------------------------------------------------------------------------------
1 | # Computación y programación funcional
2 | #### Introducción al cálculo lambda y programación funcional usando Racket y Python. Marcombo, 2021.
3 |
4 |
5 | ## Actualización
6 | - 8 de Agosto 2021. Este artículo es la continuación al libro: https://www.researchgate.net/publication/354765192_Introduccion_a_la_programacion_funcional_usando_Haskell_y_Agda
7 | - 28 de Julio 2021. Se corrige un error en el código del capítulo 12: [funciones-puras-copy-list-recursiva.py](material/cap%C3%ADtulo_12/ejemplos/funciones-puras-copy-list-recursiva.py). Pág. 187.
8 | - 31 de mayo 2021. Se añade una sección de [fe de erratas](erratas.md).
9 | - 18 de febrero 2021. Añadí una sección con lecturas recomendadas. Véase [aquí](recomendaciones.md).
10 | - 13 de febrero 2021. Se han añadido las respuestas a los ejercicios del capítulo 5. Véase [aquí](material/ejercicios_resueltos/capítulo_5/respuestas.md).
11 |
12 |
13 | ## Sipnosis
14 |
15 |
16 |
17 | La **programación funcional** ofrece diversas ventajas a la hora de construir software: reducción de errores, manejo eficiente de datos en entornos concurrentes y paralelos, y un gran respaldo teórico. No obstante, muchos programadores fracasan en su intento de adentrarse en ella por ir directamente a aprenderla usando un lenguaje de programación (tecnología), con lo que omiten la teoría y el contexto histórico que le dio origen.
18 |
19 | Este libro incluye una introducción sobre qué son la computación y la programación en pos de delimitar su campo de acción. En segundo lugar, presenta el **cálculo lambda**, el modelo de computación que influenció a la programación funcional en los años cuando ni siquiera existían los lenguajes de programación, ni mucho menos los ordenadores digitales. Para concluir, el libro emplea los lenguajes de programación **Racket** y **Python** para enseñar las diversas características de la programación funcional, sus fortalezas y debilidades, y cómo ellas pueden combinarse con otros paradigmas. Con todo ello, aprenderá:
20 |
21 | * La visión general de la computación, la programación y los lenguajes de programación.
22 | * Los fundamentos que subyacen a la programación funcional, como el cálculo lambda.
23 | * Las diferencias entre el cálculo lambda libre de tipos y tipado.
24 | * La aplicación de estos conceptos en un lenguaje de programación de estirpe funcional, como lo es Racket, y en otro de uso masivo, como Python.
25 | * El diseño y la construcción de un pequeño lenguaje de programación usando el enfoque funcional.
26 |
27 | Si tiene un mínimo conocimiento en programación y desea adentrarse en **otra forma de pensar y construir sistemas computacionales**, donde viven conceptos como reducción, funciones puras, transparencia referencial, búsqueda de patrones, entre otros, no espere más para hacerse con este libro. Gracias a él no descubrirá tan solo la programación funcional, sino que ampliará su perspectiva con respecto a la computación desde una óptica sistémica y libre de dogmas.
28 |
29 | **[Ver índice](https://docdro.id/u5lnpgj)**
30 |
31 |
32 | ## Sobre este repositorio
33 |
34 | En este repositorio se encuentra los códigos de ejemplos presentados en el libro, junto a sus figuras. Dentro de la carpeta [material](material/) se divide el contenido por cada capítulo. A su vez, dentro de la carpeta que refiere a cada capítulo existen dos: ejemplos (códigos) y figuras.
35 |
36 | ### Códigos de ejemplos
37 |
38 | #### Requisitos
39 |
40 | El libro usa las últimas versiones de cada lenguaje al momento de escribirlo:
41 |
42 | - Racket (versión 7.7, [descargar](https://download.racket-lang.org/))
43 | - Python (versión 3.8.2, [descargar](https://www.python.org/downloads/))
44 | - Haskell (versión 8.6.5, [descargar](https://www.haskell.org/platform/))
45 |
46 | (Los códigos de ejemplo fueron probados para esas versiones; de todas formas, para versiones posteriores no debería haber problemas en ejecutar cada ejemplo, ya que no se utilizan caracteristicias muy especificas, sino más bien genericas. Pero, en caso de ocurrir algún error, por favor ir a contacto o cree una issue.)
47 |
48 |
49 | Los códigos disponibles son los que aparecen en la **parte III** del libro. Agrupados por nombre de _algoritmo_ o _función_ presentada, para **Racket** (.rkt) y **Python** (.py). (Excepto para el capítulo 10 donde se presenta Haskell, leer más abajo.)
50 |
51 | Por ejemplo, para el algoritmo karp-rabin que se presenta en el capítulo 14 existen dos ficheros: [karp-rabin.rkt](material/capítulo_14/ejemplos/karp-rabin.rkt) y [karp-rabin.py](material/capítulo_14/ejemplos/karp-rabin.py) que son los dos códigos presentados en el libro, para cada lenguaje de programación.
52 |
53 | Por otro lado, los códigos de **Haskell** que solo aparecen en el capítulo 10, tienen la extensión .hs y están [aquí](material/capítulo_10/ejemplos).
54 |
55 | **Nota:** También puede usar IDE online para cada uno: https://ideone.com/, en caso de tener algún problema en la instalación de algún lenguaje.
56 |
57 |
58 |
59 | ### Figuras
60 |
61 | Dentro de cada capítulo se encuentra la carpeta figuras. Donde todas ellas siguen la misma enumeración del libro.
62 |
63 | ### Intérpretes para el cálculo lambda
64 |
65 | * [λ Calculus Interpreter](https://jacksongl.github.io/files/demo/lambda/)
66 |
67 | ### Contacto
68 |
69 | En caso de cualquier inconveniente o sugerencia, por favor escribir a: camilochs@gmail.com
70 |
--------------------------------------------------------------------------------
/erratas.md:
--------------------------------------------------------------------------------
1 | ### Fe de Erratas
2 |
3 | | Nº | Fecha | Página | Error | Solución | Nota |
4 | |----------|:------:|:-------------:|:------:|:-----------------:|:------:|
5 | | 1 | 31/05/2021 | 84 | En el cap. 5, página 84, en la lista de ejemplos hay un error en el segundo. Dice: *Si tenemos (λ x. (λ y. (λ z.z))), la variable "x" si es bound*. | Lo correcto sería: *Si tenemos (λ x. (λ y. (λ z.**x**))), la variable "x" si es bound*. | Gracias a Guillermo Llancaqueo por detectarlo.
6 | | 2 | 22/08/2021 | 85 | Dice: *Una variable es free cuando no existe en el cuerpo de la función lambda*. | Lo correcto sería: *Una variable es free cuando existe en el cuerpo y no en la cabecera de la función lambda*. | Gracias a [Felipe Santa-Cruz](https://github.com/fesanmar) por detectarlo.
7 |
--------------------------------------------------------------------------------
/img/libro-01.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/img/libro-01.jpg
--------------------------------------------------------------------------------
/material/capítulo_1/figuras/1.2blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_1/figuras/1.2blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_1/figuras/1.3blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_1/figuras/1.3blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_1/figuras/1.4blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_1/figuras/1.4blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_1/figuras/1.5blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_1/figuras/1.5blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/funciones-identity.hs:
--------------------------------------------------------------------------------
1 | identity :: Int -> Int
2 | identity x = x
3 |
4 | getIdentity :: (Int -> (Int -> Int))
5 | getIdentity n = identity
6 |
7 | main = print $ ((getIdentity 0) 1)
8 | -- 1
9 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/funciones-increment-2.hs:
--------------------------------------------------------------------------------
1 | increment :: Int -> Int
2 | increment 10 = 10
3 | increment n = increment (n + 1)
4 | main = print $ increment 0
5 | -- 10
6 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/funciones-increment.hs:
--------------------------------------------------------------------------------
1 | increment :: Int -> Int
2 | increment n = n + 1
3 | main = print $ increment 0
4 | -- resultado: 1
5 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/funciones-sumThreeNumber.hs:
--------------------------------------------------------------------------------
1 | sumThreeNumber :: Int -> Int -> Int -> Int
2 | sumThreeNumber a b c = a + b + c
3 | main = print $ sumThreeNumber 1 2 3
4 | -- 6
5 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/funciones-sumTwoNumber.hs:
--------------------------------------------------------------------------------
1 | sumTwoNumber :: Int -> Int -> Int
2 | sumTwoNumber a b = a + b
3 | main = print $ sumTwoNumber 5 10
4 | -- 15
5 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/guards-ejemplo1.hs:
--------------------------------------------------------------------------------
1 | last :: [Int] -> Int
2 | last (x:xs)
3 | | length xs == 0 = x
4 | | otherwise = (f xs)
5 |
6 | main = print $ last [1,2,3]
7 | -- 3
8 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/guards-ejemplo2.hs:
--------------------------------------------------------------------------------
1 | f :: Int -> String
2 | f v
3 | | v >= 18 && v < 65 = "Es adulto."
4 | | v >= 65 = "Es de la tercera edad."
5 | | otherwise = "Es un menor o adolescente o algún alienígena."
6 |
7 | main = print $ f 80
8 | -- "Es de la tercera edad."
9 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/lista-fromNumberToListString.hs:
--------------------------------------------------------------------------------
1 | fromNumbersToListString :: [Int] -> [String]
2 | fromNumbersToListString x = map show x
3 |
4 | main = print $ fromNumbersToListString [123, 321]
5 | -- [“123”, “321”]
6 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/lista-fromNumbersToString.hs:
--------------------------------------------------------------------------------
1 | join :: [String] -> String
2 | join ls = foldl (++) "" ls
3 |
4 | fromNumbersToString :: [Int] -> String
5 | fromNumbersToString x = join (map show x)
6 |
7 | main = print $ fromNumbersToString [1, 2, 3, 4, 5]
8 | -- “12345”
9 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/lista-sumList.hs:
--------------------------------------------------------------------------------
1 | sumList :: [Int] -> Int
2 | sumList (x:xs) = (sumList xs) + x
3 | sumList [] = 0
4 | main = print $ sumList [1,2,3]
5 | -- 6
6 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/pattern-matching-diferentes-posiciones.hs:
--------------------------------------------------------------------------------
1 | f :: ([Int], (Int, Int), (Int, Int), Int) -> Int
2 |
3 | f ([1,1,1], (1,2), (3, 4), 5) = 1
4 | f ([2,2,2], (1,2), (3, 4), 5) = 2
5 | f (_, (0,0), _, _) = 3
6 |
7 | main = do
8 | print $ f ([1, 1, 1], (1, 2), (3, 4), 5) -- 1
9 | print $ f ([2, 2, 2], (1, 2), (3, 4), 5) -- 2
10 | print $ f ([1, 2, 3], (0, 0), (5, 6), 10) -- 3
11 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/pattern-matching-f.hs:
--------------------------------------------------------------------------------
1 | f :: Int -> Int
2 | f 0 = 0
3 | f n = f (n - 1) + n
4 | main = print $ f 5
5 | -- 15
6 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/pattern-matching-fibonacci.hs:
--------------------------------------------------------------------------------
1 | f :: Int -> Int
2 | f 0 = 0
3 | f 1 = 1
4 | f n = f (n - 1) + f(n - 2)
5 | main = print $ f 7
6 | -- 13
7 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/tupla-ejemplo1.hs:
--------------------------------------------------------------------------------
1 | tuple :: a -> b -> (a, b)
2 | tuple a b = (a, b)
3 | main = print $ tuple 1 'c'
4 | -- (1, ‘c’)
5 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/tupla-ejemplo2.hs:
--------------------------------------------------------------------------------
1 | join :: (Int, Int) -> Int
2 | join a = (fst a) + (snd a)
3 |
4 | sumList :: [Int] -> [Int] -> [Int]
5 | sumList a b = map join (zip a b)
6 |
7 | main = print $ sumList [1,2,3] [1,2,3]
8 | -- [2, 4, 6]
9 |
--------------------------------------------------------------------------------
/material/capítulo_10/ejemplos/tupla-ejemplo3.hs:
--------------------------------------------------------------------------------
1 | isEven :: Int -> Bool
2 | isEven a = a `mod` 2 == 0
3 |
4 | join :: (Int, Int) -> Int
5 | join a = (fst a) + (snd a)
6 |
7 | sumList :: [Int] -> [Int] -> [Int]
8 | sumList a b = filter (isEven) (map join (zip a b))
9 | main = print $ sumList [1,2,3] [1,2,4]
10 | -- [2, 4]
11 |
--------------------------------------------------------------------------------
/material/capítulo_11/figuras/11.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_11/figuras/11.1.png
--------------------------------------------------------------------------------
/material/capítulo_11/figuras/11.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_11/figuras/11.2.png
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-getFirstElement.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/ejemplos/funciones-getFirstElement.py
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-getFirstElement.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define getFirstElement
3 | (lambda (a b)
4 | (define first (lambda (x y) x))
5 | (first a b)))
6 |
7 | (displayln (getFirstElement 1 2))
8 | ; 1
9 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-op.py:
--------------------------------------------------------------------------------
1 | def mult(a, b):
2 | return a * b
3 |
4 | def op(f, a, b):
5 | return f(a, b)
6 |
7 | print(op(mult, 1, 2))
8 | # 2
9 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-op.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define op
3 | (lambda (f a b) (f a b)))
4 |
5 | (displayln (op * 1 2))
6 | ; 2
7 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-puras-copy-list-recursiva.py:
--------------------------------------------------------------------------------
1 | def copyList(lst):
2 | if not lst:
3 | return []
4 | elif len(lst) == 1:
5 | return [lst[0]]
6 | else:
7 | return copyList([lst[0]]) + copyList(lst[1:])
8 | a = [1,2,3]
9 | b = copyList(a)
10 | print(a == b)
11 | # True
12 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-puras-copy-list.py:
--------------------------------------------------------------------------------
1 | def copyList(lst):
2 | return [element for element in lst]
3 |
4 | a = [1,2,3]
5 | b = copyList(a)
6 | print(a == b)
7 | # True
8 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-puras-copy-list.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define copy-list
3 | (lambda (lst)
4 | (cond [(null? lst) '()]
5 | [(list? lst) (cons (car lst)
6 | (copy-list (cdr lst)))])))
7 | (equal? '(1 2 3) (copy-list '(1 2 3)))
8 | ; #t
9 | (eq? '(1 2 3) (copy-list '(1 2 3)))
10 | ; #f
11 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-sum.py:
--------------------------------------------------------------------------------
1 | def sum(a, b):
2 | return a + b
3 | print(sum(1, 2))
4 | # 3
5 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/funciones-sum.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define sum
3 | (lambda (a b) (+ a b)))
4 | (displayln (sum 1 2))
5 | ; 3
6 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-filter.py:
--------------------------------------------------------------------------------
1 | result = filter(lambda n: n > 0, [-1, 2, -3, 4, -5])
2 | print(list(result))
3 | # [2, 4]
4 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-filter.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (filter (lambda (n)
3 | (if (> n 0) #t #f)) '(-1 2 -3 4 -5))
4 | ; '(2 4)
5 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-increment.py:
--------------------------------------------------------------------------------
1 | def increment(n):
2 | return n + 1
3 | result = map(increment, [1,2,3])
4 | print([*result])
5 | # [2, 3, 4]
6 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-increment.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define increment
3 | (lambda (n)
4 | (+ n 1)))
5 | (map increment '(1 2 3))
6 | ; '(2 3 4)
7 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-map.py:
--------------------------------------------------------------------------------
1 | result = map(lambda x: (x, x + 1), [1,2,3])
2 | print([*result])
3 | # [(1,2), (2,3), (3,4)]
4 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-map.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (map (lambda (n)
3 | (list n (+ n 1))) '(1 2 3))
4 | ; '((1 2) (2 3) (3 4))
5 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-reduce.py:
--------------------------------------------------------------------------------
1 | from functools import reduce
2 | result = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
3 | print(result)
4 | # 15
5 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/higher-order-function-reduce.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define (reduce func lst)
3 | (if (null? (cdr lst))
4 | (car lst) ;expr-true
5 | (func (car lst) (reduce func (cdr lst))) ;expr-false
6 | ))
7 | (reduce + '(1 2 3 4 5))
8 | ; 15
9 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/lazy-list-infinite.py:
--------------------------------------------------------------------------------
1 | from collections.abc import Sequence
2 | class LazyList(Sequence):
3 | def __init__(self, it):
4 | self.it = it
5 | self._cache = []
6 |
7 | def __getitem__(self, index):
8 | while len(self._cache) <= index:
9 | self._cache.append(next(self.it))
10 | return self._cache[index]
11 |
12 | def __len__(self):
13 | return len(self._cache)
14 |
15 | def generator():
16 | number = 1
17 | while True:
18 | yield number
19 | number += 1
20 |
21 | numbers = LazyList(generator())
22 | print(numbers)
23 | #
24 | print(numbers[0])
25 | # 1
26 | print(len(numbers))
27 | # 1
28 | print(numbers[1])
29 | # 2
30 | print(len(numbers))
31 | # 2
32 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/lazy-list-infinite.rkt:
--------------------------------------------------------------------------------
1 | #lang lazy ;package
2 | (define list-infinite
3 | (lambda (n) (cons n (list-infinite (+ n 1)))))
4 |
5 | (list-infinite 1)
6 | ; (1 . #)
7 | (first (list-infinite 1))
8 | ; 1
9 | (first (cdr (list-infinite 1)))
10 | ; 2
11 | (first (cdr (cdr (list-infinite 1))))
12 | ; 3
13 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/lista-ejemplo.py:
--------------------------------------------------------------------------------
1 | lst = [1, 2, 3, 4, 5]
2 | print(lst[0])
3 | # 1
4 |
5 | print(lst[1:])
6 | # [2, 3, 4, 5]
7 |
8 | print(lst[-1])
9 | # 5
10 |
11 | new_lst = [lst[0]] + lst[1:]
12 | print(lst == new_lst)
13 | # True
14 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/lista-ejemplo.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (equal? '(1 2 3 4 5) (list 1 2 3 4 5))
3 | ; true
4 |
5 | (car '(1 2 3 4 5))
6 | ; 1
7 |
8 | (cdr '(1 2 3 4 5))
9 | ; '(2 3 4 5)
10 |
11 | (last '(1 2 3 4 5))
12 | ; 5
13 |
14 | (cons (car '(1 2 3 4 5)) (cdr '(1 2 3 4 5)))
15 | ; '(1 2 3 4 5)
16 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/pattern-matching-checking-expr-and-result.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define checking-expr-and-result
3 | (lambda (expr)
4 | (match expr
5 | [(list a b)
6 | #:when (= 20 (+ a b))
7 | 'sum-is-twenty]
8 | [(list a b)
9 | #:when (= 30 (+ a b))
10 | 'sum-is-thirty]
11 | [else 'not-match])))
12 |
13 | (checking-expr-and-result '(10 10))
14 | ; ‘sum-is-twenty
15 | (checking-expr-and-result '(15 15))
16 | ; ‘sum-is-thirty
17 | (checking-expr-and-result '(10))
18 | ; ‘not-match
19 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/pattern-matching-checking-expr-struct.py:
--------------------------------------------------------------------------------
1 | from pampy import match_value, _
2 |
3 | def checkingExprStruct(expr):
4 | if match_value([_, _], expr)[0]:
5 | print('two-element-list')
6 | elif match_value([_, _, _], expr)[0]:
7 | print('three-element-list')
8 | elif match_value({_ : _}, expr)[0]:
9 | print('two-element-dict')
10 | else:
11 | print('not-match')
12 |
13 | checkingExprStruct({"cálculo": "lambda"})
14 | # two-element-dict
15 | checkingExprStruct([1,2,3])
16 | # three-element-list
17 | checkingExprStruct([1,2])
18 | # two-element-list
19 | checkingExprStruct(1)
20 | # not-match
21 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/pattern-matching-checking-expr-struct.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define checking-expr-struct
3 | (lambda (expr)
4 | (match expr
5 | [(list _ _)
6 | 'two-element-list]
7 | [(list _ _ _)
8 | 'three-element-list]
9 | [(hash-table (_ _))
10 | 'two-element-hash]
11 | [else 'not-match])))
12 |
13 | (checking-expr-struct (hash "cálculo" "lambda"))
14 | ; 'two-element-hash
15 | (checking-expr-struct '(1 2 3))
16 | ; 'three-element-list
17 | (checking-expr-struct '(1 2))
18 | ; 'two-element-list
19 | (checking-expr-struct 1)
20 | ; 'not-match
21 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/pattern-matching-evaluate-pattern.py:
--------------------------------------------------------------------------------
1 | from pampy import match, MatchError, _
2 |
3 | def evaluate_pattern(expr, pattern, result):
4 | try:
5 | if match(expr, pattern, lambda x, y: x + y) == result:
6 | return 'match'
7 | except MatchError as e:
8 | return 'not-match', e
9 |
10 | print(evaluate_pattern([1,2], [_, _], 3))
11 | # match
12 | print(evaluate_pattern([1, 2, 3], [_, _], 3))
13 | # ('not-match', MatchError("'_' not provided. This case is not handled:\n[1, 2, 3]"))
14 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/recursividad-fact.py:
--------------------------------------------------------------------------------
1 | def fact(n):
2 | if n <= 0:
3 | return 0
4 | elif n == 1:
5 | return 1
6 | else:
7 | return fact(n - 1) * n
8 |
9 | print(fact(7))
10 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/recursividad-fact.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define fact
3 | (lambda (n)
4 | (cond
5 | [(<= n 0) 0]
6 | [(= n 1) 1]
7 | [else (* (fact (- n 1)) n)])))
8 |
9 | (displayln (fact 7))
10 | ; 5040
11 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/recursividad-fib.py:
--------------------------------------------------------------------------------
1 | def fib(n):
2 | if n == 0:
3 | return 0
4 | elif n == 1:
5 | return 1
6 | else:
7 | return fib(n - 1) + fib(n - 2)
8 |
9 | print(fib(4))
10 | # 3
11 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/recursividad-fib.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define fib
3 | (lambda (n)
4 | (cond
5 | [(= n 0) 0]
6 | [(= n 1) 1]
7 | [else (+ (fib (- n 1)) (fib (- n 2)))])))
8 | (displayln (fib 4))
9 | ; 3
10 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/recursividad-pow.py:
--------------------------------------------------------------------------------
1 | def pow(n, e):
2 | if e == 0:
3 | return 1
4 | elif e == 1:
5 | return n
6 | else:
7 | return pow(n, e - 1) * n
8 |
9 | print(pow(2, 4))
10 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/recursividad-pow.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define pow
3 | (lambda (n e)
4 | (cond
5 | [(= e 0) 1]
6 | [(= e 1) n]
7 | [else (* (pow n (- e 1)) n)])))
8 |
9 | (displayln (pow 2 4))
10 | ; 16
11 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/transparencia-referencial-concat-list.py:
--------------------------------------------------------------------------------
1 | def concat_list(lst1, lst2):
2 | return lst1 + lst2
3 |
4 | def concat_list_v2(lst1, lst2):
5 | if not lst1:
6 | return lst2
7 | else:
8 | return [lst1[0]] + concat_list_v2(lst1[1:], lst2)
9 |
10 | lst1 = [0, 1, 2]
11 | lst2 = [3, 4, 5]
12 | print(concat_list(lst1, lst2) ==
13 | concat_list_v2(lst1, lst2))
14 | # True
15 |
--------------------------------------------------------------------------------
/material/capítulo_12/ejemplos/transparencia-referencial-concat-list.rkt:
--------------------------------------------------------------------------------
1 | #lang lazy
2 | (define concat-list
3 | (lambda (lst1 lst2)
4 | (append lst1 lst2)))
5 |
6 | (equal? (concat-list '(0 1 2) '(3 4 5)) '(0 1 2 3 4 5))
7 | ; #t
8 |
9 | (define concat-list-v2
10 | (lambda (lst1 lst2)
11 | (cond
12 | [(null? lst1) lst2]
13 | [else (cons (car lst1)
14 | (concat-list-v2 (cdr lst1) lst2))]
15 | )))
16 |
17 | (equal? (concat-list-v2 '(0 1 2) '(3 4 5))
18 | '(0 1 2 3 4 5))
19 | ; #t
20 | (equal? (concat-list '(0 1 2) '(3 4 5))
21 | (concat-list-v2 '(0 1 2) '(3 4 5)))
22 | ; #t
23 |
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.1.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.2.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.3.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.4.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.5.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.6.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.7.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.8.png
--------------------------------------------------------------------------------
/material/capítulo_12/figuras/12.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_12/figuras/12.9.png
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/estructura-de-tipo-ejemplo1.py:
--------------------------------------------------------------------------------
1 | class chapter_13(object):
2 | def __init__(self, list, hash, structure, tree):
3 | self.list = list
4 | self.hash = hash
5 | self.structure = structure
6 | self.tree = tree
7 |
8 | cap = chapter_13([1,2,3], {1: 2}, None, None)
9 | print(cap.__dict__)
10 | # {'list': [1, 2, 3], 'hash': {1: 2}, 'structure': None, 'tree': None}
11 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/estructura-de-tipo-ejemplo1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (struct cap13
3 | (list hash pair structure-type tree) #:transparent)
4 | (define cap
5 | (cap13 '(1 2 3) '#([1 . 2]) (cons 1 2) null null))
6 | (displayln cap)
7 | ; #(struct:cap13 (1 2 3) #((1 . 2)) (1 . 2) () ())
8 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/estructura-de-tipo-operaciones-acceso.py:
--------------------------------------------------------------------------------
1 | class chapter_13(object):
2 | def __init__(self, list, hash, structure, tree):
3 | self.list = list
4 | self.hash = hash
5 | self.structure = structure
6 | self.tree = tree
7 |
8 | cap = chapter_13([1,2,3], {1: 2}, None, None)
9 | print(cap.__dict__)
10 | # {'list': [1, 2, 3], 'hash': {1: 2}, 'structure': None, 'tree': None}
11 |
12 | print(cap.list)
13 | # [1,2,3]
14 | print(cap.hash)
15 | # {1: 2}
16 | print(cap.structure)
17 | # None
18 | print(cap.tree)
19 | # None
20 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/estructura-de-tipo-operaciones-acceso.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (struct cap13
4 | (list hash pair structure-type tree) #:transparent)
5 | (define cap
6 | (cap13 '(1 2 3) '#([1 . 2]) (cons 1 2) null null))
7 |
8 | (cap13-list cap)
9 | ; '(1 2 3)
10 | (cap13-pair cap)
11 | ; '(1 . 2)
12 | (cap13-tree cap)
13 | ; '()
14 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/generate-list.py:
--------------------------------------------------------------------------------
1 | def generateTuple(elem, limit):
2 | return ((elem),) * limit
3 |
4 | print(generateTuple((1,2), 5))
5 | # ((1, 2), (1, 2), (1, 2), (1, 2), (1, 2))
6 | print(generateTuple(("a", "z"), 5))
7 | # (('a', 'z'), ('a', 'z'), ('a', 'z'), ('a', 'z'), ('a', 'z'))
8 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/generate-list.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define generate-list
3 | (lambda (init elem limit)
4 | (cond
5 | [(= init limit) '()]
6 | [else (cons elem (generate-list (+ init 1) elem limit))]
7 | )))
8 | (generate-list 0 '(1 2) 5)
9 | ; '((1 2) (1 2) (1 2) (1 2) (1 2))
10 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-ejemplo1.py:
--------------------------------------------------------------------------------
1 | class immutable_dict(dict):
2 | def __hash__(self):
3 | return id(self)
4 |
5 | def _immutable(self, *args, **kws):
6 | raise TypeError('immutable_dict is immutable')
7 |
8 | __setitem__ = _immutable
9 | __delitem__ = _immutable
10 | clear = _immutable
11 | update = _immutable
12 | setdefault = _immutable
13 | pop = _immutable
14 | popitem = _immutable
15 |
16 | table = immutable_dict({ 'cálculo': "lambda" })
17 | print(table)
18 | # {'cálculo': 'lambda'}
19 | table["a"] = "b"
20 | # error, porque este diccionario es inmutable.
21 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-ejemplo1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define table
3 | (make-immutable-hash '(["cálculo" . "lambda"])))
4 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-ejemplo2.py:
--------------------------------------------------------------------------------
1 | class immutable_dict(dict):
2 | def __hash__(self):
3 | return id(self)
4 |
5 | def _immutable(self, *args, **kws):
6 | raise TypeError('immutable_dict is immutable')
7 |
8 | __setitem__ = _immutable
9 | __delitem__ = _immutable
10 | clear = _immutable
11 | update = _immutable
12 | setdefault = _immutable
13 | pop = _immutable
14 | popitem = _immutable
15 |
16 | table = immutable_dict({ ("a", "b", "c"): "d",
17 | 1: 2})
18 | print(table)
19 | # {('a', 'b', 'c'): 'd', 1: 2}
20 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-ejemplo2.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define table
3 | (make-immutable-hash '([("a" "b" "c") . "d"]
4 | [1 . 2])))
5 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-operaciones-búsqueda.py:
--------------------------------------------------------------------------------
1 | class immutable_dict(dict):
2 | def __hash__(self):
3 | return id(self)
4 |
5 | def _immutable(self, *args, **kws):
6 | raise TypeError('immutable_dict is immutable')
7 |
8 | __setitem__ = _immutable
9 | __delitem__ = _immutable
10 | clear = _immutable
11 | update = _immutable
12 | setdefault = _immutable
13 | pop = _immutable
14 | popitem = _immutable
15 |
16 | table = immutable_dict({ ("a", "b", "c"): "d",
17 | 1: 2})
18 | print(table)
19 | # {('a', 'b', 'c'): 'd', 1: 2}
20 |
21 | table.get(("a", "b", "c"))
22 | # “d”
23 | table.get(1)
24 | # 2
25 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-operaciones-búsqueda.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define table
3 | (make-immutable-hash '([("a" "b" "c") . "d"]
4 | [1 . 2])))
5 |
6 | (hash-ref table '("a" "b" "c"))
7 | ; "d"
8 | (hash-ref table 1)
9 | ; 2
10 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-operaciones-eliminación.py:
--------------------------------------------------------------------------------
1 | class immutable_dict(dict):
2 | def __hash__(self):
3 | return id(self)
4 |
5 | def _immutable(self, *args, **kws):
6 | raise TypeError('immutable_dict is immutable')
7 |
8 | __setitem__ = _immutable
9 | __delitem__ = _immutable
10 | clear = _immutable
11 | update = _immutable
12 | setdefault = _immutable
13 | pop = _immutable
14 | popitem = _immutable
15 |
16 | table = immutable_dict({ ("a", "b", "c"): "d",
17 | 1: 2})
18 | print(table)
19 | # {('a', 'b', 'c'): 'd', 1: 2}
20 |
21 | def dict_remove(imm_dict, key):
22 | temp_dict = imm_dict.copy()
23 | if key in temp_dict:
24 | del temp_dict[key]
25 | return immutable_dict(temp_dict)
26 |
27 | table_3 = dict_remove(table, ('a', 'b', 'c'))
28 | print(table_3)
29 | # {1: 2}
30 | print(table)
31 | # {('a', 'b', 'c'): 'd', 1: 2}
32 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-operaciones-eliminación.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define table
3 | (make-immutable-hash '([("a" "b" "c") . "d"]
4 | [1 . 2])))
5 |
6 | (define table-2 (hash-set table "programación" "funcional"))
7 |
8 | (define table-3 (hash-remove table-2 '("a" "b" "c")))
9 | table-3
10 | ;'#hash((1 . 2) (("a" "b" "c") . "d"))
11 |
12 | (equal? table-2 table-3)
13 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-operaciones-inserción.py:
--------------------------------------------------------------------------------
1 | class immutable_dict(dict):
2 | def __hash__(self):
3 | return id(self)
4 |
5 | def _immutable(self, *args, **kws):
6 | raise TypeError('immutable_dict is immutable')
7 |
8 | __setitem__ = _immutable
9 | __delitem__ = _immutable
10 | clear = _immutable
11 | update = _immutable
12 | setdefault = _immutable
13 | pop = _immutable
14 | popitem = _immutable
15 |
16 | table = immutable_dict({ ("a", "b", "c"): "d",
17 | 1: 2})
18 | print(table)
19 | # {('a', 'b', 'c'): 'd', 1: 2}
20 |
21 | def dict_set(imm_dict, key, value):
22 | temp_dict = imm_dict.copy()
23 | temp_dict[key] = value
24 | return immutable_dict(temp_dict)
25 |
26 | table_2 = dict_set(table, (3,3), 6)
27 | print(table_2)
28 | # {('a', 'b', 'c'): 'd', 1: 2, (3, 3): 6}
29 | print(table)
30 | # {('a', 'b', 'c'): 'd', 1: 2}
31 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/hashtable-operaciones-inserción.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define table
3 | (make-immutable-hash '([("a" "b" "c") . "d"]
4 | [1 . 2])))
5 | (define table-2 (hash-set table "programación" "funcional"))
6 | table-2
7 | ; '#hash((1 . 2) ("programación" . "funcional") (("a" "b" "c") . "d"))
8 | table
9 | ; '#hash((1 . 2) (("a" "b" "c") . "d"))
10 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-búsqueda.bak:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define lst '(1 2 3 4 5))
3 |
4 | (member 3 lst)
5 | ; '(3 4 5)
6 |
7 | (member 10 lst)
8 | ; #f
9 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-búsqueda.py:
--------------------------------------------------------------------------------
1 | tupla_vocales = ("a", "e", "i", "o", "u")
2 | print(tupla_vocales.index("i"))
3 | # 2
4 | print("i" in tupla_vocales)
5 | # True
6 | print("z" in tupla_vocales)
7 | # False
8 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-búsqueda.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define lst '(1 2 3 4 5))
3 |
4 | (member 3 lst)
5 | ; '(3 4 5)
6 |
7 | (member 10 lst)
8 | ; #f
9 |
10 | (findf (lambda (elem)
11 | (= elem 3)) lst)
12 | ; 3
13 |
14 | (findf (lambda (elem)
15 | (= elem 100)) lst)
16 | ; #f
17 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-eliminación.py:
--------------------------------------------------------------------------------
1 | lst = (1, 2, 3, 4, 5)
2 | new_lst = lst[1:]
3 | print(new_lst)
4 | # (2, 3, 4, 5)
5 | new_lst = tuple(v for v in lst if v != 4)
6 | print(new_lst)
7 | # (1, 2, 3, 5)
8 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-eliminación.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (remove 2 lst)
3 | ; '(1 3 4 5)
4 | (remove 3 lst)
5 | ; '(1 2 4 5)
6 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-filtrado.py:
--------------------------------------------------------------------------------
1 | lst = (1, 2, 3, 4, 5)
2 | new_lst = tuple(filter(lambda e: e == 0, lst))
3 | print(new_lst)
4 | # ()
5 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-filtrado.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (filter (lambda (e)
3 | (= e 0)) lst)
4 | ; '()
5 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-inserción.py:
--------------------------------------------------------------------------------
1 | lst = (1, 2, 3)
2 | lst += (4, 5)
3 | print(lst)
4 | # (1, 2, 3, 4, 5)
5 | lst = (4, 5) + (1, 2, 3)
6 | print(lst)
7 | # (4, 5, 1, 2, 3)
8 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/operador-inserción.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define lst '(1 2 3))
3 | (append lst '(4 5))
4 | ; '(1 2 3 4 5)
5 | (append '(4 5) lst)
6 | ; '(4 5 1 2 3)
7 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/par-ejemplo1.py:
--------------------------------------------------------------------------------
1 | class pair(tuple):
2 | def __init__(self, args):
3 | if len(args) != 2:
4 | raise TypeError('pair debe contener dos elementos.')
5 |
6 | def first(self):
7 | return self.__getitem__(0)
8 |
9 | def second(self):
10 | return self.__getitem__(-1)
11 |
12 | par = pair((1, 2))
13 | print(par)
14 | # (1,2)
15 | print(pair((1, 2, 3)))
16 | # pair must contain two elements.
17 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/par-ejemplo1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define par (cons 1 2))
3 | (pair? par)
4 | ; #t
5 | (define empty '())
6 | (pair? empty)
7 | ; #f
8 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/par-operaciones-acceso.py:
--------------------------------------------------------------------------------
1 | class pair(tuple):
2 | def __init__(self, args):
3 | if len(args) != 2:
4 | raise TypeError('pair debe contener dos elementos.')
5 |
6 | def first(self):
7 | return self.__getitem__(0)
8 |
9 | def second(self):
10 | return self.__getitem__(-1)
11 |
12 | par = pair((1, 2))
13 |
14 | print(par.first())
15 | # 1
16 | print(par.second())
17 | # 2
18 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/par-operaciones-acceso.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define par (cons 1 2))
3 | (car par)
4 | ; 1
5 | (cdr par)
6 | ; 2
7 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/reverse-list.py:
--------------------------------------------------------------------------------
1 | def reverseTuple(tupla):
2 | return tupla[::-1]
3 |
4 | print(reverseTuple((1, 2, 3, 4, 5)))
5 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/reverse-list.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define reverse-list
3 | (lambda (lst)
4 | (cond
5 | [(null? lst) '()]
6 | [else (cons (last lst)
7 | (reverse-list
8 | (drop-right lst 1)))])))
9 |
10 | (reverse-list '(1 2 3 4 5))
11 | ; '(5 4 3 2 1)
12 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/slicing.py:
--------------------------------------------------------------------------------
1 | tupla_slicing = (1, 2, 3, 4, 5)
2 | print(tupla_slicing [0])
3 | # 1
4 | print(tupla_slicing[-1])
5 | # 5
6 | print(tupla_slicing[:3])
7 | # (1, 2, 3)
8 | print(tupla_slicing[3:])
9 | # (4, 5)
10 | print(tupla_slicing[2:4])
11 | # (3, 4)
12 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-ejemplo1.py:
--------------------------------------------------------------------------------
1 | class node(object):
2 | def __init__(self, value, left = None, right = None):
3 | self.value = value
4 | self.left = left
5 | self.right = right
6 |
7 | tree = node(9,
8 | node(7,
9 | node(5,
10 | node(1), node(6)),
11 | node(8)),
12 | node(10,
13 | None,
14 | node(11,
15 | None,
16 | node(12))))
17 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-ejemplo1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (struct node (value left right))
3 | (define tree
4 | (node 9
5 | (node 7
6 | (node 5
7 | (node 1 null null)
8 | (node 6 null null))
9 | (node 8 null null))
10 | (node 10 null
11 | (node 11 null
12 | (node 12 null null)))))
13 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-ejemplo2.py:
--------------------------------------------------------------------------------
1 | class node(object):
2 | def __init__(self, value, left = None, right = None):
3 | self.value = value
4 | self.left = left
5 | self.right = right
6 |
7 | def create_binary_tree(lst):
8 | if not lst:
9 | return None
10 | if not lst[1:]:
11 | return node(lst[0])
12 | else:
13 | value = lst[0]
14 | tail = lst[1:]
15 | left = list(filter(lambda v: v < value, tail))
16 | right = list(filter(lambda v: v >= value, tail))
17 | return node(value,
18 | create_binary_tree(left),
19 | create_binary_tree(right))
20 |
21 | create_binary_tree((9, 7, 5, 1, 6, 8, 10, 11, 12))
22 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-ejemplo2.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (struct node (value left right))
3 |
4 | (define (create-binary-tree lst)
5 | (if (null? lst) null
6 | (cond
7 | [(null? (cdr lst)) (node (car lst) null null)]
8 | [else (let*
9 | ([value (car lst)]
10 | [tail (cdr lst)]
11 | [left
12 | (filter
13 | (lambda (v) (< v value)) tail)]
14 | [right
15 | (filter
16 | (lambda (v) (>= v value)) tail)])
17 | (node value
18 | (create-binary-tree left)
19 | (create-binary-tree right)))]
20 | )
21 | )
22 | )
23 | (create-binary-tree (list 9 7 5 1 6 8 10 11 12))
24 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-operaciones-búsqueda.py:
--------------------------------------------------------------------------------
1 | class node(object):
2 | def __init__(self, value, left = None, right = None):
3 | self.value = value
4 | self.left = left
5 | self.right = right
6 |
7 | def create_binary_tree(lst):
8 | if not lst:
9 | return None
10 | if not lst[1:]:
11 | return node(lst[0])
12 | else:
13 | value = lst[0]
14 | tail = lst[1:]
15 | left = list(filter(lambda v: v < value, tail))
16 | right = list(filter(lambda v: v >= value, tail))
17 | return node(value,
18 | create_binary_tree(left),
19 | create_binary_tree(right))
20 |
21 | tree = create_binary_tree((9, 7, 5, 1, 6, 8, 10, 11, 12))
22 |
23 | def search(tree, value):
24 | if not tree or value == tree.value:
25 | return tree
26 | elif value > tree.value:
27 | return search(tree.right, value)
28 | else:
29 | return search(tree.left, value)
30 |
31 | if search(tree, 10):
32 | print("found")
33 | else:
34 | print("not found")
35 | # found
36 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-operaciones-búsqueda.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (struct node (value left right))
3 |
4 | (define (create-binary-tree lst)
5 | (if (null? lst) null
6 | (cond
7 | [(null? (cdr lst)) (node (car lst) null null)]
8 | [else (let*
9 | ([value (car lst)]
10 | [tail (cdr lst)]
11 | [left
12 | (filter
13 | (lambda (v) (< v value)) tail)]
14 | [right
15 | (filter
16 | (lambda (v) (>= v value)) tail)])
17 | (node value
18 | (create-binary-tree left)
19 | (create-binary-tree right)))]
20 | )
21 | )
22 | )
23 | (define tree (create-binary-tree (list 9 7 5 1 6 8 10 11 12)))
24 |
25 | (define search
26 | (lambda (tree value)
27 | (cond
28 | [(or (null? tree) (= value (node-value tree))) tree]
29 | [(> value (node-value tree))
30 | (search (node-right tree) value)]
31 | [else (search (node-left tree) value)]
32 | )
33 | )
34 | )
35 |
36 | (if (null? (search tree 10)) 'not-found 'found)
37 | ; 'found
38 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-operaciones-cantidad-elementos.py:
--------------------------------------------------------------------------------
1 | class node(object):
2 | def __init__(self, value, left = None, right = None):
3 | self.value = value
4 | self.left = left
5 | self.right = right
6 |
7 | def create_binary_tree(lst):
8 | if not lst:
9 | return None
10 | if not lst[1:]:
11 | return node(lst[0])
12 | else:
13 | value = lst[0]
14 | tail = lst[1:]
15 | left = list(filter(lambda v: v < value, tail))
16 | right = list(filter(lambda v: v >= value, tail))
17 | return node(value,
18 | create_binary_tree(left),
19 | create_binary_tree(right))
20 |
21 | tree = create_binary_tree((9, 7, 5, 1, 6, 8, 10, 11, 12))
22 |
23 | def count_tree(tree):
24 | if not tree:
25 | return 0
26 | else:
27 | return (1 +
28 | count_tree(tree.left) +
29 | count_tree(tree.right))
30 | print(count_tree(tree))
31 | # 9
32 |
--------------------------------------------------------------------------------
/material/capítulo_13/ejemplos/tree-operaciones-cantidad-elementos.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (struct node (value left right))
4 |
5 | (define (create-binary-tree lst)
6 | (if (null? lst) null
7 | (cond
8 | [(null? (cdr lst)) (node (car lst) null null)]
9 | [else (let*
10 | ([value (car lst)]
11 | [tail (cdr lst)]
12 | [left
13 | (filter
14 | (lambda (v) (< v value)) tail)]
15 | [right
16 | (filter
17 | (lambda (v) (>= v value)) tail)])
18 | (node value
19 | (create-binary-tree left)
20 | (create-binary-tree right)))]
21 | )
22 | )
23 | )
24 | (define tree (create-binary-tree (list 9 7 5 1 6 8 10 11 12)))
25 |
26 | (define count-tree
27 | (lambda (tree)
28 | (cond
29 | [(null? tree) 0]
30 | [else
31 | (+ 1 (count-tree (node-left tree))
32 | (count-tree (node-right tree)))]
33 | )
34 | )
35 | )
36 | (count-tree tree)
37 | ; 9
38 |
--------------------------------------------------------------------------------
/material/capítulo_13/figuras/13.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_13/figuras/13.1.png
--------------------------------------------------------------------------------
/material/capítulo_13/figuras/13.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_13/figuras/13.2.png
--------------------------------------------------------------------------------
/material/capítulo_13/figuras/13.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_13/figuras/13.3.png
--------------------------------------------------------------------------------
/material/capítulo_13/figuras/13.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_13/figuras/13.4.png
--------------------------------------------------------------------------------
/material/capítulo_13/figuras/13.5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_13/figuras/13.5.png
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/hanoi.py:
--------------------------------------------------------------------------------
1 | def hanoi(n, source, dest, aux):
2 | if n == 1:
3 | print("Mover disco 1 desde origen {} al destino {}".format(source, dest))
4 | else:
5 | hanoi(n-1, source, aux, dest)
6 | print("Mover disco {} desde origen {} al destino {}".format(n, source, dest))
7 | hanoi(n-1, aux, dest, source)
8 |
9 | hanoi(3, "A", "C", "B")
10 | # Mover disco 1 desde origen A al destino C
11 | # Mover disco 2 desde origen A al destino B
12 | # Mover disco 1 desde origen C al destino B
13 | # Mover disco 3 desde origen A al destino C
14 | # Mover disco 1 desde origen B al destino A
15 | # Mover disco 2 desde origen B al destino C
16 | # Mover disco 1 desde origen A al destino C
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/hanoi.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (require racket/block)
3 | (define (hanoi n source dest aux)
4 | (if (= n 1)
5 | (displayln
6 | (list "Mover disco 1 desde origen" source
7 | "al destino" dest))
8 | (block
9 | (hanoi (- n 1) source aux dest)
10 | (displayln
11 | (list "Mover disco" n
12 | "desde origen" source
13 | "al destino" dest))
14 | (hanoi (- n 1) aux dest source))))
15 |
16 | (hanoi 3 "A" "C" "B")
17 | ; (Mover disco 1 desde origen A al destino C)
18 | ; (Mover disco 2 desde origen A al destino B)
19 | ; (Mover disco 1 desde origen C al destino B)
20 | ; (Mover disco 3 desde origen A al destino C)
21 | ; (Mover disco 1 desde origen B al destino A)
22 | ; (Mover disco 2 desde origen B al destino C)
23 | ; (Mover disco 1 desde origen A al destino C)
24 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/huffman-encoding.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (struct node (value left right) #:transparent)
3 |
4 | (define sequence (string->list "AEEEADDECA"))
5 |
6 | (define freq (make-immutable-hash))
7 |
8 | (define (increment-freq freq key)
9 | (if (hash-has-key? freq key)
10 | (+ 1 (hash-ref freq key))
11 | 1))
12 |
13 | (define (calculate-freq sequence freq)
14 | (if (null? sequence) freq
15 | (calculate-freq
16 | (cdr sequence)
17 | (hash-set
18 | freq
19 | (car sequence)
20 | (increment-freq freq (car sequence))
21 | ))))
22 |
23 | (define (create-tree sum-value left right)
24 | (node sum-value left right))
25 |
26 | (define (create-huffman-tree nodes tree)
27 | (if (null? nodes) tree
28 | (cond [(<= (node-value tree) (cdr (car nodes)))
29 | (create-huffman-tree
30 | (cdr nodes)
31 | (create-tree
32 | (+ (node-value tree) (cdr (car nodes)))
33 | tree
34 | (caar nodes)))]
35 | [else
36 | (create-huffman-tree
37 | (cdr nodes)
38 | (create-tree
39 | (+ (node-value tree) (cdr (car nodes)))
40 | (caar nodes)
41 | tree))]
42 | )))
43 |
44 | (define (huffman nodes)
45 | (cond
46 | [(= (length nodes) 0)
47 | (raise '"Error. Sequence is empty" #t)]
48 | [(>= (length nodes) 2)
49 | (create-huffman-tree
50 | (cddr nodes)
51 | (create-tree
52 | (+ (cdr (car nodes)) (cdr (second nodes)))
53 | (caar nodes)
54 | (car (second nodes))
55 | ))]
56 | [else
57 | (create-huffman-tree
58 | (cdr nodes)
59 | (create-tree
60 | (cdr (car nodes))
61 | (caar nodes)
62 | null
63 | ))]))
64 |
65 | (define nodes-freq (calculate-freq sequence freq))
66 | (define nodes-key (hash-keys nodes-freq))
67 | (define huffman-tree (huffman (hash->list nodes-freq)))
68 | (displayln huffman-tree)
69 | ; #(struct:node 10 E #(struct:node 6 #(struct:node 3 C D) A))
70 |
71 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/huffman.py:
--------------------------------------------------------------------------------
1 | sequence = 'AEEEADDECA'
2 |
3 | class Tree(object):
4 | def __init__(self, value, left=None, right=None):
5 | self.value = value
6 | self.left = left
7 | self.right = right
8 |
9 | def children(self):
10 | return (self.left, self.right)
11 |
12 | def huffman_code_tree(node, binary=''):
13 | if type(node) is str:
14 | return { node: binary }
15 | if not node:
16 | return {}
17 | (left, right) = node.children()
18 | encoding = dict()
19 | encoding.update(huffman_code_tree(left, binary+'0'))
20 | encoding.update(huffman_code_tree(right, binary+'1'))
21 | return encoding
22 |
23 | if len(sequence) == 0:
24 | raise Exception("Error. Sequence is empty")
25 | freq = {}
26 | for c in sequence:
27 | if c in freq:
28 | freq[c] += 1
29 | else:
30 | freq[c] = 1
31 |
32 | freq = sorted(freq.items(), key=lambda x: x[1])
33 | nodes = freq.copy()
34 |
35 | if len(nodes) >= 2:
36 | (letter1, v1), (letter2, v2) = nodes[:2]
37 | tree = Tree(v1 + v2, letter1, letter2)
38 | nodes = nodes[2:]
39 | else:
40 | (letter, value) = nodes[0]
41 | tree = Tree(value, letter)
42 |
43 | for node in nodes:
44 | (letter, value) = node
45 | if tree.value <= value:
46 | tree = Tree(tree.value + value, tree, letter)
47 | else:
48 | tree = Tree(tree.value + value, letter, tree)
49 |
50 | print(huffman_code_tree(tree))
51 | # {'E': '0', 'C': '100', 'D': '101', 'A': '11'}
52 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/huffman.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (struct node (value left right) #:transparent)
3 |
4 | (define sequence (string->list "AEEEADDECA"))
5 |
6 | (define freq (make-immutable-hash))
7 |
8 | (define (increment-freq freq key)
9 | (if (hash-has-key? freq key)
10 | (+ 1 (hash-ref freq key))
11 | 1))
12 |
13 | (define (calculate-freq sequence freq)
14 | (if (null? sequence) freq
15 | (calculate-freq
16 | (cdr sequence)
17 | (hash-set
18 | freq
19 | (car sequence)
20 | (increment-freq freq (car sequence))
21 | ))))
22 |
23 | (define (create-tree sum-value left right)
24 | (node sum-value left right))
25 |
26 | (define (create-huffman-tree nodes tree)
27 | (if (null? nodes) tree
28 | (cond [(<= (node-value tree) (cdr (car nodes)))
29 | (create-huffman-tree
30 | (cdr nodes)
31 | (create-tree
32 | (+ (node-value tree) (cdr (car nodes)))
33 | tree
34 | (caar nodes)))]
35 | [else
36 | (create-huffman-tree
37 | (cdr nodes)
38 | (create-tree
39 | (+ (node-value tree) (cdr (car nodes)))
40 | (caar nodes)
41 | tree))]
42 | )))
43 |
44 | (define (huffman nodes)
45 | (cond
46 | [(= (length nodes) 0)
47 | (raise '"Error. Sequence is empty" #t)]
48 | [(>= (length nodes) 2)
49 | (create-huffman-tree
50 | (cddr nodes)
51 | (create-tree
52 | (+ (cdr (car nodes)) (cdr (second nodes)))
53 | (caar nodes)
54 | (car (second nodes))
55 | ))]
56 | [else
57 | (create-huffman-tree
58 | (cdr nodes)
59 | (create-tree
60 | (cdr (car nodes))
61 | (caar nodes)
62 | null
63 | ))]))
64 |
65 | (define nodes-freq (calculate-freq sequence freq))
66 | (define nodes-key (hash-keys nodes-freq))
67 | (define huffman-tree (huffman (sort (hash->list nodes-freq) #:key cdr <)))
68 | (displayln huffman-tree)
69 | ; #(struct:node 10 E #(struct:node 6 #(struct:node 3 C D) A))
70 |
71 | (require racket/hash)
72 | (define (decoding tree binary)
73 | (cond
74 | [(char? tree) (hash tree binary)]
75 | [(null? tree) (make-hash)]
76 | [else
77 | (let*
78 | ([left (node-left tree)]
79 | [right (node-right tree)])
80 | (hash-union
81 | (decoding left (string-append binary "0"))
82 | (decoding right (string-append binary "1"))))
83 | ]))
84 | (displayln (decoding huffman-tree ""))
85 | ; #hash((A . 11) (C . 100) (D . 101) (E . 0))
86 |
87 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/karp-rabin.py:
--------------------------------------------------------------------------------
1 | def karp_rabin(T, P, b, q):
2 | #q = número primo
3 | #b = número base
4 | n = len(T)
5 | m = len(P)
6 | if m > n:
7 | return -1
8 |
9 | d = (b**(m-1)) % q
10 | h_y = 0
11 | h_x = 0
12 |
13 | #preprocesamiento
14 | for i in range(0, m):
15 | h_y += (ord(T[i]) * (b**(m - i - 1)))
16 | h_x += (ord(P[i]) * (b**(m - i - 1)))
17 |
18 | h_y = h_y % q
19 | h_x = h_x % q
20 |
21 | for i in range(0, n - m + 1):
22 | if h_y == h_x:
23 | if P == T[i: i + m]:
24 | print("Encontrado:", i)
25 | return i
26 | elif i + m < n:
27 | h_y = (h_y + b * q - ord(T[i]) * d) % q
28 | h_y = (h_y * b + ord(T[i + m])) % q
29 | i += 1
30 |
31 | return -1
32 |
33 | result = karp_rabin("cálculo lambda!", "lambda", 256, 8355967)
34 | print(result)
35 | # Encontrado: 8
36 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/karp-rabin.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define (calculate-hash-specific h C i b m)
3 | (+ h
4 | (*
5 | (char->integer (list-ref C i))
6 | (expt b (- (- m i) 1))
7 | )))
8 |
9 | (define (calculate-hash-general T P b m h_y h_x i)
10 | (if (< i m)
11 | (calculate-hash-general T P b m
12 | (calculate-hash-specific h_y T i b m)
13 | (calculate-hash-specific h_x P i b m)
14 | (+ i 1))
15 | (list h_y h_x)))
16 |
17 | (define (update-hash h b q d m C i)
18 | (let* ([h (modulo
19 | (+ h
20 | (-
21 | (* b q)
22 | (* (char->integer
23 | (list-ref C i)) d)))
24 | q)]
25 | [h (modulo
26 | (+ (* h b)
27 | (char->integer
28 | (list-ref C (+ i m))))
29 | q)])
30 | h))
31 |
32 | (define (matcher T P b d q m n h_y h_x i)
33 | (if (< i (+ (- n m) 1))
34 | (cond [(and (= h_y h_x)
35 | (equal? (list->string P)
36 | (substring (list->string T)
37 | i (+ i m))))
38 | (list "Encontrado" i)]
39 | [(< (+ i m) n)
40 | (matcher T P b d q m n
41 | (update-hash h_y b q d m T i)
42 | h_x
43 | (+ i 1))]
44 | [else -1])
45 | -1))
46 |
47 | (define (karp-rabin T P b q)
48 | (let* ([n (length T)]
49 | [m (length P)])
50 | (if (> m n)
51 | -1
52 | (let* ([d (modulo (expt b (- m 1)) q)]
53 | [hashes
54 | (calculate-hash-general T P b m 0 0 0)]
55 | [h_y (modulo (first hashes) q)]
56 | [h_x (modulo (last hashes) q)])
57 | (matcher T P b d q m n h_y h_x 0)
58 | ))))
59 |
60 | (karp-rabin
61 | (string->list "culo")
62 | (string->list "lambda") 256 8355967)
63 | ; ‘(Encontrado, 8)
64 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/msort.py:
--------------------------------------------------------------------------------
1 | def merge_list(left, right):
2 | if not left or not right:
3 | return left + right
4 | else:
5 | fa = left[0]
6 | fb = right[0]
7 | if fa < fb:
8 | return [fa] + merge_list(left[1:], right)
9 | else:
10 | return [fb] + merge_list(left, right[1:])
11 |
12 | def msort(lst):
13 | if len(lst) <= 1:
14 | return lst
15 | else:
16 | middle = round(len(lst) / 2)
17 | left = lst[:middle]
18 | right = lst[-(len(lst) - middle):]
19 | return merge_list(msort(left), msort(right))
20 |
21 | print(msort([9, 2, 1, 8, 3]))
22 | # [1, 2, 3, 8, 9]
23 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/msort.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define (merge-list left right)
3 | (if (or (null? left) (null? right))
4 | (append left right)
5 | (let ([fa (car left)])
6 | (let ([fb (car right)])
7 | (if (< fa fb)
8 | (append
9 | (list fa)
10 | (merge-list (cdr left) right))
11 | (append
12 | (list fb)
13 | (merge-list left (cdr right)))
14 | )))))
15 |
16 | (define (msort lst)
17 | (if (<= (length lst) 1)
18 | lst
19 | (let ([middle
20 | (round (/ (length lst) 2))])
21 | (let ([left (take lst middle)])
22 | (let ([right
23 | (take-right lst
24 | (- (length lst) middle))])
25 | (merge-list
26 | (msort left)
27 | (msort right))
28 | )))))
29 |
30 | (msort '(9 2 1 8 3))
31 | ; '(1 2 3 8 9)
32 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/qsort.py:
--------------------------------------------------------------------------------
1 | def qsort(lst):
2 | if not lst:
3 | return lst
4 | pivot = lst[0]
5 | tail = lst[1:]
6 | lsr = list(filter(lambda v: v < pivot, tail))
7 | grt = list(filter(lambda v: v >= pivot, tail))
8 | return qsort(lsr) + [pivot] + qsort(grt)
9 |
10 | print(qsort([9, 2, 1, 8, 3]))
11 | # [1, 2, 3, 8, 9]
12 |
--------------------------------------------------------------------------------
/material/capítulo_14/ejemplos/qsort.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (define (qsort lst)
3 | (if (null? lst)
4 | lst
5 | (let ([pivot (car lst)])
6 | (let ([tail (cdr lst)])
7 | (let ([lsr
8 | (filter
9 | (lambda (v) (< v pivot))
10 | tail)])
11 | (let ([grt
12 | (filter
13 | (lambda (v) (>= v pivot))
14 | tail)])
15 | (append
16 | (qsort lsr)
17 | (list pivot)
18 | (qsort grt))))))))
19 |
20 | (qsort '(9 2 1 8 3))
21 | ; '(1 2 3 8 9)
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14-ejercicio.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14-ejercicio.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.1.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.10.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.11.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.12.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.2.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.3.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.4.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.5.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.5.jpg
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.6.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.7.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.8.png
--------------------------------------------------------------------------------
/material/capítulo_14/figuras/14.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_14/figuras/14.9.png
--------------------------------------------------------------------------------
/material/capítulo_15/ejemplos/interpreter.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (require syntax/parse)
4 | (require "while.rkt")
5 | (require "lexer.rkt")
6 |
7 | (define variables (make-hash))
8 |
9 | (define (interpret-program program-stx)
10 | (syntax-parse program-stx
11 |
12 | [({~literal program} program-1 ";" program-2)
13 | (interpret-program #'program-1)
14 | (interpret-program #'program-2)
15 | ]
16 |
17 | [({~literal program} "if" bool "then" program-1
18 | "else" program-2)
19 | (if (interpret-bool #'bool)
20 | (interpret-program #'program-1)
21 | (interpret-program #'program-2))
22 | ]
23 |
24 | [({~literal program} "while" bool "do" program-1)
25 | (cond
26 | [(equal? (interpret-bool #'bool) #t)
27 | (interpret-program #'program-1)
28 | (interpret-program program-stx)]
29 | [else null])
30 | ]
31 |
32 | [({~literal program} "print" "(" expr-1 ")")
33 | (displayln (interpret-exprs #'expr-1))
34 | ]
35 |
36 | [({~literal program} var ":=" expr-1)
37 | (if (hash-has-key? variables
38 | (second
39 | (syntax->datum #'var)))
40 | (dict-set! variables
41 | (second (syntax->datum #'var))
42 | (interpret-exprs #'expr-1))
43 | (dict-set! variables
44 | (second (syntax->datum #'var))
45 | (interpret-exprs #'expr-1)))
46 | ]
47 | )
48 | )
49 |
50 | (define (interpret-bool bool-stx)
51 | (syntax-parse bool-stx
52 | [({~literal bool} "true") #t ]
53 | [({~literal bool} "false") #f ]
54 | [({~literal bool} "(" expr-1 "=" expr-2 ")")
55 | (= (interpret-exprs #'expr-1)
56 | (interpret-exprs #'expr-2))
57 | ]
58 | [({~literal bool} "(" bool-1 "&" bool-2 ")")
59 | (equal? (interpret-bool #'bool-1)
60 | (interpret-bool #'bool-2))
61 | ]
62 | [({~literal bool} "¬" bool-1)
63 | (not (interpret-bool #'bool-1))
64 | ]
65 | )
66 | )
67 |
68 | (define (interpret-exprs expr-stx)
69 | (syntax-parse expr-stx
70 |
71 | [({~literal exprs} expr)
72 | (syntax-parse #'expr
73 | [({~literal num} n)
74 | (syntax->datum #'n)
75 | ]
76 | [({~literal var} variable)
77 | (if (hash-has-key?
78 | variables (syntax->datum #'variable))
79 | (dict-ref variables
80 | (syntax->datum #'variable))
81 | 0)
82 | ]
83 | )
84 | ]
85 |
86 | [({~literal exprs}
87 | "(" expr-1 "+" expr-2 ")")
88 | (+ (interpret-exprs #'expr-1)
89 | (interpret-exprs #'expr-2))
90 | ]
91 |
92 | [({~literal exprs}
93 | expr-1 "+" expr-2)
94 | (+ (interpret-exprs #'expr-1)
95 | (interpret-exprs #'expr-2))
96 | ]
97 | )
98 | )
99 |
100 | (define run
101 | (lambda (input)
102 | (interpret-program input)
103 | )
104 | )
105 | (provide run)
106 |
--------------------------------------------------------------------------------
/material/capítulo_15/ejemplos/lexer.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 | (require br-parser-tools/lex)
3 | (require brag/support)
4 |
5 | (define-lex-abbrev digits (:+ (char-set "0123456789")))
6 | (define (lexer-tokenize ip)
7 | (port-count-lines! ip)
8 | (define my-lexer
9 | (lexer-src-pos
10 | [(:or "(" ")" ":=" "+" "&" ";" "¬" "if" "while" "="
11 | "print" "then" "do" "else" "true" "false")
12 | (token lexeme lexeme)]
13 | [lower-case (token 'VARIABLE lexeme)]
14 | [digits (token 'INT (string->number lexeme))]
15 | [whitespace
16 | (token 'WHITESPACE lexeme #:skip? #t)]
17 | [(eof)
18 | (void)]
19 | ))
20 | (define (next-token) (my-lexer ip))
21 | next-token)
22 |
23 | (provide lexer-tokenize)
--------------------------------------------------------------------------------
/material/capítulo_15/ejemplos/parser.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (require syntax/parse)
4 | (require "while.rkt")
5 |
6 | (define (parser lexer)
7 | (parse lexer)
8 | )
9 | (provide parser)
--------------------------------------------------------------------------------
/material/capítulo_15/ejemplos/test.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (require syntax/parse)
4 | (require "lexer.rkt")
5 | (require "parser.rkt")
6 | (require "interpreter.rkt")
7 |
8 | (run (parser (lexer-tokenize (open-input-string
9 | "x := 0;
10 | y := 5;
11 | while ¬((x + 1) = y) do
12 | x := x + 1;
13 | print(x)
14 | "))))
15 |
16 | (run (parser (lexer-tokenize (open-input-string
17 | "
18 | x := 0;
19 | y := 5;
20 | while ¬((x + 1) = y) do
21 | if ¬(x = y) then
22 | y := x + 1
23 | else
24 | y := 0;
25 |
26 | print(x)
27 | "))))
28 |
29 |
30 |
31 | (run (parser (lexer-tokenize (open-input-string
32 | "
33 | x := 0;
34 | y := 1;
35 | if (x = y) then
36 | x := x + 1000
37 | else
38 | x := 100;
39 |
40 | print(x)
41 | "))))
42 |
43 |
44 | (run (parser (lexer-tokenize (open-input-string
45 | "
46 | if (false & true) then
47 | x := 0
48 | else
49 | if (true & true) then
50 | x := 1
51 | else
52 | x := 0;
53 |
54 | print(x)
55 | "))))
56 |
57 |
58 | (parser (lexer-tokenize (open-input-string
59 | "
60 | x := 0;
61 | y := 1
62 | ")))
--------------------------------------------------------------------------------
/material/capítulo_15/ejemplos/while.rkt:
--------------------------------------------------------------------------------
1 | #lang brag
2 | program : program ";" program
3 | | "if" bool "then" program "else" program
4 | | "while" bool "do" program
5 | | "print" "(" exprs ")"
6 | | var ":=" exprs
7 |
8 | bool : "true"
9 | | "false"
10 | | "(" exprs "=" exprs ")"
11 | | "(" bool '&' bool ")"
12 | | "¬" bool
13 |
14 | exprs : "(" exprs '+' exprs ")"
15 | | exprs '+' exprs
16 | | var
17 | | num
18 |
19 | var : VARIABLE
20 | num: INT
--------------------------------------------------------------------------------
/material/capítulo_15/figuras/15.1.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_15/figuras/15.1.PNG
--------------------------------------------------------------------------------
/material/capítulo_15/figuras/15.2.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_15/figuras/15.2.PNG
--------------------------------------------------------------------------------
/material/capítulo_15/figuras/15.3.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_15/figuras/15.3.PNG
--------------------------------------------------------------------------------
/material/capítulo_15/figuras/15.4.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_15/figuras/15.4.PNG
--------------------------------------------------------------------------------
/material/capítulo_15/figuras/15.5.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_15/figuras/15.5.PNG
--------------------------------------------------------------------------------
/material/capítulo_3/figuras/3.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_3/figuras/3.1.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.1-blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.1-blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.1.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.10.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.10blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.10blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.11.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.11blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.11blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.2.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.2blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.2blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.3.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.3blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.3blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.4.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.4blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.4blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.5.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.5blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.5blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.6.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.6blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.6blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.7.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.7blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.7blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.8.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.8blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.8blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.9.png
--------------------------------------------------------------------------------
/material/capítulo_5/figuras/5.9blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_5/figuras/5.9blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_6/figuras/6.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_6/figuras/6.1.png
--------------------------------------------------------------------------------
/material/capítulo_6/figuras/6.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_6/figuras/6.2.png
--------------------------------------------------------------------------------
/material/capítulo_6/figuras/6.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_6/figuras/6.3.png
--------------------------------------------------------------------------------
/material/capítulo_6/figuras/6.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_6/figuras/6.4.png
--------------------------------------------------------------------------------
/material/capítulo_6/figuras/6.4blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_6/figuras/6.4blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.1.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.1blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.1blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.2.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.2blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.2blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.3.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.3blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.3blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.4.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.4blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.4blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.5.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.5blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.5blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.6.png
--------------------------------------------------------------------------------
/material/capítulo_7/figuras/7.6blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_7/figuras/7.6blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_8/figuras/8.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_8/figuras/8.1.png
--------------------------------------------------------------------------------
/material/capítulo_8/figuras/8.1blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_8/figuras/8.1blancoynegro.png
--------------------------------------------------------------------------------
/material/capítulo_9/figuras/9.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_9/figuras/9.1.png
--------------------------------------------------------------------------------
/material/capítulo_9/figuras/9.1blancoynegro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Marcombo/computacion-calculo-lambda-programacion-funcional/caea3048be07f4a971137c8443c84be99532e3bf/material/capítulo_9/figuras/9.1blancoynegro.png
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_12/ex-12-1.py:
--------------------------------------------------------------------------------
1 | def ackermann(m, n):
2 | if m == 0:
3 | return n + 1
4 | if n == 0:
5 | return ackermann(m - 1, 1)
6 | scd_arg = ackermann(m, n - 1)
7 | return ackermann(m - 1, scd_arg)
8 |
9 |
10 | if __name__ == '__main__':
11 | print(ackermann(2, 5))
12 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_12/ex-12-1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (define (ackermann m n)
4 | (cond ((= m 0) (+ n 1))
5 | ((and (> m 0) (= n 0)) (ackermann (- m 1) 1))
6 | (else (ackermann (- m 1)
7 | (ackermann m (- n 1))))))
8 |
9 | (ackermann 2 5)
10 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_12/ex-12-2.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (define (third-a? tuple)
4 | (match tuple
5 | [(list _ _ "a" _) #t]
6 | [else #f]))
7 |
8 | (third-a? '(1 2 "a" 3))
9 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_12/ex-12-3.hs:
--------------------------------------------------------------------------------
1 | -- |
2 | -- >>> copyList [1, 2, 3]
3 | -- [1,2,3]
4 | copyList :: [a] -> [a]
5 | copyList [] = []
6 | copyList (x:xs) = [x] ++ copyList xs
7 |
8 | -- |
9 | -- >>> mapIncrement [1, 2, 3]
10 | -- [2,3,4]
11 | mapIncrement :: [Int] -> [Int]
12 | mapIncrement = map (1 +)
13 |
14 | -- |
15 | -- >>> reduce (+) [1, 2, 3]
16 | -- 6
17 | reduce :: (a -> a -> a) -> [a] -> a
18 | reduce f [x] = x
19 | reduce f (x:y:xs) = reduce f ((f x y) : xs)
20 |
21 | -- |
22 | -- >>> filterGt0 [1, -2, 3]
23 | -- [1,3]
24 | filterGt0 :: [Int] -> [Int]
25 | filterGt0 = filter (> 0)
26 |
27 | -- |
28 | -- >>> checkStructure [1]
29 | -- "singleton list"
30 | -- >>> checkStructure [1, 2]
31 | -- "two elements list"
32 | checkStructure :: [a] -> String
33 | checkStructure [x] = "singleton list"
34 | checkStructure [x, y] = "two elements list"
35 | checkStructure _ = "unknown type"
36 |
37 | -- |
38 | -- >>> checkAndRrsult [10,10]
39 | -- Just "is twenty"
40 | -- >>> checkAndRrsult [15,15]
41 | -- Just "is thirty"
42 | -- >>> checkAndRrsult [1,12]
43 | -- Nothing
44 | -- >>> checkAndRrsult [12]
45 | -- Nothing
46 | checkAndRrsult :: [Int] -> Maybe String
47 | checkAndRrsult [x, y]
48 | | sumIs 20 = Just "is twenty"
49 | | sumIs 30 = Just "is thirty"
50 | where elSum = x + y
51 | sumIs = (elSum ==)
52 | checkAndRrsult _ = Nothing
53 |
54 | -- |
55 | -- >>> head $ listInfinite 1
56 | -- 1
57 | -- >>> take 2 $ listInfinite 1
58 | -- [1,2]
59 | listInfinite :: Int -> [Int]
60 | listInfinite x = [x..]
61 |
62 | -- |
63 | -- >>>sumEqual 5 10 $ 3 + 2 + 10
64 | -- True
65 | sumEqual :: Int -> Int -> Int -> Bool
66 | sumEqual a b result = (a + b) == result
67 |
68 | -- |
69 | -- >>> concatList [0..2] [3..5]
70 | -- [0,1,2,3,4,5]
71 | -- >>>
72 | --
73 | concatList :: [a] -> [a] -> [a]
74 | concatList = (++)
75 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_13/ex-13-1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (define table (make-immutable-hash '(["cálculo" . "lambda"]
4 | ["máquina" . "turing"])))
5 |
6 | table
7 | ;; '#hash(("cálculo" . "lambda") ("máquina" . "turing"))
8 |
9 | ;;; La función hash-set ya actualiza el valor de una clave concreta si
10 | ;;; existe en el hash. Nos basta con coprobar que la clave existe, ya
11 | ;;; que, de otro modo, la creará. En ese caso, se lanza una excepción.
12 | (define (hash-reset hash key new-val)
13 | (unless (hash-has-key? hash key)
14 | (error "no value found for key: " key))
15 | (hash-set hash key new-val))
16 |
17 | (hash-reset table "cálculo" "LAMBDA")
18 | ;; '#hash(("cálculo" . "LAMBDA") ("máquina" . "turing"))
19 |
20 | (hash-reset table "máquina" "de Turing")
21 | ;; '#hash(("cálculo" . "lambda") ("máquina" . "de Turing"))
22 |
23 | (hash-reset (hash-reset table "cálculo" "LAMBDA") "máquina" "A Machine")
24 | ;; '#hash(("cálculo" . "LAMBDA") ("máquina" . "A Machine"))
25 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_13/ex-13-2.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (define (pair-reverse pair)
4 | (cons (cdr pair) (car pair)))
5 |
6 | (define x (cons 1 2))
7 |
8 | x
9 | ;; '(1 . 2)
10 |
11 | (pair-reverse x)
12 | ;; '(2 . 1)
13 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_13/ex-13-3.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 |
4 | ;;; Creadores es inspectores
5 |
6 | ;; Al encapsular la estructura de datos con creadores e inspectores,
7 | ;; cuando queramos cambiar la implementación sólo tendremos que
8 | ;; modificar esto, y no el resto del sistema.
9 |
10 | ;; Definimos dos creadores de nodes a partir de listas para poder
11 | ;; visualizar el resultado de las llamadas en forma de lista.
12 | (define (make-node value left right)
13 | (list value left right))
14 |
15 | (define (start-node value)
16 | (make-node value null null))
17 |
18 | ;; A continuación, los inspectores
19 | (define (node-value node)
20 | (car node))
21 |
22 | (define (node-left node)
23 | (cadr node))
24 |
25 | (define (node-right node)
26 | (caddr node))
27 |
28 | (define (node-childs node)
29 | (list (node-left node)
30 | (node-right node)))
31 |
32 | (define (min-succesor tree)
33 | (if (null? (node-left tree))
34 | (node-value tree)
35 | (min-succesor (node-left tree))))
36 |
37 | ;;; Predicados
38 |
39 | (define (node-leave? node)
40 | (andmap null? (node-childs node)))
41 |
42 | (define (node-single-child? node)
43 | (apply xor (map null? (node-childs node))))
44 |
45 | ;;; Funciones auxiliares
46 |
47 | ;; Negación de un predicado, para no tener que insertar una expresión
48 | ;; lambda sólo para el caso.
49 | (define (not? p?)
50 | (λ (x) (not (p? x))))
51 |
52 | (define (node-single-child node)
53 | (unless (node-single-child? node)
54 | (error "node should have only one child."))
55 | (car (filter (not? null?) (node-childs node))))
56 |
57 | ;; Pequeño método de ayuda que cambia el orden de los argumentos en
58 | ;; una función binaria. Es decir (flip +) hace que (/ a b) se
59 | ;; convierta en (/ b a). Esto lo usaremos a continuación, en
60 | ;; make-tree-from-list.
61 | (define (flip fn)
62 | (λ (a b) (fn b a)))
63 |
64 | ;;; Inserción de datos
65 |
66 | ;; Definimos la función para insertar valores en un árbol binario
67 | (define (binary-tree-insert tree value)
68 | (define (insert-node-at wich [new-val #f])
69 | (let* ([start (start-node value)]
70 | [wich-value (or new-val start)]
71 | [left (if (equal? wich 'left) wich-value (node-left tree))]
72 | [right (if (equal? wich 'right) wich-value (node-right tree))])
73 | (make-node (node-value tree) left right)))
74 | (cond [(null? tree) (start-node value)]
75 | [(> value (node-value tree))
76 | (insert-node-at 'right (and (not (null? (node-right tree)))
77 | (binary-tree-insert (node-right tree) value)))]
78 | [(< value (node-value tree))
79 | (insert-node-at 'left (and (not (null? (node-left tree)))
80 | (binary-tree-insert (node-left tree) value)))]
81 | [else tree]))
82 |
83 | ;; Ahora podemos definir la creación de un árbol binario a partir de
84 | ;; binary-tree-insert de manera muy sencilla, usando la función foldl
85 | ;; y ayudándonos de la función flip, que evitará que usemos una lambda
86 | ;; y mejorando la legibilidad del código.
87 | (define (make-tree-from-list lst)
88 | (foldl (flip binary-tree-insert) null lst))
89 |
90 |
91 | (define my-tree (make-tree-from-list (list 9 7 5 1 6 8 10 11 12)))
92 |
93 | my-tree
94 | ;; '(9 (7 (5 (1 () ()) (6 () ())) (8 () ())) (10 () (11 () (12 () ()))))
95 |
96 | ;; 9
97 | ;; / \
98 | ;; / \
99 | ;; 7 10
100 | ;; / \ \
101 | ;; / \ \
102 | ;; 5 8 11
103 | ;; / \ \
104 | ;; / \ \
105 | ;; 1 6 12
106 |
107 | (binary-tree-insert my-tree 4)
108 | ;; '(9 (7 (5 (1 () (4 () ())) (6 () ())) (8 () ())) (10 () (11 () (12 () ()))))
109 |
110 | ;; 9
111 | ;; / \
112 | ;; / \
113 | ;; 7 10
114 | ;; / \ \
115 | ;; / \ \
116 | ;; 5 8 11
117 | ;; / \ \
118 | ;; / \ \
119 | ;; 1 6 12
120 | ;; /
121 | ;; /
122 | ;; 4
123 |
124 |
125 | ;;; Eliminación de datos
126 |
127 | ;; Para eliminar un elemento, buscamos el elemento situada más abajo y
128 | ;; a la derecha. Eliminamos el elemento x y lo sustituimos con este
129 | ;; último, el cual eliminamos también.
130 |
131 | (define (binary-tree-remove tree value)
132 | (cond [(null? tree) tree]
133 | [(> value (node-value tree))
134 | (make-node (node-value tree)
135 | (node-left tree)
136 | (binary-tree-remove (node-right tree) value))]
137 | [(< value (node-value tree))
138 | (make-node (node-value tree)
139 | (binary-tree-remove (node-left tree) value)
140 | (node-right tree))]
141 | [else (cond [(node-leave? tree) null]
142 | [(node-single-child? tree) (node-single-child tree)]
143 | [else (let ([min-sucss (min-succesor (node-right tree))])
144 | (make-node min-sucss
145 | (node-left tree)
146 | (binary-tree-remove (node-right tree)
147 | min-sucss)))])]))
148 |
149 | ;; Eliminar un nodo sin hijos
150 | (binary-tree-remove my-tree 12)
151 | ;; '(9 (7 (5 (1 () ()) (6 () ())) (8 () ())) (10 () (11 () ())))
152 |
153 | ;; 9
154 | ;; / \
155 | ;; / \
156 | ;; 7 10
157 | ;; / \ \
158 | ;; / \ \
159 | ;; 5 8 11
160 | ;; / \
161 | ;; / \
162 | ;; 1 6
163 |
164 | (binary-tree-remove my-tree 8)
165 | ;; '(9 (7 (5 (1 () ()) (6 () ())) ()) (10 () (11 () (12 () ()))))
166 |
167 | ;; 9
168 | ;; / \
169 | ;; / \
170 | ;; 7 10
171 | ;; / \
172 | ;; / \
173 | ;; 5 11
174 | ;; / \ \
175 | ;; / \ \
176 | ;; 1 6 12
177 |
178 | ;; Eliminar un nodo con un solo hijo
179 | (binary-tree-remove my-tree 10)
180 | ;; '(9 (7 (5 (1 () ()) (6 () ())) (8 () ())) (11 () (12 () ())))
181 |
182 | ;; 9
183 | ;; / \
184 | ;; / \
185 | ;; 7 11
186 | ;; / \ \
187 | ;; / \ \
188 | ;; 5 8 12
189 | ;; / \
190 | ;; / \
191 | ;; 1 6
192 |
193 | (binary-tree-remove (binary-tree-remove my-tree 8) 7)
194 | ;; '(9 (5 (1 () ()) (6 () ())) (10 () (11 () (12 () ()))))
195 |
196 | ;; 9
197 | ;; / \
198 | ;; / \
199 | ;; 5 10
200 | ;; / \ \
201 | ;; / \ \
202 | ;; 1 6 11
203 | ;; \
204 | ;; \
205 | ;; 12
206 |
207 | ;; Eliinar un nodo con dos hijos
208 | (binary-tree-remove my-tree 7)
209 | ;; '(9 (8 (5 (1 () ()) (6 () ())) ()) (10 () (11 () (12 () ()))))
210 |
211 | ;; 9
212 | ;; / \
213 | ;; / \
214 | ;; 8 10
215 | ;; / \
216 | ;; / \
217 | ;; 5 11
218 | ;; / \ \
219 | ;; / \ \
220 | ;; 1 6 12
221 |
222 | (binary-tree-remove my-tree 5)
223 | ;; '(9 (7 (6 (1 () ()) ()) (8 () ())) (10 () (11 () (12 () ()))))
224 |
225 | ;; 9
226 | ;; / \
227 | ;; / \
228 | ;; 7 10
229 | ;; / \ \
230 | ;; / \ \
231 | ;; 6 8 11
232 | ;; / \
233 | ;; / \
234 | ;; 1 12
235 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_13/ex-13-4.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | ;;; Definimos alguas funciones auxiliares genéricas
4 | (define (not-false? val)
5 | (not (eq? #f val)))
6 |
7 | (define (any p? lst)
8 | (not-false? (ormap p? lst)))
9 |
10 | (define (all p? lst)
11 | (not-false? (andmap p? lst)))
12 |
13 | (define (shorter-list list-of-lists)
14 | (define (null-or-empty-? lst)
15 | (or (null? lst) (empty? lst)))
16 | (foldl (λ (lst res)
17 | (cond [(null-or-empty-? res) lst]
18 | [(null-or-empty-? lst) res]
19 | [(< (length res) (length lst)) res]
20 | [else lst]))
21 | null
22 | list-of-lists))
23 |
24 | ;;; Deifinimos la estructura de datos
25 | (define (make-node node . edges)
26 | (cons node edges))
27 |
28 | (define (make-grapth . nodes)
29 | nodes)
30 |
31 | (define (node-value node)
32 | (car node))
33 |
34 | (define (node-edges node)
35 | (cdr node))
36 |
37 | (define (node-grade node)
38 | (length (node-edges node)))
39 |
40 | (node-grade (make-node 3 1 5))
41 | ;; 2
42 |
43 | (define (node-find val graph)
44 | (assoc val graph))
45 |
46 | (node-find 1 (make-grapth (make-node 2 3 4)
47 | (make-node 1 2 3)))
48 | ;; '(1 2 3)
49 |
50 | ;;; Algunos predicados
51 | (define (node=? n1 n2)
52 | (and (= (node-value n1) (node-value n2))
53 | (= (length n1) (length n2))
54 | (let ([n1-edges (node-edges n1)])
55 | (all (λ (n2-edge)
56 | (member n2-edge n1-edges))
57 | (node-edges n2)))))
58 |
59 | (node=? (make-node 1 2 3) (make-node 1 3 2))
60 | ;; #t
61 | (node=? (make-node 1 2 3) (make-node 1 4 2))
62 | ;; #f
63 | (node=? (make-node 1 2 3) (make-node 3 2 1))
64 | ;; #f
65 |
66 | (define (node-exists? node graph)
67 | (ormap (λ (graph-node)
68 | (node=? node graph-node))
69 | graph))
70 |
71 | (define graph (make-grapth (make-node 4 5 7 8)
72 | (make-node 3)
73 | (make-node 1 2 3)
74 | (make-node 2 10)))
75 |
76 | (node-exists? (make-node 1 2 3) graph)
77 | ;; #t
78 |
79 | (define graph2 (make-grapth (make-node 4 5 7 8)
80 | (make-node 3)
81 | (make-node 2 10)))
82 |
83 | (node-exists? (make-node 1 2 3) graph2)
84 | ;; #f
85 |
86 | (define (node-no-edges? node)
87 | (null? (node-edges node)))
88 |
89 | (define (node-one-edge? node)
90 | (= (length (node-edges node)) 1))
91 |
92 | (define (node-lonely-edge node)
93 | (if (node-one-edge? node)
94 | (car (filter (compose not null?) (node-edges node)))
95 | (error "Not a lonely node")))
96 | ;;; Camino más corto
97 |
98 | (define (node-shorter-path start target graph)
99 | (define (iter node path [result null])
100 | (let ([actual-val (node-value node)]
101 | [target-val (node-value target)])
102 | (cond [(= actual-val target-val) (append path (list actual-val))]
103 | [(node-no-edges? node) null]
104 | [(node-one-edge? node)
105 | (iter (remove actual-val (node-find (node-lonely-edge node) graph))
106 | (append path (list actual-val)))]
107 | [else (let ([not-visited-edges
108 | (filter (λ (edge) (not (member edge path)))
109 | (node-edges node))])
110 | (shorter-list (map (λ (edge)
111 | (iter (make-node actual-val edge)
112 | path))
113 | not-visited-edges)))])))
114 | (shorter-list (map (λ (edge)
115 | (iter (remove (node-value start) (node-find edge graph))
116 | (list (node-value start))))
117 | (node-edges start))))
118 |
119 | (define n1 (make-node 1 2 3 9))
120 | (define n2 (make-node 2 1 4 6))
121 | (define n3 (make-node 3 1 7 12 13))
122 | (define n4 (make-node 4 2 5))
123 | (define n5 (make-node 5 4))
124 | (define n6 (make-node 6 2 11 12))
125 | (define n7 (make-node 7 3 12))
126 | (define n8 (make-node 8 11 12))
127 | (define n9 (make-node 9 1 13))
128 | (define n11 (make-node 11 6 8))
129 | (define n12 (make-node 12 3 8 6 7))
130 | (define n13 (make-node 13 3 9))
131 |
132 | (define graph3 (make-grapth n1 n2 n3 n4 n5 n6 n7 n8 n9 n11 n12 n13))
133 |
134 | (node-shorter-path n1 n12 graph3)
135 | ;;'(1 3 12)
136 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_13/ex-13-5.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | (define (set-insert el s)
4 | (if (member el s)
5 | s
6 | (cons el s)))
7 |
8 | (define (make-set . lst)
9 | (foldr set-insert null lst))
10 |
11 | (define s1 (make-set 1 2 3))
12 | s1
13 | ;; '(1 2 3)
14 | (define s2 (make-set '2 5))
15 | s2
16 | ;; '(2 5)
17 |
18 | (set-insert 5 s1)
19 | ;; '(5 1 2 3)
20 |
21 | (set-insert 3 s1)
22 | ;; '(1 2 3)
23 |
24 | (define (set-intersection s1 s2)
25 | (let* ([longest-set (if (>= (length s1) (length s2)) s1 s2)]
26 | [shortest-set (if (equal? longest-set s1) s2 s1)])
27 | (filter (λ (el) (member el shortest-set)) longest-set)))
28 |
29 | (set-intersection s1 s2)
30 | ;; '(2)
31 |
32 | (define (set-union s1 s2)
33 | (apply make-set (append s1 s2)))
34 |
35 | (set-union s1 s2)
36 | ;; '(1 3 2 5)
37 |
38 | ;; Como extra, ya que los sets no tienen orden, haremos una función
39 | ;; para compararlos
40 | (define (set-equal-? s1 s2)
41 | (and (= (length s1) (length s2))
42 | (not (eq? #f
43 | (ormap (λ (el)
44 | (member el s2))
45 | s1)))))
46 |
47 | (set-equal-? s1 s2)
48 | ;; #f
49 | (define s3 (make-set 3 2 1))
50 | s3
51 | ;; '(3 2 1)
52 |
53 | (set-equal-? s1 s3)
54 | ;; #t
55 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_14/ex-14-1.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | ;;; Estructuras de datos
4 |
5 | ;; Definimos la estructura punto con las coordenadas x e y
6 | (struct point (x y) #:transparent)
7 |
8 | ;; En función de las coordenadas, definimos triángulo como una
9 | ;; estructura de tres punto, con el vértice solitario siempre hacia
10 | ;; arriba, ya que es lo que necesitamos para este problema.
11 | (struct triangle (upper left right) #:transparent)
12 |
13 | ;; Función para calcular la altura de un triángulo equilátero. La
14 | ;; parte de la raíz cuadrada de 3 entre 2 la sacamos fuera, en una
15 | ;; variable para que se calcule cada vez.
16 | (define 3-sqrt/2 (/ (sqrt 3) 2))
17 |
18 | (define (height side)
19 | (* side 3-sqrt/2))
20 |
21 | ;; Función para calcular la longitud de un lado, dado un triángule
22 | ;; equilátero
23 | (define (side trngl)
24 | (- (point-x (triangle-right trngl))
25 | (point-x (triangle-left trngl))))
26 |
27 | ;; En función de estas dos estructuras, definimos la forma de crear un
28 | ;; triángulo equilátero a partir del punto del vértice de abajo a la
29 | ;; izquierda y un lado, hacinedo uso de la altura
30 | (define (make-triangle left-point side)
31 | (let ([left-x (point-x left-point)]
32 | [left-y (point-y left-point)])
33 | (triangle (point (+ left-x (/ side 2))
34 | (+ left-y (height side)))
35 | left-point
36 | (point (+ left-x side) left-y))))
37 |
38 | ;; Esta función recibe un triángulo y devuelve una lista con los tres
39 | ;; triángulos internos que contiene, de forma que quede un triángulo
40 | ;; vacío invertido en el centro
41 | (define (divide-by-three trngl)
42 | (let* ([t-side (/ (side trngl) 2)]
43 | [left (make-triangle (triangle-left trngl) t-side)]
44 | [right (make-triangle (triangle-right left) t-side)]
45 | [upper (make-triangle (triangle-upper left) t-side)])
46 | `(,left ,right ,upper)))
47 |
48 | ;; Esta función recibe un triángulo y el número de recursiones, y
49 | ;; devuelve una lista formada por el triángulo de sierpinski.
50 | (define (sierpinski-triangle trngl n)
51 | (if (= n 0)
52 | null
53 | (let ([inner-triangles (divide-by-three trngl)]
54 | [sierpinski-next (λ (t) (sierpinski-triangle t (- n 1)))])
55 | (append `(,trngl)
56 | (append-map sierpinski-next inner-triangles)))))
57 |
58 | (sierpinski-triangle (make-triangle (point 0 0) 4) 2)
59 |
60 | ;; (list
61 | ;; (triangle (point 2 3.4641016151377544) (point 0 0) (point 4 0))
62 | ;; (triangle (point 1 1.7320508075688772) (point 0 0) (point 2 0))
63 | ;; (triangle (point 3 1.7320508075688772) (point 2 0) (point 4 0))
64 | ;; (triangle (point 2 3.4641016151377544) (point 1 1.7320508075688772) (point 3 1.7320508075688772)))
65 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_14/ex-14-2.rkt:
--------------------------------------------------------------------------------
1 | #lang racket
2 |
3 | ;; Un Heap min o montículo mínimo es una estructura de árbol binario
4 | ;; en la que cada nodo, menos el último, tiene dos hijos, y cada uno
5 | ;; de ellos es mayor al padre. Se rellena de izquierda a derecha
6 |
7 | ;;; Estructura de datos
8 |
9 | (define (just v)
10 | `(,v))
11 |
12 | (define nothing null)
13 |
14 | (define just? (compose not null?))
15 |
16 | (define nothing? null?)
17 |
18 | (define from-just car)
19 |
20 | (define (heap-insert-last hp el)
21 | (apply vector
22 | (append (vector->list hp) `(,el))))
23 |
24 | (define (parent-index i)
25 | (quotient (- i 1) 2))
26 |
27 | (define (node-value hp i)
28 | (if (and (>= i 0) (< i (vector-length hp)))
29 | (just (vector-ref hp i))
30 | nothing))
31 |
32 | (define (parent-node hp i)
33 | (if (= i 0)
34 | nothing
35 | (node-value hp (parent-index i))))
36 |
37 | (define (left-child-index i)
38 | (+ (* 2 i) 1))
39 |
40 | (define (left-child-node hp i)
41 | (node-value hp (left-child-index i)))
42 |
43 | (define (right-child-index i)
44 | (+ (* 2 i) 2))
45 |
46 | (define (right-child-node hp i)
47 | (node-value hp (right-child-index i)))
48 |
49 | (define (swap hp src-i dest-i)
50 | (let ([src-val (node-value hp src-i)]
51 | [dest-val (node-value hp dest-i)])
52 | (vector-set! hp dest-i (from-just src-val))
53 | (vector-set! hp src-i (from-just dest-val))
54 | hp))
55 |
56 | (define (float hp i)
57 | (let ([node (node-value hp i)]
58 | [parent (parent-node hp i)]
59 | [parent-i (parent-index i)])
60 | (if (and (just? parent) (just? node) (< (from-just node) (from-just parent)))
61 | (float (swap hp i parent-i) parent-i)
62 | hp)))
63 |
64 | (define (heap-insert hp el)
65 | (let ([unfloated-hp (heap-insert-last hp el)]
66 | [index (vector-length hp)])
67 | (float unfloated-hp index)))
68 |
69 | (heap-insert (vector 1 3 6 5 9) 2)
70 | ;; '#(1 3 2 5 9 6)
71 |
72 | (define (make-heap . n)
73 | (define (iter hp ls)
74 | (if (null? ls)
75 | hp
76 | (iter (heap-insert hp (car ls))
77 | (cdr ls))))
78 | (iter (vector) n))
79 |
80 | (make-heap 3 1 9 6 2 5)
81 | ;; '#(1 2 5 6 3 9)
82 |
83 | (define (kill-head-put-tail hp)
84 | (if (< (vector-length hp) 2)
85 | (vector)
86 | (let* ([last-indx (- (vector-length hp) 1)]
87 | [last-val (vector-ref hp last-indx)]
88 | [new-vec (make-vector last-indx last-val)])
89 | (vector-copy! new-vec 1 hp 1 last-indx)
90 | new-vec)))
91 |
92 | (define (sink hp i)
93 | (define (sink-swapping f)
94 | (let ([dest-idx (f i)])
95 | (sink (swap hp i dest-idx) dest-idx)))
96 | (let ([actual (node-value hp i)]
97 | [left (left-child-node hp i)]
98 | [right (right-child-node hp i)])
99 | (cond [(and (nothing? left) (nothing? right)) hp]
100 | [(and (just? left) (nothing? right) (> (from-just actual) (from-just left)))
101 | (sink-swapping left-child-index)]
102 | [(and (nothing? left) (just? right) (> (from-just actual) (from-just right)))
103 | (sink-swapping right-child-index)]
104 | [(and (just? left) (just? right))
105 | (let ([actual-val (from-just actual)]
106 | [left-val (from-just left)]
107 | [right-val (from-just right)])
108 | (if (or (> actual-val left-val) (> actual-val right-val))
109 | (if (< left-val right-val)
110 | (sink-swapping left-child-index)
111 | (sink-swapping right-child-index))
112 | hp))]
113 | [else hp])))
114 |
115 | (define (heap-remove hp)
116 | (let* ([removed (vector-ref hp 0)]
117 | [swapped-vec (kill-head-put-tail hp)]
118 | [new-heap (sink swapped-vec 0)])
119 | (cons removed new-heap)))
120 |
121 | (heap-remove '#(1 3 2 5 9 6))
122 | ;; '(1 . #(2 3 6 5 9))
123 |
124 | (define (heap-sort . lst)
125 | (define (iter hp lst-sort)
126 | (if (vector-empty? hp)
127 | lst-sort
128 | (let* ([state (heap-remove hp)]
129 | [actual (car state)]
130 | [new-hp (cdr state)])
131 | (iter new-hp (append lst-sort `(,actual))))))
132 | (iter (apply make-heap lst) '()))
133 |
134 | (heap-sort 8 1 3 4 5 7)
135 | ;; '(1 3 4 5 7 8)
136 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_14/ex-14-3.hs:
--------------------------------------------------------------------------------
1 |
2 | quickSort :: [Int] -> [Int]
3 | quickSort [] = []
4 | quickSort lst = let pivot = head lst
5 | left = filter (< pivot) lst
6 | right = filter (> pivot) lst in
7 | quickSort left ++ [pivot] ++ quickSort right
8 |
9 | mergeSort :: [Int] -> [Int]
10 | mergeSort [] = []
11 | mergeSort [x] = [x]
12 | mergeSort [x, y] = if x < y then [x, y] else [y, x]
13 | mergeSort lst = let midPoint = ((length lst) `div` 2)
14 | firsHalf = mergeSort $ take midPoint lst
15 | secondHalf = mergeSort $ drop midPoint lst in
16 | merge firsHalf secondHalf
17 |
18 | merge :: [Int] -> [Int] -> [Int]
19 | merge a [] = a
20 | merge [] b = b
21 | merge a@(x:xs) b@(y:ys) = if x < y
22 | then x : (merge xs b)
23 | else y : (merge a ys)
24 |
--------------------------------------------------------------------------------
/material/ejercicios_resueltos/capítulo_5/respuestas.md:
--------------------------------------------------------------------------------
1 | ### Notas previas:
2 | - Hemos cambiado el símbolo «λ» por «lambda» para que el intérprete lo pueda ejecutar.
3 | - Todos los ejercicios pueden ser verificados en: https://jacksongl.github.io/files/demo/lambda/
4 | - Algo importante de este intérprete es que renombra las variables, añadiendo un dígito al final, para evitar ambigüedades.
5 |
6 | ### 5-1
7 |
8 | ```
9 | ((lambda x.x) (lambda y.y)) (lambda z.z)
10 | ```
11 |
12 | Respuesta:
13 |
14 | ```
15 | (((λx.x) (λy.y)) (λz.z))
16 | ((λy.y) (λz.z))
17 | (λz.z)
18 | ```
19 |
20 |
21 | ### 5-2
22 |
23 | ```
24 | ((lambda x.(lambda y.y)) 1)
25 | ```
26 |
27 | Respuesta:
28 |
29 | ```
30 | ((λx.(λy.y)) 1)
31 | (λy.y)
32 | ```
33 |
34 | ### 5-3
35 |
36 | ```
37 | ((((lambda x.x) 1) 2) 3)
38 | ```
39 |
40 | Respuesta:
41 |
42 | ```
43 | ((((λx.x) 1) 2) 3)
44 | ((1 2) 3)
45 | ```
46 |
47 | ### 5-4
48 |
49 | ```
50 | ((lambda x.x) (lambda y.y)) ((lambda x.x) 2)
51 | ```
52 |
53 | Respuesta:
54 |
55 | ```
56 | (((λx.x) (λy.y)) ((λx0.x0) 2))
57 | ((λy.y) ((λx0.x0) 2))
58 | ((λx0.x0) 2)
59 | 2
60 | ```
61 |
62 | ### 5-5
63 |
64 | Hay un error en este ejercicio en el libro: no es «(lambda x.(xx) 1)» sino «(lambda x.(x x) 1)», como se ve a continuación:
65 |
66 | ```
67 | ((lambda x.(x x) 1) ((lambda y.2) (lambda z.z)))
68 | ```
69 |
70 | Respuesta:
71 |
72 | ```
73 | ((λx.((x x) 1)) ((λy.2) (λz.z)))
74 | ((((λy.2) (λz.z)) ((λy.2) (λz.z))) 1)
75 | ((((λy.2) (λz.z)) ((λx0.2) (λx1.x1))) 1)
76 | ((2 ((λx0.2) (λx1.x1))) 1)
77 | ((2 2) 1)
78 | ```
--------------------------------------------------------------------------------
/recomendaciones.md:
--------------------------------------------------------------------------------
1 | ### Más lecturas recomendadas
2 |
3 | En el epílogo de este trabajo añadi algunas recomendaciones de libros para ahondar en cada una de las tres parte del libro. Pues bien, en esta sección iré añadiendo algunas obras extras.
4 |
5 | #### Parte I
6 | - Rapaport, William J. - Philosophy of Computer Science. https://cse.buffalo.edu/~rapaport/Papers/phics.pdf Una amena introducción a la filosofía de la ciencia de la computación.
7 | - Eden, Amnon H. - «Three Paradigms of Computer Science.» Minds and Machines, vol. 17, no. 2, Aug. 2007, pp. 135–67. DOI.org (Crossref), doi:10.1007/s11023-007-9060-8. http://eden-study.org/?publications=20073paradigms
8 | - Este artículo es excelente. Presenta las tres manera de hacer computación: racionalista, tecnocrática y científica. Sobre esto hice un ep. del podcast: https://www.buzzsprout.com/758831/6501958
9 |
10 |
11 | #### Parte III
12 | - Okasaki, Chris. Purely Functional Data Structures. 1. paperback ed., transf. to digital printing, Cambridge Univ. Press, 2003. Un excelente libro sobre estructuras de datos funcionales (persistentes). Hice una breve introducción sobre esto en un ep. del podcast: https://www.buzzsprout.com/758831/4032086
13 |
14 |
15 |
--------------------------------------------------------------------------------