SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
Pensando FuncionalmentePensando Funcionalmente
Denis Fuenzalida – Agosto de 2013Denis Fuenzalida – Agosto de 2013
denis.fuenzalida@gmail.comdenis.fuenzalida@gmail.com
Programación funcional?Programación funcional?
•• Problema: no hay definiciónProblema: no hay definición universalmenteuniversalmente aceptadaaceptada
•• Funciones como elementos de primer nivel del lenguaje:Funciones como elementos de primer nivel del lenguaje:
““First Class FunctionsFirst Class Functions””
→→ es posible almacenares posible almacenar referenciasreferencias a funcionesa funciones
pasar funciones como→pasar funciones como→ parámetrosparámetros
→→ crear funciones que retornancrear funciones que retornan funcionesfunciones
DefiniciónDefinición
•• Mayor nivel de abstracción:Mayor nivel de abstracción:
más énfasis en el→más énfasis en el→ quéqué y no en ely no en el cómocómo
→→ menos código que comprendermenos código que comprender
→→ a veces, código más genérico y re-utilizablea veces, código más genérico y re-utilizable
•• EnEn ClojureClojure se prefieren funciones puras*se prefieren funciones puras*
son más fáciles de entender→son más fáciles de entender→
→→ más fáciles de testearmás fáciles de testear
→→ se pueden guardarse pueden guardar en cachéen caché y paralelizary paralelizar fácilmentefácilmente
BeneficiosBeneficios
Convertir de códigoConvertir de código
imperativo a funcionalimperativo a funcional
// Basado en StringUtils.java de Apache Commons Lang// Basado en StringUtils.java de Apache Commons Lang
/*/*
* Spec:* Spec:
**
* StringUtils.indexOfAny(null, *) = -1* StringUtils.indexOfAny(null, *) = -1
* StringUtils.indexOfAny("", *) = -1* StringUtils.indexOfAny("", *) = -1
* StringUtils.indexOfAny(*, null) = -1* StringUtils.indexOfAny(*, null) = -1
* StringUtils.indexOfAny(*, []) = -1* StringUtils.indexOfAny(*, []) = -1
* StringUtils.indexOfAny("* StringUtils.indexOfAny("zzzabyycdxx",['z','a']) = 0zabyycdxx",['z','a']) = 0
* StringUtils.indexOfAny("zza* StringUtils.indexOfAny("zzabbyycdxx",['b','y']) = 3yycdxx",['b','y']) = 3
* StringUtils.indexOfAny("aba", ['z']) = -1* StringUtils.indexOfAny("aba", ['z']) = -1
*/*/
// Basado en StringUtils.java de Apache Commons Lang// Basado en StringUtils.java de Apache Commons Lang
classclass StringUtils {StringUtils {
public staticpublic static intint indexOfAnyindexOfAny(String(String strstr, char[], char[] toSearchtoSearch){){
ifif (isEmpty(str) || ArrayUtils.isEmpty(toSearch)){(isEmpty(str) || ArrayUtils.isEmpty(toSearch)){
returnreturn -1;-1;
}}
forfor (int i = 0; i < str.length(); i++){(int i = 0; i < str.length(); i++){
charchar chch = str.charAt(i);= str.charAt(i);
forfor (int(int jj = 0; j < toSearch.length; j++){= 0; j < toSearch.length; j++){
ifif (searchChars[j] == ch){(searchChars[j] == ch){
returnreturn i;i;
}}
}}
}}
returnreturn -1;-1;
}}
}}
// Simplificando condiciones de borde...// Simplificando condiciones de borde...
classclass StringUtils {StringUtils {
public staticpublic static intint indexOfAnyindexOfAny(String(String strstr, char[], char[] toSearchtoSearch){){
when (toSearch) {when (toSearch) {
forfor (int i = 0; i < str.length(); i++){(int i = 0; i < str.length(); i++){
charchar chch = str.charAt(i);= str.charAt(i);
forfor (int(int jj = 0; j < toSearch.length; j++){= 0; j < toSearch.length; j++){
ifif (searchChars[j] == ch){(searchChars[j] == ch){
returnreturn i;i;
}}
}}
}}
}}
}}
}}
// En un lenguaje dinámico* podemos quitar tipos/clases:// En un lenguaje dinámico* podemos quitar tipos/clases:
indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){
when (toSearch) {when (toSearch) {
forfor (i = 0; i < str.length(); i++){(i = 0; i < str.length(); i++){
chch = str.charAt(i);= str.charAt(i);
forfor ((jj = 0; j < toSearch.length; j++){= 0; j < toSearch.length; j++){
ifif (searchChars[j] == ch){(searchChars[j] == ch){
returnreturn i;i;
}}
}}
}}
}}
}}
// pseudo-codigo// pseudo-codigo
indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){
when (toSearch) {when (toSearch) {
forfor (i = 0; i < str.length(); i++){(i = 0; i < str.length(); i++){
chch = str.charAt(i);= str.charAt(i);
when toSearch(ch) i; // Busca 'ch', retorna iwhen toSearch(ch) i; // Busca 'ch', retorna i
}}
}}
}}
// Usando una list-comprehension para iterar// Usando una list-comprehension para iterar
indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){
when (toSearch) {when (toSearch) {
forfor ([i, ch] in indexed(str)){([i, ch] in indexed(str)){
when toSearch(ch) i;when toSearch(ch) i;
}}
}}
}}
// pseudo-codigo// pseudo-codigo
indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){
when (toSearch) {when (toSearch) {
forfor ([i, ch] in indexed(str)){([i, ch] in indexed(str)){
when toSearch(ch) i;when toSearch(ch) i;
}}
}}
}}
;; Version Clojure;; Version Clojure
((defndefn index-filterindex-filter [coll pred][coll pred]
((whenwhen predpred
((forfor [[idx elt] (indexed coll)[[idx elt] (indexed coll) :when:when (pred elt)] idx)))(pred elt)] idx)))
Imperativa Funcional
Funciones 1 1
Clases 1 0
Puntos internos
de retorno
2 0
Variables 3 0
Ramificaciones 4 0
Operaciones
booleanas
1 0
Llamadas a
funciones
6 3
Total 18 4
Complejidad de cada versiónComplejidad de cada versión
;; Es correcta esta implementación?;; Es correcta esta implementación?
((defndefn indexedindexed [s] ([s] (mapmap vector (vector (iterateiterate inc 0) s))inc 0) s))
((defndefn index-filterindex-filter [coll pred][coll pred]
((whenwhen predpred
((forfor [[idx elt] (indexed coll)[[idx elt] (indexed coll) :when:when (pred elt)] idx)))(pred elt)] idx)))
;; StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0;; StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
;; StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3;; StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
(index-filter "zzabyycdxx" #{z a})(index-filter "zzabyycdxx" #{z a})
;; => (;; => (00 1 2)1 2)
(index-filter "zzabyycdxx" #{b y})(index-filter "zzabyycdxx" #{b y})
;; => (;; => (33 4 5)4 5)
;; index-filter retorna una lista* de TODOS los calces!;; index-filter retorna una lista* de TODOS los calces!
;; Indices de 'cara' en una lista de tiradas de moneda:;; Indices de 'cara' en una lista de tiradas de moneda:
(index-filter [(index-filter [:c :s :c :c :s :s :c :s :c :s :c:c :s :c :c :s :s :c :s :c :s :c] #{] #{:c:c})})
;; => (0 2 3 6 8 10);; => (0 2 3 6 8 10)
;; Cuál es el primer número de Fibonacci mayor que 1000?;; Cuál es el primer número de Fibonacci mayor que 1000?
((defndefn fibofibo [][]
((mapmap first (first (iterateiterate ((fnfn [[a b]] [b (+ a b)]) [0 1])))[[a b]] [b (+ a b)]) [0 1])))
((firstfirst (index-filter (fibo) #(> % 1000)))(index-filter (fibo) #(> % 1000)))
;; => 17;; => 17
((nthnth (fibo) 17)(fibo) 17)
;; => 1597;; => 1597
¿Qué versión es más general?¿Qué versión es más general?
Imperativa Funcional
Busca dentro de Strings Busca en Secuencias
Busca sólo caracteres
Busca usando cualquier
función predicado
Retorna el primer calce
Retorna una lista lazy de
todos los calces
Euler #4:Euler #4:
Mayor producto palíndromoMayor producto palíndromo
•• Número palíndromo: si es el mismo, escrito al revésNúmero palíndromo: si es el mismo, escrito al revés
(1.234.321)(1.234.321)
•• El mayor palíndromo que es producto de 2 númerosEl mayor palíndromo que es producto de 2 números
de 2 cifras esde 2 cifras es 90099009 = 91 x 99= 91 x 99
•• Encontrar el mayor producto de números de 3 cifrasEncontrar el mayor producto de números de 3 cifras
que sea palíndromoque sea palíndromo
// Palindromos.java// Palindromos.java
public classpublic class Palindromos {Palindromos {
public staticpublic static booleanboolean isPalinisPalin(Integer(Integer nn) {) {
StringString nsns = n.toString();= n.toString();
StringString reversereverse = new StringBuffer(ns).reverse().toString();= new StringBuffer(ns).reverse().toString();
returnreturn nstring.equals(reverse);nstring.equals(reverse);
}}
public staticpublic static void main(String[]void main(String[] argsargs) {) {
IntegerInteger maxmax = 0;= 0;
forfor (int(int ii = 100; i <= 999; i++) {= 100; i <= 999; i++) {
forfor (int(int jj = 100; j <= 999; j++) {= 100; j <= 999; j++) {
IntegerInteger prodprod = i * j;= i * j;
ifif (isPalin(prod) && prod > max) {(isPalin(prod) && prod > max) {
max = prod;max = prod;
}}
}}
}}
System.out.println(max);System.out.println(max);
}}
}}
# euler-004.py# euler-004.py
defdef palin(x):palin(x):
returnreturn strstr(x) ==(x) == strstr(x)[::-1](x)[::-1]
palinspalins = [x*y= [x*y forfor xx inin range(100, 1000) range(100, 1000) 
forfor yy inin range(x, 1000)range(x, 1000) ifif palin(x*y)]palin(x*y)]
print(max(palins))print(max(palins))
# euler-004.rb# euler-004.rb
puts (100..999).flat_map{|a| (a..999).flat_map {|b| a*b}}puts (100..999).flat_map{|a| (a..999).flat_map {|b| a*b}}
.select{|x| x.to_s == x.to_s.reverse}.select{|x| x.to_s == x.to_s.reverse}
.max.max
# euler-004.groovy# euler-004.groovy
defdef maxmax = (100..999).collect{x->(100..999).collect{y->x*y}}= (100..999).collect{x->(100..999).collect{y->x*y}}
.flatten().flatten()
.findAll{ it.toString() == it.toString().reverse() }.findAll{ it.toString() == it.toString().reverse() }
.max().max()
println maxprintln max
;; euler-004.clj;; euler-004.clj
((defndefn palin? [x]palin? [x]
(= ((= (strstr x) (x) (apply strapply str ((reversereverse ((strstr x)))))x)))))
((printlnprintln
((reducereduce maxmax
((forfor [x ([x (rangerange 100 1000)100 1000)
y (y (rangerange x 1000)x 1000)
:let:let [prod (* x y)][prod (* x y)]
:when:when (palin? prod)] prod))))(palin? prod)] prod))))
ConclusiónConclusión
•• Mayor nivel de abstracción:Mayor nivel de abstracción:
más énfasis en el→más énfasis en el→ quéqué y no en ely no en el cómocómo
→→ menos código que comprendermenos código que comprender
→→ a veces, código más genérico y re-utilizablea veces, código más genérico y re-utilizable
•• EnEn ClojureClojure se prefieren funciones puras*se prefieren funciones puras*
son más fáciles de entender→son más fáciles de entender→
→→ más fáciles de testear (no se necesitamás fáciles de testear (no se necesita mockingmocking))
→→ se pueden guardarse pueden guardar en cachéen caché (memoize f)(memoize f)
→→ se pueden paralelizarse pueden paralelizar fácilmentefácilmente (pmap f)(pmap f)
Beneficios de PFBeneficios de PF
FinFin
CréditosCréditos
Portada - “Lights of Ideas” por Saad Faruque
http://www.flickr.com/photos/cblue98/7254347346/sizes/l/
Fondo - “Gravel Background” por Ember Studio
http://www.flickr.com/photos/48013511@N07/7685947954/
Ejemplos en Clojure basados en “Functional Thinking” por Neal Ford
http://shop.oreilly.com/product/0636920030393.do

Contenu connexe

Tendances

Programacion en python_2
Programacion en python_2Programacion en python_2
Programacion en python_2wozgeass
 
Dart como alternativa a TypeScript (Codemotion 2016)
Dart como alternativa a TypeScript (Codemotion 2016)Dart como alternativa a TypeScript (Codemotion 2016)
Dart como alternativa a TypeScript (Codemotion 2016)Rafael Bermúdez Míguez
 
Python científico (introducción a numpy y matplotlib))
Python científico (introducción a numpy y matplotlib))Python científico (introducción a numpy y matplotlib))
Python científico (introducción a numpy y matplotlib))kikocorreoso
 
Programacion en python_1
Programacion en python_1Programacion en python_1
Programacion en python_1wozgeass
 
Descubriendo scala
Descubriendo scalaDescubriendo scala
Descubriendo scalanluaces
 
Javascript funcional
Javascript funcionalJavascript funcional
Javascript funcionalLeonardo Soto
 
Charla congreso web introducción programación funcional en JavaScript
Charla congreso web introducción programación funcional en JavaScriptCharla congreso web introducción programación funcional en JavaScript
Charla congreso web introducción programación funcional en JavaScriptRicardo Pallás Román
 
Ejercicios en Netbeans
Ejercicios en NetbeansEjercicios en Netbeans
Ejercicios en Netbeansedgar muñoz
 
Fourier
FourierFourier
FourierDC FCP
 
Red generativa antagonica
Red generativa antagonicaRed generativa antagonica
Red generativa antagonicaMichel Jraiche
 
Codemotion 2016 - d3.js un taller divertido y difícil
Codemotion 2016 - d3.js un taller divertido y difícilCodemotion 2016 - d3.js un taller divertido y difícil
Codemotion 2016 - d3.js un taller divertido y difícilJavier Abadía
 
Ejercicios resueltos practica 2 (nueva 2014) informática ii
Ejercicios resueltos practica 2 (nueva 2014) informática iiEjercicios resueltos practica 2 (nueva 2014) informática ii
Ejercicios resueltos practica 2 (nueva 2014) informática iiAlvin Jacobs
 
ORM Doctrine
ORM DoctrineORM Doctrine
ORM DoctrineDecharlas
 
Lo que las empresas piden
Lo que las empresas pidenLo que las empresas piden
Lo que las empresas pidenSvet Ivantchev
 

Tendances (20)

Programacion en python_2
Programacion en python_2Programacion en python_2
Programacion en python_2
 
Dart como alternativa a TypeScript (Codemotion 2016)
Dart como alternativa a TypeScript (Codemotion 2016)Dart como alternativa a TypeScript (Codemotion 2016)
Dart como alternativa a TypeScript (Codemotion 2016)
 
Python científico (introducción a numpy y matplotlib))
Python científico (introducción a numpy y matplotlib))Python científico (introducción a numpy y matplotlib))
Python científico (introducción a numpy y matplotlib))
 
