SlideShare a Scribd company logo
Programación
Funcional en Haskell
2a parte
Agustín Ramos Fonseca
Un lenguaje de programación...


• Funcional.

Las funciones son construcciones de primera clase.


• Puro.

Las funciones no tienen efectos colaterales.


• De evaluación perezosa.

Las expresiones se evalúan hasta que es requerido.


• De tipado estático.

Con inferencia de tipos.
Características
•
•
•
•
•
•
•
•
•

List comprehensions.

Pattern matching.

Currying

Function Composition

Infinite data structures.

Agebraic Data Types

Type classes.

Applicative Functors

Monads
Ejemplos
¿Haskell Sweet Spot?
Algoritmos
Eight Queens
Eight Queens
!
isValidSolution sol

= all isValid fullPositions


where fullPositions = zip sol [1..8]

isValid pos

= null $ intersect fullPositions $ diags pos


diags pos

= diag1 pos ++ diag2 pos ++ diag3 pos ++ diag4 pos


diag1 (r,c)

= [(r',c') | r' <- [r-1,r-2..1], r' >= 1, c' <- [c-1,c-2..1], c' >= 1, r'-c' == r-c ]


diag2 (r,c)

= [(r',c') | r' <- [r+1..8],

r' <= 8, c' <- [c+1..8],

diag3 (r,c)

= [(r',c') | r' <- [r+1..8],

r' <= 8, c' <- [c-1,c-2..1], c' >= 1, r'+c' == r+c ]


diag4 (r,c)

= [(r',c') | r' <- [r-1,r-2..1], r' >= 1, c' <- [c+1..8],

!
eightQueens = filter isValidSolution $ permutations [1..8]


c' <= 8, r'-c' == r-c ]


c' <= 8, r'+c' == r+c ]
Knights Tour
Knights Tour
type Position = (Int,Int)

type Solution = [Position]

!

possibleMovs :: Int -> Position -> [Position]

possibleMovs n (r,c) = [(r',c') | r' <- [r-2..r+2], 

c' <- [c-2..c+2], 

isLMovement (r’,c'), 

isWithinBoard (r',c')]

where isLMovement (r',c')

= abs(r-r') + abs(c-c') == 3


isWithinBoard (r',c') = r' >= 1 && r' <= n && c' >= 1 && c' <= n
Knights Tour
tours :: Int -> Position -> [Solution] 

tours n from

= tours' n from [[from]]


where tours' n from sols

= filter fullTour $ concat $ solutions n from sols


solutions n from sols = parMap rpar (completeSols sols) $ possibleMovs n from 

completeSols sols m

= if isNewPosition m sols

then tours' n m $ appendToSolutions sols m

else sols


fullTour s

= length s == n*n

isNewPosition p
appendToSolutions []




= all (isNothing . elemIndex p) 

mov = [[mov]]


appendToSolutions sols mov = map (sol -> sol ++ [mov] ) sols


!
knightsTour n

= concat $ parMap rpar (tours n) allPositions


where allPositions = [(r,c) | r <- [1..n], c <- [1..n]]
Lattice Paths

http://projecteuler.net/problem=15
Lattice Paths
import Control.Monad.Memo


!
pathsm 0 0 = return 0

pathsm 0 _ = return 1

pathsm _ 0 = return 1

pathsm r d = do

r1 <- for2 memo pathsm (r - 1) d

d1 <- for2 memo pathsm r (d -1)

return (r1 + d1)


!
evalPathsm :: (Num n, Ord n) => n -> n -> n

evalPathsm r d = startEvalMemo $ pathsm r d


!
runPathsm n = evalPathsm n n
Proyectos Interesantes
HAXL

http:/
/j.mp/1bWl9Oz
Elm

http:/
/elm-lang.org/
Porque...

#SoyPunk
¿Preguntas?
¡Gracias!

Agustín Ramos Fonseca

@MachinesAreUs

More Related Content

Similar to Programación funcional con Haskell

Tork03 LT
Tork03 LT Tork03 LT
Tork03 LT
Masaya TARUI
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
Lukasz Dynowski
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
Paul Phillips
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
Koen Handekyn
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
Chia-Chi Chang
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
aztack
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
Eleanor McHugh
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
Nguyen Tuan
 
Analysis of algorithms
Analysis of algorithms Analysis of algorithms
Analysis of algorithms
MUSAIDRIS15
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
Philip Schwarz
 
Rtutorial
RtutorialRtutorial
Rtutorial
Dheeraj Dwivedi
 
Retos de Programación en Python
Retos de Programación en PythonRetos de Programación en Python
Retos de Programación en Python
Javier Abadía
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
Stephan Janssen
 
Fp
FpFp
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
Ashin Guha Majumder
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
Chen Fisher
 

Similar to Programación funcional con Haskell (20)

Tork03 LT
Tork03 LT Tork03 LT
Tork03 LT
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
Monadologie
MonadologieMonadologie
Monadologie
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Scala training workshop 02
Scala training workshop 02Scala training workshop 02
Scala training workshop 02
 
Analysis of algorithms
Analysis of algorithms Analysis of algorithms
Analysis of algorithms
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Rtutorial
RtutorialRtutorial
Rtutorial
 
Retos de Programación en Python
Retos de Programación en PythonRetos de Programación en Python
Retos de Programación en Python
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Scala by Luc Duponcheel
Scala by Luc DuponcheelScala by Luc Duponcheel
Scala by Luc Duponcheel
 
Fp
FpFp
Fp
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 

More from Software Guru

Hola Mundo del Internet de las Cosas
Hola Mundo del Internet de las CosasHola Mundo del Internet de las Cosas
Hola Mundo del Internet de las Cosas
Software Guru
 
Estructuras de datos avanzadas: Casos de uso reales
Estructuras de datos avanzadas: Casos de uso realesEstructuras de datos avanzadas: Casos de uso reales
Estructuras de datos avanzadas: Casos de uso reales
Software Guru
 
Building bias-aware environments
Building bias-aware environmentsBuilding bias-aware environments
Building bias-aware environments
Software Guru
 
El secreto para ser un desarrollador Senior
El secreto para ser un desarrollador SeniorEl secreto para ser un desarrollador Senior
El secreto para ser un desarrollador Senior
Software Guru
 
Cómo encontrar el trabajo remoto ideal
Cómo encontrar el trabajo remoto idealCómo encontrar el trabajo remoto ideal
Cómo encontrar el trabajo remoto ideal
Software Guru
 
Automatizando ideas con Apache Airflow
Automatizando ideas con Apache AirflowAutomatizando ideas con Apache Airflow
Automatizando ideas con Apache Airflow
Software Guru
 
How thick data can improve big data analysis for business:
How thick data can improve big data analysis for business:How thick data can improve big data analysis for business:
How thick data can improve big data analysis for business:
Software Guru
 
Introducción al machine learning
Introducción al machine learningIntroducción al machine learning
Introducción al machine learning
Software Guru
 
Democratizando el uso de CoDi
Democratizando el uso de CoDiDemocratizando el uso de CoDi
Democratizando el uso de CoDi
Software Guru
 
Gestionando la felicidad de los equipos con Management 3.0
Gestionando la felicidad de los equipos con Management 3.0Gestionando la felicidad de los equipos con Management 3.0
Gestionando la felicidad de los equipos con Management 3.0
Software Guru
 
Taller: Creación de Componentes Web re-usables con StencilJS
Taller: Creación de Componentes Web re-usables con StencilJSTaller: Creación de Componentes Web re-usables con StencilJS
Taller: Creación de Componentes Web re-usables con StencilJS
Software Guru
 
El camino del full stack developer (o como hacemos en SERTI para que no solo ...
El camino del full stack developer (o como hacemos en SERTI para que no solo ...El camino del full stack developer (o como hacemos en SERTI para que no solo ...
El camino del full stack developer (o como hacemos en SERTI para que no solo ...
Software Guru
 
¿Qué significa ser un programador en Bitso?
¿Qué significa ser un programador en Bitso?¿Qué significa ser un programador en Bitso?
¿Qué significa ser un programador en Bitso?
Software Guru
 
Colaboración efectiva entre desarrolladores del cliente y tu equipo.
Colaboración efectiva entre desarrolladores del cliente y tu equipo.Colaboración efectiva entre desarrolladores del cliente y tu equipo.
Colaboración efectiva entre desarrolladores del cliente y tu equipo.
Software Guru
 
Pruebas de integración con Docker en Azure DevOps
Pruebas de integración con Docker en Azure DevOpsPruebas de integración con Docker en Azure DevOps
Pruebas de integración con Docker en Azure DevOps
Software Guru
 
Elixir + Elm: Usando lenguajes funcionales en servicios productivos
Elixir + Elm: Usando lenguajes funcionales en servicios productivosElixir + Elm: Usando lenguajes funcionales en servicios productivos
Elixir + Elm: Usando lenguajes funcionales en servicios productivos
Software Guru
 
Así publicamos las apps de Spotify sin stress
Así publicamos las apps de Spotify sin stressAsí publicamos las apps de Spotify sin stress
Así publicamos las apps de Spotify sin stress
Software Guru
 
Achieving Your Goals: 5 Tips to successfully achieve your goals
Achieving Your Goals: 5 Tips to successfully achieve your goalsAchieving Your Goals: 5 Tips to successfully achieve your goals
Achieving Your Goals: 5 Tips to successfully achieve your goals
Software Guru
 
Acciones de comunidades tech en tiempos del Covid19
Acciones de comunidades tech en tiempos del Covid19Acciones de comunidades tech en tiempos del Covid19
Acciones de comunidades tech en tiempos del Covid19
Software Guru
 
De lo operativo a lo estratégico: un modelo de management de diseño
De lo operativo a lo estratégico: un modelo de management de diseñoDe lo operativo a lo estratégico: un modelo de management de diseño
De lo operativo a lo estratégico: un modelo de management de diseño
Software Guru
 

More from Software Guru (20)

Hola Mundo del Internet de las Cosas
Hola Mundo del Internet de las CosasHola Mundo del Internet de las Cosas
Hola Mundo del Internet de las Cosas
 
Estructuras de datos avanzadas: Casos de uso reales
Estructuras de datos avanzadas: Casos de uso realesEstructuras de datos avanzadas: Casos de uso reales
Estructuras de datos avanzadas: Casos de uso reales
 
Building bias-aware environments
Building bias-aware environmentsBuilding bias-aware environments
Building bias-aware environments
 
El secreto para ser un desarrollador Senior
El secreto para ser un desarrollador SeniorEl secreto para ser un desarrollador Senior
El secreto para ser un desarrollador Senior
 
Cómo encontrar el trabajo remoto ideal
Cómo encontrar el trabajo remoto idealCómo encontrar el trabajo remoto ideal
Cómo encontrar el trabajo remoto ideal
 
Automatizando ideas con Apache Airflow
Automatizando ideas con Apache AirflowAutomatizando ideas con Apache Airflow
Automatizando ideas con Apache Airflow
 
How thick data can improve big data analysis for business:
How thick data can improve big data analysis for business:How thick data can improve big data analysis for business:
How thick data can improve big data analysis for business:
 
Introducción al machine learning
Introducción al machine learningIntroducción al machine learning
Introducción al machine learning
 
Democratizando el uso de CoDi
Democratizando el uso de CoDiDemocratizando el uso de CoDi
Democratizando el uso de CoDi
 
Gestionando la felicidad de los equipos con Management 3.0
Gestionando la felicidad de los equipos con Management 3.0Gestionando la felicidad de los equipos con Management 3.0
Gestionando la felicidad de los equipos con Management 3.0
 
Taller: Creación de Componentes Web re-usables con StencilJS
Taller: Creación de Componentes Web re-usables con StencilJSTaller: Creación de Componentes Web re-usables con StencilJS
Taller: Creación de Componentes Web re-usables con StencilJS
 
El camino del full stack developer (o como hacemos en SERTI para que no solo ...
El camino del full stack developer (o como hacemos en SERTI para que no solo ...El camino del full stack developer (o como hacemos en SERTI para que no solo ...
El camino del full stack developer (o como hacemos en SERTI para que no solo ...
 
¿Qué significa ser un programador en Bitso?
¿Qué significa ser un programador en Bitso?¿Qué significa ser un programador en Bitso?
¿Qué significa ser un programador en Bitso?
 
Colaboración efectiva entre desarrolladores del cliente y tu equipo.
Colaboración efectiva entre desarrolladores del cliente y tu equipo.Colaboración efectiva entre desarrolladores del cliente y tu equipo.
Colaboración efectiva entre desarrolladores del cliente y tu equipo.
 
Pruebas de integración con Docker en Azure DevOps
Pruebas de integración con Docker en Azure DevOpsPruebas de integración con Docker en Azure DevOps
Pruebas de integración con Docker en Azure DevOps
 
Elixir + Elm: Usando lenguajes funcionales en servicios productivos
Elixir + Elm: Usando lenguajes funcionales en servicios productivosElixir + Elm: Usando lenguajes funcionales en servicios productivos
Elixir + Elm: Usando lenguajes funcionales en servicios productivos
 
Así publicamos las apps de Spotify sin stress
Así publicamos las apps de Spotify sin stressAsí publicamos las apps de Spotify sin stress
Así publicamos las apps de Spotify sin stress
 
Achieving Your Goals: 5 Tips to successfully achieve your goals
Achieving Your Goals: 5 Tips to successfully achieve your goalsAchieving Your Goals: 5 Tips to successfully achieve your goals
Achieving Your Goals: 5 Tips to successfully achieve your goals
 
Acciones de comunidades tech en tiempos del Covid19
Acciones de comunidades tech en tiempos del Covid19Acciones de comunidades tech en tiempos del Covid19
Acciones de comunidades tech en tiempos del Covid19
 
De lo operativo a lo estratégico: un modelo de management de diseño
De lo operativo a lo estratégico: un modelo de management de diseñoDe lo operativo a lo estratégico: un modelo de management de diseño
De lo operativo a lo estratégico: un modelo de management de diseño
 

Recently uploaded

Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 

Programación funcional con Haskell

  • 1. Programación Funcional en Haskell 2a parte Agustín Ramos Fonseca
  • 2. Un lenguaje de programación... • Funcional. Las funciones son construcciones de primera clase. • Puro. Las funciones no tienen efectos colaterales. • De evaluación perezosa. Las expresiones se evalúan hasta que es requerido. • De tipado estático. Con inferencia de tipos.
  • 3. Características • • • • • • • • • List comprehensions. Pattern matching. Currying Function Composition Infinite data structures. Agebraic Data Types Type classes. Applicative Functors Monads
  • 8. Eight Queens ! isValidSolution sol = all isValid fullPositions where fullPositions = zip sol [1..8] isValid pos = null $ intersect fullPositions $ diags pos diags pos = diag1 pos ++ diag2 pos ++ diag3 pos ++ diag4 pos diag1 (r,c) = [(r',c') | r' <- [r-1,r-2..1], r' >= 1, c' <- [c-1,c-2..1], c' >= 1, r'-c' == r-c ] diag2 (r,c) = [(r',c') | r' <- [r+1..8], r' <= 8, c' <- [c+1..8], diag3 (r,c) = [(r',c') | r' <- [r+1..8], r' <= 8, c' <- [c-1,c-2..1], c' >= 1, r'+c' == r+c ] diag4 (r,c) = [(r',c') | r' <- [r-1,r-2..1], r' >= 1, c' <- [c+1..8], ! eightQueens = filter isValidSolution $ permutations [1..8] c' <= 8, r'-c' == r-c ] c' <= 8, r'+c' == r+c ]
  • 10. Knights Tour type Position = (Int,Int) type Solution = [Position] ! possibleMovs :: Int -> Position -> [Position] possibleMovs n (r,c) = [(r',c') | r' <- [r-2..r+2], c' <- [c-2..c+2], isLMovement (r’,c'), isWithinBoard (r',c')] where isLMovement (r',c') = abs(r-r') + abs(c-c') == 3 isWithinBoard (r',c') = r' >= 1 && r' <= n && c' >= 1 && c' <= n
  • 11. Knights Tour tours :: Int -> Position -> [Solution] tours n from = tours' n from [[from]] where tours' n from sols = filter fullTour $ concat $ solutions n from sols solutions n from sols = parMap rpar (completeSols sols) $ possibleMovs n from completeSols sols m = if isNewPosition m sols then tours' n m $ appendToSolutions sols m else sols fullTour s = length s == n*n isNewPosition p appendToSolutions [] = all (isNothing . elemIndex p) mov = [[mov]] appendToSolutions sols mov = map (sol -> sol ++ [mov] ) sols ! knightsTour n = concat $ parMap rpar (tours n) allPositions where allPositions = [(r,c) | r <- [1..n], c <- [1..n]]
  • 13. Lattice Paths import Control.Monad.Memo ! pathsm 0 0 = return 0 pathsm 0 _ = return 1 pathsm _ 0 = return 1 pathsm r d = do r1 <- for2 memo pathsm (r - 1) d d1 <- for2 memo pathsm r (d -1) return (r1 + d1) ! evalPathsm :: (Num n, Ord n) => n -> n -> n evalPathsm r d = startEvalMemo $ pathsm r d ! runPathsm n = evalPathsm n n