Programacion en python_1
Programacion en python_1Programacion en python_1
Programacion en python_1
 
Descubriendo scala
Descubriendo scalaDescubriendo scala
Descubriendo scala
 
Javascript funcional
Javascript funcionalJavascript funcional
Javascript funcional
 
Tipos basicos
Tipos basicosTipos basicos
Tipos basicos
 
Lecture 37
Lecture 37Lecture 37
Lecture 37
 
Practica 5
Practica  5Practica  5
Practica 5
 
Charla congreso web introducción programación funcional en JavaScript
Charla congreso web introducción programación funcional en JavaScriptCharla congreso web introducción programación funcional en JavaScript
Charla congreso web introducción programación funcional en JavaScript
 
Ejercicios en Netbeans
Ejercicios en NetbeansEjercicios en Netbeans
Ejercicios en Netbeans
 
Practica
PracticaPractica
Practica
 
Fourier
FourierFourier
Fourier
 
Red generativa antagonica
Red generativa antagonicaRed generativa antagonica
Red generativa antagonica
 
7
77
7
 
Transparencias3
Transparencias3Transparencias3
Transparencias3
 
Codemotion 2016 - d3.js un taller divertido y difícil
Codemotion 2016 - d3.js un taller divertido y difícilCodemotion 2016 - d3.js un taller divertido y difícil
Codemotion 2016 - d3.js un taller divertido y difícil
 
Ejercicios resueltos practica 2 (nueva 2014) informática ii
Ejercicios resueltos practica 2 (nueva 2014) informática iiEjercicios resueltos practica 2 (nueva 2014) informática ii
Ejercicios resueltos practica 2 (nueva 2014) informática ii
 
ORM Doctrine
ORM DoctrineORM Doctrine
ORM Doctrine
 
Lo que las empresas piden
Lo que las empresas pidenLo que las empresas piden
Lo que las empresas piden
 

En vedette

Instituto tecnológico de matehuala
Instituto  tecnológico  de  matehualaInstituto  tecnológico  de  matehuala
Instituto tecnológico de matehualaEsperanza Alvarez
 
Introduccion al desarrollo con Launchpad
Introduccion al desarrollo con LaunchpadIntroduccion al desarrollo con Launchpad
Introduccion al desarrollo con LaunchpadDenis Fuenzalida
 
Ensayo sobre la creatividad!!!!
Ensayo sobre la creatividad!!!!Ensayo sobre la creatividad!!!!
Ensayo sobre la creatividad!!!!MelidSa BecErra
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionIn a Rocket
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanPost Planner
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldabaux singapore
 

En vedette (8)

Introducción a Clojure
Introducción a ClojureIntroducción a Clojure
Introducción a Clojure
 
Instituto tecnológico de matehuala
Instituto  tecnológico  de  matehualaInstituto  tecnológico  de  matehuala
Instituto tecnológico de matehuala
 
Introduccion al desarrollo con Launchpad
Introduccion al desarrollo con LaunchpadIntroduccion al desarrollo con Launchpad
Introduccion al desarrollo con Launchpad
 
Ensayo sobre la creatividad!!!!
Ensayo sobre la creatividad!!!!Ensayo sobre la creatividad!!!!
Ensayo sobre la creatividad!!!!
 
Primer Programa Java en Bluej
Primer Programa Java en BluejPrimer Programa Java en Bluej
Primer Programa Java en Bluej
 
Learn BEM: CSS Naming Convention
Learn BEM: CSS Naming ConventionLearn BEM: CSS Naming Convention
Learn BEM: CSS Naming Convention
 
How to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media PlanHow to Build a Dynamic Social Media Plan
How to Build a Dynamic Social Media Plan
 
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika AldabaLightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
Lightning Talk #9: How UX and Data Storytelling Can Shape Policy by Mika Aldaba
 

Similaire à Mayor producto palíndromo de 3 cifras

Introducción a Scala
Introducción a ScalaIntroducción a Scala
Introducción a Scaladhaat
 
Chuleta de lenguaje C para principiantes
Chuleta de lenguaje C para principiantesChuleta de lenguaje C para principiantes
Chuleta de lenguaje C para principiantesAbrirllave
 
Sesion1_Ciencia_de_Datos-Introduccion a Pithon.pdf
Sesion1_Ciencia_de_Datos-Introduccion a Pithon.pdfSesion1_Ciencia_de_Datos-Introduccion a Pithon.pdf
Sesion1_Ciencia_de_Datos-Introduccion a Pithon.pdfMarxx4
 
INTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptx
INTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptxINTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptx
INTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptxRodmanCevallos1
 
Informe minishell
Informe minishellInforme minishell
Informe minishellAlex Pin
 
Introducción a Swift
Introducción a SwiftIntroducción a Swift
Introducción a Swiftbetabeers
 
UNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARSUNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARSCamiEscobar1995
 
UNIVERSIDAD CENTRAL DEL ECUADOR GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR GETCHARSUNIVERSIDAD CENTRAL DEL ECUADOR GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR GETCHARSCamiEscobar1995
 
Instrucciones(raptor, java, c#)
Instrucciones(raptor, java, c#)Instrucciones(raptor, java, c#)
Instrucciones(raptor, java, c#)Markoos Riveroo
 
El lenguaje de programacion c++ prev
El lenguaje de programacion c++ prevEl lenguaje de programacion c++ prev
El lenguaje de programacion c++ prevjtk1
 
Sistemas de tipos: Lo bueno, lo malo y lo feo
Sistemas de tipos: Lo bueno, lo malo y lo feoSistemas de tipos: Lo bueno, lo malo y lo feo
Sistemas de tipos: Lo bueno, lo malo y lo feoEnrique Zamudio López
 

Similaire à Mayor producto palíndromo de 3 cifras (20)

Los lenguajes de la web
Los lenguajes de la webLos lenguajes de la web
Los lenguajes de la web
 
Introducción a Scala
Introducción a ScalaIntroducción a Scala
Introducción a Scala
 
Chuleta de lenguaje C para principiantes
Chuleta de lenguaje C para principiantesChuleta de lenguaje C para principiantes
Chuleta de lenguaje C para principiantes
 
Python workshop
Python workshopPython workshop
Python workshop
 
Sesion1_Ciencia_de_Datos-Introduccion a Pithon.pdf
Sesion1_Ciencia_de_Datos-Introduccion a Pithon.pdfSesion1_Ciencia_de_Datos-Introduccion a Pithon.pdf
Sesion1_Ciencia_de_Datos-Introduccion a Pithon.pdf
 
Introducción a Scala
Introducción a ScalaIntroducción a Scala
Introducción a Scala
 
INTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptx
INTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptxINTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptx
INTRODUCCIÓN A LA PROGRAMACIÓN - PYTHON.pptx
 
Informe minishell
Informe minishellInforme minishell
Informe minishell
 
Java 8
Java 8Java 8
Java 8
 
Introducción a Swift
Introducción a SwiftIntroducción a Swift
Introducción a Swift
 
Getchars
GetcharsGetchars
Getchars
 
UNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARSUNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR CAMILA ESCOBAR LOPEZ GETCHARS
 
UNIVERSIDAD CENTRAL DEL ECUADOR GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR GETCHARSUNIVERSIDAD CENTRAL DEL ECUADOR GETCHARS
UNIVERSIDAD CENTRAL DEL ECUADOR GETCHARS
 
Getchars
GetcharsGetchars
Getchars
 
Instrucciones(raptor, java, c#)
Instrucciones(raptor, java, c#)Instrucciones(raptor, java, c#)
Instrucciones(raptor, java, c#)
 
Python_Slides.pptx
Python_Slides.pptxPython_Slides.pptx
Python_Slides.pptx
 
Clase 7 objetos globales de javaScript
Clase 7 objetos globales de javaScriptClase 7 objetos globales de javaScript
Clase 7 objetos globales de javaScript
 
El lenguaje de programacion c++ prev
El lenguaje de programacion c++ prevEl lenguaje de programacion c++ prev
El lenguaje de programacion c++ prev
 
Universidad técnica de ambato
Universidad técnica de ambatoUniversidad técnica de ambato
Universidad técnica de ambato
 
Sistemas de tipos: Lo bueno, lo malo y lo feo
Sistemas de tipos: Lo bueno, lo malo y lo feoSistemas de tipos: Lo bueno, lo malo y lo feo
Sistemas de tipos: Lo bueno, lo malo y lo feo
 

Dernier

Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricKeyla Dolores Méndez
 
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE  DE TECNOLOGIA E INFORMATICA PRIMARIACLASE  DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIAWilbisVega
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveFagnerLisboa3
 
Herramientas de corte de alta velocidad.pptx
Herramientas de corte de alta velocidad.pptxHerramientas de corte de alta velocidad.pptx
Herramientas de corte de alta velocidad.pptxRogerPrieto3
 
KELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento ProtégelesKELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento ProtégelesFundación YOD YOD
 
Presentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxPresentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxLolaBunny11
 
International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)GDGSucre
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITMaricarmen Sánchez Ruiz
 
trabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdftrabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdfIsabellaMontaomurill
 
9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudiante9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudianteAndreaHuertas24
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan JosephBRAYANJOSEPHPEREZGOM
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíassuserf18419
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx241521559
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...silviayucra2
 
Redes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdfRedes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdfsoporteupcology
 

Dernier (15)

Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft FabricGlobal Azure Lima 2024 - Integración de Datos con Microsoft Fabric
Global Azure Lima 2024 - Integración de Datos con Microsoft Fabric
 
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE  DE TECNOLOGIA E INFORMATICA PRIMARIACLASE  DE TECNOLOGIA E INFORMATICA PRIMARIA
CLASE DE TECNOLOGIA E INFORMATICA PRIMARIA
 
EPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial UninoveEPA-pdf resultado da prova presencial Uninove
EPA-pdf resultado da prova presencial Uninove
 
Herramientas de corte de alta velocidad.pptx
Herramientas de corte de alta velocidad.pptxHerramientas de corte de alta velocidad.pptx
Herramientas de corte de alta velocidad.pptx
 
KELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento ProtégelesKELA Presentacion Costa Rica 2024 - evento Protégeles
KELA Presentacion Costa Rica 2024 - evento Protégeles
 
Presentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptxPresentación guía sencilla en Microsoft Excel.pptx
Presentación guía sencilla en Microsoft Excel.pptx
 
International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)International Women's Day Sucre 2024 (IWD)
International Women's Day Sucre 2024 (IWD)
 
pruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNITpruebas unitarias unitarias en java con JUNIT
pruebas unitarias unitarias en java con JUNIT
 
trabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdftrabajotecologiaisabella-240424003133-8f126965.pdf
trabajotecologiaisabella-240424003133-8f126965.pdf
 
9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudiante9egb-lengua y Literatura.pdf_texto del estudiante
9egb-lengua y Literatura.pdf_texto del estudiante
 
guía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Josephguía de registro de slideshare por Brayan Joseph
guía de registro de slideshare por Brayan Joseph
 
Trabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnologíaTrabajo Mas Completo De Excel en clase tecnología
Trabajo Mas Completo De Excel en clase tecnología
 
Proyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptxProyecto integrador. Las TIC en la sociedad S4.pptx
Proyecto integrador. Las TIC en la sociedad S4.pptx
 
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
POWER POINT YUCRAElabore una PRESENTACIÓN CORTA sobre el video película: La C...
 
Redes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdfRedes direccionamiento y subredes ipv4 2024 .pdf
Redes direccionamiento y subredes ipv4 2024 .pdf
 

Mayor producto palíndromo de 3 cifras

  • 1. Pensando FuncionalmentePensando Funcionalmente Denis Fuenzalida – Agosto de 2013Denis Fuenzalida – Agosto de 2013 denis.fuenzalida@gmail.comdenis.fuenzalida@gmail.com
  • 3. •• Problema: no hay definiciónProblema: no hay definición universalmenteuniversalmente aceptadaaceptada •• Funciones como elementos de primer nivel del lenguaje:Funciones como elementos de primer nivel del lenguaje: ““First Class FunctionsFirst Class Functions”” →→ es posible almacenares posible almacenar referenciasreferencias a funcionesa funciones pasar funciones como→pasar funciones como→ parámetrosparámetros →→ crear funciones que retornancrear funciones que retornan funcionesfunciones DefiniciónDefinición
  • 4. •• Mayor nivel de abstracción:Mayor nivel de abstracción: más énfasis en el→más énfasis en el→ quéqué y no en ely no en el cómocómo →→ menos código que comprendermenos código que comprender →→ a veces, código más genérico y re-utilizablea veces, código más genérico y re-utilizable •• EnEn ClojureClojure se prefieren funciones puras*se prefieren funciones puras* son más fáciles de entender→son más fáciles de entender→ →→ más fáciles de testearmás fáciles de testear →→ se pueden guardarse pueden guardar en cachéen caché y paralelizary paralelizar fácilmentefácilmente BeneficiosBeneficios
  • 5. Convertir de códigoConvertir de código imperativo a funcionalimperativo a funcional
  • 6. // Basado en StringUtils.java de Apache Commons Lang// Basado en StringUtils.java de Apache Commons Lang /*/* * Spec:* Spec: ** * StringUtils.indexOfAny(null, *) = -1* StringUtils.indexOfAny(null, *) = -1 * StringUtils.indexOfAny("", *) = -1* StringUtils.indexOfAny("", *) = -1 * StringUtils.indexOfAny(*, null) = -1* StringUtils.indexOfAny(*, null) = -1 * StringUtils.indexOfAny(*, []) = -1* StringUtils.indexOfAny(*, []) = -1 * StringUtils.indexOfAny("* StringUtils.indexOfAny("zzzabyycdxx",['z','a']) = 0zabyycdxx",['z','a']) = 0 * StringUtils.indexOfAny("zza* StringUtils.indexOfAny("zzabbyycdxx",['b','y']) = 3yycdxx",['b','y']) = 3 * StringUtils.indexOfAny("aba", ['z']) = -1* StringUtils.indexOfAny("aba", ['z']) = -1 */*/
  • 7. // Basado en StringUtils.java de Apache Commons Lang// Basado en StringUtils.java de Apache Commons Lang classclass StringUtils {StringUtils { public staticpublic static intint indexOfAnyindexOfAny(String(String strstr, char[], char[] toSearchtoSearch){){ ifif (isEmpty(str) || ArrayUtils.isEmpty(toSearch)){(isEmpty(str) || ArrayUtils.isEmpty(toSearch)){ returnreturn -1;-1; }} forfor (int i = 0; i < str.length(); i++){(int i = 0; i < str.length(); i++){ charchar chch = str.charAt(i);= str.charAt(i); forfor (int(int jj = 0; j < toSearch.length; j++){= 0; j < toSearch.length; j++){ ifif (searchChars[j] == ch){(searchChars[j] == ch){ returnreturn i;i; }} }} }} returnreturn -1;-1; }} }}
  • 8. // Simplificando condiciones de borde...// Simplificando condiciones de borde... classclass StringUtils {StringUtils { public staticpublic static intint indexOfAnyindexOfAny(String(String strstr, char[], char[] toSearchtoSearch){){ when (toSearch) {when (toSearch) { forfor (int i = 0; i < str.length(); i++){(int i = 0; i < str.length(); i++){ charchar chch = str.charAt(i);= str.charAt(i); forfor (int(int jj = 0; j < toSearch.length; j++){= 0; j < toSearch.length; j++){ ifif (searchChars[j] == ch){(searchChars[j] == ch){ returnreturn i;i; }} }} }} }} }} }}
  • 9. // En un lenguaje dinámico* podemos quitar tipos/clases:// En un lenguaje dinámico* podemos quitar tipos/clases: indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){ when (toSearch) {when (toSearch) { forfor (i = 0; i < str.length(); i++){(i = 0; i < str.length(); i++){ chch = str.charAt(i);= str.charAt(i); forfor ((jj = 0; j < toSearch.length; j++){= 0; j < toSearch.length; j++){ ifif (searchChars[j] == ch){(searchChars[j] == ch){ returnreturn i;i; }} }} }} }} }}
  • 10. // pseudo-codigo// pseudo-codigo indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){ when (toSearch) {when (toSearch) { forfor (i = 0; i < str.length(); i++){(i = 0; i < str.length(); i++){ chch = str.charAt(i);= str.charAt(i); when toSearch(ch) i; // Busca 'ch', retorna iwhen toSearch(ch) i; // Busca 'ch', retorna i }} }} }}
  • 11. // Usando una list-comprehension para iterar// Usando una list-comprehension para iterar indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){ when (toSearch) {when (toSearch) { forfor ([i, ch] in indexed(str)){([i, ch] in indexed(str)){ when toSearch(ch) i;when toSearch(ch) i; }} }} }}
  • 12. // pseudo-codigo// pseudo-codigo indexOfAnyindexOfAny((strstr,, toSearchtoSearch){){ when (toSearch) {when (toSearch) { forfor ([i, ch] in indexed(str)){([i, ch] in indexed(str)){ when toSearch(ch) i;when toSearch(ch) i; }} }} }} ;; Version Clojure;; Version Clojure ((defndefn index-filterindex-filter [coll pred][coll pred] ((whenwhen predpred ((forfor [[idx elt] (indexed coll)[[idx elt] (indexed coll) :when:when (pred elt)] idx)))(pred elt)] idx)))
  • 13. Imperativa Funcional Funciones 1 1 Clases 1 0 Puntos internos de retorno 2 0 Variables 3 0 Ramificaciones 4 0 Operaciones booleanas 1 0 Llamadas a funciones 6 3 Total 18 4 Complejidad de cada versiónComplejidad de cada versión
  • 14. ;; Es correcta esta implementación?;; Es correcta esta implementación? ((defndefn indexedindexed [s] ([s] (mapmap vector (vector (iterateiterate inc 0) s))inc 0) s)) ((defndefn index-filterindex-filter [coll pred][coll pred] ((whenwhen predpred ((forfor [[idx elt] (indexed coll)[[idx elt] (indexed coll) :when:when (pred elt)] idx)))(pred elt)] idx))) ;; StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0;; StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0 ;; StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3;; StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3 (index-filter "zzabyycdxx" #{z a})(index-filter "zzabyycdxx" #{z a}) ;; => (;; => (00 1 2)1 2) (index-filter "zzabyycdxx" #{b y})(index-filter "zzabyycdxx" #{b y}) ;; => (;; => (33 4 5)4 5)
  • 15. ;; index-filter retorna una lista* de TODOS los calces!;; index-filter retorna una lista* de TODOS los calces! ;; Indices de 'cara' en una lista de tiradas de moneda:;; Indices de 'cara' en una lista de tiradas de moneda: (index-filter [(index-filter [:c :s :c :c :s :s :c :s :c :s :c:c :s :c :c :s :s :c :s :c :s :c] #{] #{:c:c})}) ;; => (0 2 3 6 8 10);; => (0 2 3 6 8 10) ;; Cuál es el primer número de Fibonacci mayor que 1000?;; Cuál es el primer número de Fibonacci mayor que 1000? ((defndefn fibofibo [][] ((mapmap first (first (iterateiterate ((fnfn [[a b]] [b (+ a b)]) [0 1])))[[a b]] [b (+ a b)]) [0 1]))) ((firstfirst (index-filter (fibo) #(> % 1000)))(index-filter (fibo) #(> % 1000))) ;; => 17;; => 17 ((nthnth (fibo) 17)(fibo) 17) ;; => 1597;; => 1597
  • 16. ¿Qué versión es más general?¿Qué versión es más general? Imperativa Funcional Busca dentro de Strings Busca en Secuencias Busca sólo caracteres Busca usando cualquier función predicado Retorna el primer calce Retorna una lista lazy de todos los calces
  • 17. Euler #4:Euler #4: Mayor producto palíndromoMayor producto palíndromo •• Número palíndromo: si es el mismo, escrito al revésNúmero palíndromo: si es el mismo, escrito al revés (1.234.321)(1.234.321) •• El mayor palíndromo que es producto de 2 númerosEl mayor palíndromo que es producto de 2 números de 2 cifras esde 2 cifras es 90099009 = 91 x 99= 91 x 99 •• Encontrar el mayor producto de números de 3 cifrasEncontrar el mayor producto de números de 3 cifras que sea palíndromoque sea palíndromo
  • 18. // Palindromos.java// Palindromos.java public classpublic class Palindromos {Palindromos { public staticpublic static booleanboolean isPalinisPalin(Integer(Integer nn) {) { StringString nsns = n.toString();= n.toString(); StringString reversereverse = new StringBuffer(ns).reverse().toString();= new StringBuffer(ns).reverse().toString(); returnreturn nstring.equals(reverse);nstring.equals(reverse); }} public staticpublic static void main(String[]void main(String[] argsargs) {) { IntegerInteger maxmax = 0;= 0; forfor (int(int ii = 100; i <= 999; i++) {= 100; i <= 999; i++) { forfor (int(int jj = 100; j <= 999; j++) {= 100; j <= 999; j++) { IntegerInteger prodprod = i * j;= i * j; ifif (isPalin(prod) && prod > max) {(isPalin(prod) && prod > max) { max = prod;max = prod; }} }} }} System.out.println(max);System.out.println(max); }} }}
  • 19. # euler-004.py# euler-004.py defdef palin(x):palin(x): returnreturn strstr(x) ==(x) == strstr(x)[::-1](x)[::-1] palinspalins = [x*y= [x*y forfor xx inin range(100, 1000) range(100, 1000) forfor yy inin range(x, 1000)range(x, 1000) ifif palin(x*y)]palin(x*y)] print(max(palins))print(max(palins))
  • 20. # euler-004.rb# euler-004.rb puts (100..999).flat_map{|a| (a..999).flat_map {|b| a*b}}puts (100..999).flat_map{|a| (a..999).flat_map {|b| a*b}} .select{|x| x.to_s == x.to_s.reverse}.select{|x| x.to_s == x.to_s.reverse} .max.max # euler-004.groovy# euler-004.groovy defdef maxmax = (100..999).collect{x->(100..999).collect{y->x*y}}= (100..999).collect{x->(100..999).collect{y->x*y}} .flatten().flatten() .findAll{ it.toString() == it.toString().reverse() }.findAll{ it.toString() == it.toString().reverse() } .max().max() println maxprintln max
  • 21. ;; euler-004.clj;; euler-004.clj ((defndefn palin? [x]palin? [x] (= ((= (strstr x) (x) (apply strapply str ((reversereverse ((strstr x)))))x))))) ((printlnprintln ((reducereduce maxmax ((forfor [x ([x (rangerange 100 1000)100 1000) y (y (rangerange x 1000)x 1000) :let:let [prod (* x y)][prod (* x y)] :when:when (palin? prod)] prod))))(palin? prod)] prod))))
  • 23. •• Mayor nivel de abstracción:Mayor nivel de abstracción: más énfasis en el→más énfasis en el→ quéqué y no en ely no en el cómocómo →→ menos código que comprendermenos código que comprender →→ a veces, código más genérico y re-utilizablea veces, código más genérico y re-utilizable •• EnEn ClojureClojure se prefieren funciones puras*se prefieren funciones puras* son más fáciles de entender→son más fáciles de entender→ →→ más fáciles de testear (no se necesitamás fáciles de testear (no se necesita mockingmocking)) →→ se pueden guardarse pueden guardar en cachéen caché (memoize f)(memoize f) →→ se pueden paralelizarse pueden paralelizar fácilmentefácilmente (pmap f)(pmap f) Beneficios de PFBeneficios de PF
  • 25. CréditosCréditos Portada - “Lights of Ideas” por Saad Faruque http://www.flickr.com/photos/cblue98/7254347346/sizes/l/ Fondo - “Gravel Background” por Ember Studio http://www.flickr.com/photos/48013511@N07/7685947954/ Ejemplos en Clojure basados en “Functional Thinking” por Neal Ford http://shop.oreilly.com/product/0636920030393.do