SlideShare uma empresa Scribd logo
1 de 67
Baixar para ler offline
Haskell in the Real World



       Functional Programming Night
               Geekup Liverpool, 31st May, 2011
                hakim.cassimally@gmail.com




http://www.fickr.com/photos/jef_saf/3493852795/
What makes FP different?
●   MJD quoting Norvig (on Lisp):
    ●   “big, important features, features like frst-class
        functions, dynamic access to the symbol table,
        and automatic storage management.”
●   gluing functions together
●   declarative
Popular FP languages
●   Excel
●   SQL?
●   Linq (based on Haskell's monads)
●   Lisp → Scheme → Clojure
●   Strongly Typed FP (Hindley/Milner)
    ●   ML → Ocaml → F#
    ●   Haskell
What makes Haskell different?
●   Purity
●   Laziness
●   High Level
●   Strong Typing
●   Memory Managed
●   Modular
●   Mathematical rigour
    ●   category theory
Sounds a bit ivory tower?
●
    http://prog21.dadgum.com/31.html


    ●   Q “When will Haskell fnally go
           mainstream?”
    ●   A “most of it already has.”
Imperative programming
●
    records =
            [ "one", "two", "three", "four", "five" ]



    filtered = [];        j = 0;
    for (i = 0; i < length records; i++) {
            if (records[i] matches “o”) {
                filtered[j++] = records[i];
        }
    }
Imperative programming
●
    records =
            [ "one", "two", "three", "four", "five" ]



    filtered = [];       j = 0;
    for (i = 0; i < length records; i++) {
            if (records[i] matches “o”) {
                filtered[j++] = records[i];
        }
    }
Functional version
●
    filtered =
        filter (=~ “o”)
        records
Why is this better?
●   less code. less bugs
●   no synthetic variables
    ●
        i, j, length records
●   no risk of off-by-one error
●   intent clear from skimming
●   intent clear to compiler
●   parallelize (MapReduce, Hadoop)
Why is this better?
●   fewer codes. fewer bugs
●   no synthetic variables
    ●
        i, j, length records
●   no risk of off-by-one error
●   intent clear from skimming
●   intent clear to compiler
●   parallelize (MapReduce, Hadoop)
Your language has this construct
●   Perl: my   @filtered = grep /o/, @records;
●   .Net: var  filtered = from r in records
           where r.match('o') select r
●   Ruby: @filtered    = @records.grep /o/
●   Python: filtered    = [x for x in records
               if re.match('o', x)]
●   etc.
Another example
●
    countCaps = length
        . filter (isUpper . head)
        . words

    > countCaps “Hello there, Fred”
      2
Real World Haskell
●   JSON library
●   barcode reading
●   database
Quizzes
●   important subsystem of Makini's attention
    management system
●   real world (has customers, pays wages)
●   currently written in Perl
●   could it be ported to Haskell?
Haskell Quiz – proof of concept
●   full code at:
    ●
        https://github.com/
          osfameron/geekup-talk-haskell/


●   overview, to give a favour of programming
    in Haskell
Modelling the quiz
Modelling the quiz
Modelling the quiz
Modelling the quiz




2x
Modelling the quiz
Modelling the quiz




1x
Quiz tree data types
●   Quizzes
●   Sections
    ●   (randomized sections)
●   Questions
Quiz data type
●
    data QuizNode =
         Quiz            Name              [QuizNode]
       | Section         Name Score        [QuizNode]
       | RandomSection   Name Score Choose [QuizNode]
       | Question        Name Score         Answer
Quiz data type
●
    data QuizNode =
         Quiz            Name              [QuizNode]
       | Section         Name Score        [QuizNode]
       | RandomSection   Name Score Choose [QuizNode]
       | Question        Name Score         Answer


●
    type Name   = String

    type Score = Int
    type Choose = Int
Quiz data type
●
    data QuizNode =
         Quiz            Name              [QuizNode]
       | Section         Name Score        [QuizNode]
       | RandomSection   Name Score Choose [QuizNode]
       | Question        Name Score         Answer


●
    data Answer = MultiChoice [BoolAnswer]
                | StringChoice [String]
Quiz data type
●
    data QuizNode =
         Quiz            Name              [QuizNode]
       | Section         Name Score        [QuizNode]
       | RandomSection   Name Score Choose [QuizNode]
       | Question        Name Score         Answer


●
    data Answer = MultiChoice [BoolAnswer]
                | StringChoice [String]

●
    data BoolAnswer = BoolAnswer Bool String
Quiz data type
quiz,geo,pop :: QuizNode
quiz = Quiz “General Knowledge Quiz” [ pop, geo ]

geo = RandomSection “Geography” 40 2 [
    Question “What is the capital of England?”
      2 $ StringChoice [“London”],
    Question “What is the capital of France?”
      2 $ StringChoice [“Paris”],
    Question “What is the capital of Finland?”
      2 $ StringChoice [“Helsinki”],
    Question “What is the capital of Italy?”
      2 $ StringChoice [“Rome”, “Roma”],
 ]
Quiz data type
quiz,geo,pop :: QuizNode
quiz = Quiz “General Knowledge Quiz” [ pop, geo ]

geo = RandomSection “Geography” 40 2 [
    Question “What is the capital of England?”
      2 $ StringChoice [“London”],
    Question “What is the capital of France?”
      2 $ StringChoice [“Paris”],
    Question “What is the capital of Finland?”
      2 $ StringChoice [“Helsinki”],
    Question “What is the capital of Italy?”
      2 $ StringChoice [“Rome”, “Roma”],
 ]
Quiz data type
quiz,geo,pop :: QuizNode
quiz = Quiz “General Knowledge Quiz” [ pop, geo ]

geo = RandomSection “Geography” 40 2 [
    Question “What is the capital of England?”
      2 $ StringChoice [“London”],
    Question “What is the capital of France?”
      2 $ StringChoice [“Paris”],
    Question “What is the capital of Finland?”
      2 $ StringChoice [“Helsinki”],
    Question “What is the capital of Italy?”
      2 $ StringChoice [“Rome”, “Roma”],
 ]
Quiz data type
pop = Section “Pop music” 60 [
    Question “Which of these are Beatles?” 5
        $ MultiChoice [
            y “John”,
            y “Paul”,
            y “George”,
            y “Ringo”,
            n “Bob”,
            n “Jason” ],
            ...
Quiz data type
pop = Section “Pop music” 60 [
    Question “Which of these are Beatles?” 5
        $ MultiChoice [
            BoolAnswer True “John”,
            BoolAnswer True “Paul”,
            BoolAnswer True “George”,
            BoolAnswer True “Ringo”,
            BoolAnswer False “Bob”,
            BoolAnswer False “Jason” ],
            ...
Quiz data type
pop = Section “Pop music” 60 [
    Question “Which of these are Beatles?” 5
        $ MultiChoice [
            y “John”,
            y “Paul”,
            y “George”,
            y “Ringo”,
            n “Bob”,
            n “Jason” ],
            ...

y,n :: String -> BoolAnswer
y = BoolAnswer True
n = BoolAnswer False
Stamping the quiz


1x        2x
Stamping the quiz


1x        2x
Stamping the quiz
         stamp ::
           QuizNode → ...

1x        2x
Stamping the quiz
         stamp ::
           QuizNode → QuizNode?

1x        2x
Functions
●
    increment :: Num → Num
    ●
        increment 4   => 5
    ●
        increment 10 => 11
Functions
●
    increment :: Num → Num
    ●
        increment 4   => 5
    ●
        increment 10 => 11
Functions
●
    increment :: Num → Num
    ●
        increment 4   => 5
    ●
        increment 10 => 11
Functions
●
    increment :: Num → Num
●
    increment x = x+1
Functions

let x = 42




   addx :: Num → Num
   add y = x + y
Functions

           (cannot
let x = 42 change!)




    addx :: Num → Num
    add y = x + y
Functions

let x = 42




   addx :: Num → Num
   add y = x + y
Stamping the quiz
         stamp ::
           QuizNode → QuizNode?

1x        2x
Stamping the quiz
         stamp ::
           QuizNode → QuizNode?

1x        2x
Stamping the quiz
         stamp ::
           QuizNode → IO QuizNode

1x        2x
Monads
●   Useful data-structure
●   Lets us model various thing...
    ●   including IO in a pure language
●   Concept is a little confusing
●   Using them is (mostly) not too bad.
Stamping the quiz
    stamp ::
      QuizNode → IO QuizNode
Stamping the quiz
         stamp ::
           QuizNode → IO QuizNode

1x        2x
Stamping the quiz
         stamp ::
           QuizNode → IO QuizNode

1x        2x
Stamping the quiz
    stamp ::
      QuizNode → IO QuizNode
Stamping the quiz
    stamp ::
      QuizNode → IO QuizNode
The stamp function
stamp :: QuizNode -> IO QuizNode

stamp q@(Question _ _ _) = return q

stamp (Quiz s ns)      = Quiz    s   <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns

stamp (RandomSection s i r ns)
   = do selected <- pickN r ns
        Section s i <$> mapM stamp selected
The stamp function
stamp :: QuizNode -> IO QuizNode

stamp q@(Question _ _ _) = return q

stamp (Quiz s ns)      = Quiz    s   <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns

stamp (RandomSection s i r ns)
   = do selected <- pickN r ns
        Section s i <$> mapM stamp selected
The stamp function
                                       map stamp ns
stamp :: QuizNode -> IO QuizNode       – “stamp all the
                                       child nodes in
stamp q@(Question _ _ _) = return q    turn”
stamp (Quiz s ns)      = Quiz    s   <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns

stamp (RandomSection s i r ns)
   = do selected <- pickN r ns
        Section s i <$> mapM stamp selected
The stamp function
stamp :: QuizNode -> IO QuizNode

stamp q@(Question _ _ _) = return q

stamp (Quiz s ns)      = Quiz    s   <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns

stamp (RandomSection s i r ns)
   = do selected <- pickN r ns
        Section s i <$> mapM stamp selected
The stamp function
stamp :: QuizNode -> IO QuizNode

stamp q@(Question _ _ _) = return q

stamp (Quiz s ns)      = Quiz    s   <$> mapM stamp ns
stamp (Section s i ns) = Section s i <$> mapM stamp ns

stamp (RandomSection s i r ns)
   = do selected <- pickN r ns
        Section s i <$> mapM stamp selected
1x
Taking the quiz!
●
    takeNode ::
     QuizNode -> IO CompletedNode
●
    printQuestion ::
     QuizNode -> IO ()
●
    showBoolTextAnswers ::
     [BoolAnswer] -> String
●
    checkAnswer ::
     String -> Answer -> Bool
Taking the quiz!
●
    takeNode ::
     QuizNode -> IO CompletedNode
●
    printQuestion ::
     QuizNode -> IO ()
●
    showBoolTextAnswers ::
     [BoolAnswer] -> String
●
    checkAnswer ::
     String -> Answer -> Bool
Taking the quiz!
●
    takeNode ::
     QuizNode -> IO CompletedNode
●
    printQuestion ::
     QuizNode -> IO ()
●
    showBoolTextAnswers ::
     [BoolAnswer] -> String
●
    checkAnswer ::
     String -> Answer -> Bool
Taking the quiz!
●
    takeNode ::
     QuizNode -> IO CompletedNode
●
    printQuestion ::
     QuizNode -> IO ()
●
    showBoolTextAnswers ::
     [BoolAnswer] -> String
●
    checkAnswer ::
     String -> Answer -> Bool
takeNode
takeNode node@(Question s i a) = do
    printQuestion node
    ans <- getLine
    let correct = checkAnswer ans a
    let score = if correct
      then (i,i) else (0,i)
    putStrLn $ if correct
      then “Correct!” else “Wrong!”
    return $
      CompletedNode ans score [] node
main
main :: IO ()
main = stamp quiz >>= takeQuiz


  Function, not entrypoint
main
main :: IO ()
main = stamp quiz >>= takeQuiz




        Live Demo!
Should you go Haskell?
●   Power
●   Speed?
    ●   can be faster than C (supercompilation)
    ●   can be tricky to optimize
●   Jobs?
    ●   In NorthWestUK?
●   Libraries & Tools
    ●   Haskell Platform. Hackage. Cabal
Should you learn Haskell?
●   Powerful
●   Interesting techniques
●   … and ways of thinking about problems
●   Ready for future shift to FP
●   … possibly in your own language
Thank you! Questions?
    ●   full code at:
        ●
            https://github.com/
              osfameron/geekup-talk-haskell/


    ●   hakim.cassimally@gmail.com




http://www.fickr.com/photos/jef_saf/3493852795/

Mais conteúdo relacionado

Mais procurados

First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation streamRuslan Shevchenko
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonMax Klymyshyn
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. ExperienceMike Fogus
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Paulo Morgado
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsJohn De Goes
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)stasimus
 

Mais procurados (20)

A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and PythonOdessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & AnalyticsQuark: A Purely-Functional Scala DSL for Data Processing & Analytics
Quark: A Purely-Functional Scala DSL for Data Processing & Analytics
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 

Destaque

Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
 
Web programming in Haskell
Web programming in HaskellWeb programming in Haskell
Web programming in Haskellchriseidhof
 
From Ruby to Haskell (Kansai Yami RubyKaigi)
From Ruby to Haskell (Kansai Yami RubyKaigi)From Ruby to Haskell (Kansai Yami RubyKaigi)
From Ruby to Haskell (Kansai Yami RubyKaigi)ujihisa
 
[WebCamp2014] Towards functional web
[WebCamp2014] Towards functional web[WebCamp2014] Towards functional web
[WebCamp2014] Towards functional webBlaž Repas
 
Fotos graciosas 33657
Fotos graciosas 33657Fotos graciosas 33657
Fotos graciosas 33657serviojapon
 
Learn Haskell The Easy Way
Learn Haskell The Easy WayLearn Haskell The Easy Way
Learn Haskell The Easy WayYC Ling
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)Bikram Thapa
 
Building a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.jsBuilding a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.jsNicolas Hery
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskellgoncharenko
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git민태 김
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
Online movie ticket booking
Online movie ticket bookingOnline movie ticket booking
Online movie ticket bookingmrinnovater007
 

Destaque (17)

Functional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures edition
 
Web programming in Haskell
Web programming in HaskellWeb programming in Haskell
Web programming in Haskell
 
From Ruby to Haskell (Kansai Yami RubyKaigi)
From Ruby to Haskell (Kansai Yami RubyKaigi)From Ruby to Haskell (Kansai Yami RubyKaigi)
From Ruby to Haskell (Kansai Yami RubyKaigi)
 
[WebCamp2014] Towards functional web
[WebCamp2014] Towards functional web[WebCamp2014] Towards functional web
[WebCamp2014] Towards functional web
 
El Protocolo de Kioto
El Protocolo de KiotoEl Protocolo de Kioto
El Protocolo de Kioto
 
Fotos graciosas 33657
Fotos graciosas 33657Fotos graciosas 33657
Fotos graciosas 33657
 
Learn Haskell The Easy Way
Learn Haskell The Easy WayLearn Haskell The Easy Way
Learn Haskell The Easy Way
 
Functional programming seminar (haskell)
Functional programming seminar (haskell)Functional programming seminar (haskell)
Functional programming seminar (haskell)
 
Building a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.jsBuilding a website in Haskell coming from Node.js
Building a website in Haskell coming from Node.js
 
Haskell study 8
Haskell study 8Haskell study 8
Haskell study 8
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
OSCON14: Mirage 2.0
OSCON14: Mirage 2.0 OSCON14: Mirage 2.0
OSCON14: Mirage 2.0
 
Jobs ppt
Jobs pptJobs ppt
Jobs ppt
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
버전관리를 들어본적 없는 사람들을 위한 DVCS - Git
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Online movie ticket booking
Online movie ticket bookingOnline movie ticket booking
Online movie ticket booking
 

Semelhante a Haskell in the Real World

Python Fundamentals - Basic
Python Fundamentals - BasicPython Fundamentals - Basic
Python Fundamentals - BasicWei-Yuan Chang
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In RubyRoss Lawley
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsMichael Pirnat
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門Hiromi Ishii
 
Joshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayJoshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayRefresh Events
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software DevelopmentNaveenkumar Muguda
 
Convex Hull Approximation of Nearly Optimal Lasso Solutions
Convex Hull Approximation of Nearly Optimal Lasso SolutionsConvex Hull Approximation of Nearly Optimal Lasso Solutions
Convex Hull Approximation of Nearly Optimal Lasso SolutionsSatoshi Hara
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016Codemotion
 
Locality sensitive hashing
Locality sensitive hashingLocality sensitive hashing
Locality sensitive hashingSEMINARGROOT
 
Pontificating quantification
Pontificating quantificationPontificating quantification
Pontificating quantificationAaron Bedra
 
Querying your database in natural language by Daniel Moisset PyData SV 2014
Querying your database in natural language by Daniel Moisset PyData SV 2014Querying your database in natural language by Daniel Moisset PyData SV 2014
Querying your database in natural language by Daniel Moisset PyData SV 2014PyData
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobikrmboya
 
PyCon2009_AI_Alt
PyCon2009_AI_AltPyCon2009_AI_Alt
PyCon2009_AI_AltHiroshi Ono
 

Semelhante a Haskell in the Real World (20)

Python Fundamentals - Basic
Python Fundamentals - BasicPython Fundamentals - Basic
Python Fundamentals - Basic
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Intro
IntroIntro
Intro
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Invertible-syntax 入門
Invertible-syntax 入門Invertible-syntax 入門
Invertible-syntax 入門
 
7li7w devcon5
7li7w devcon57li7w devcon5
7li7w devcon5
 
GuessWhat?!
GuessWhat?!GuessWhat?!
GuessWhat?!
 
Joshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages TodayJoshua Wehner - Tomorrows Programming Languages Today
Joshua Wehner - Tomorrows Programming Languages Today
 
Yin Yangs of Software Development
Yin Yangs of Software DevelopmentYin Yangs of Software Development
Yin Yangs of Software Development
 
Convex Hull Approximation of Nearly Optimal Lasso Solutions
Convex Hull Approximation of Nearly Optimal Lasso SolutionsConvex Hull Approximation of Nearly Optimal Lasso Solutions
Convex Hull Approximation of Nearly Optimal Lasso Solutions
 
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
How to avoid Go gotchas - Ivan Daniluk - Codemotion Milan 2016
 
Locality sensitive hashing
Locality sensitive hashingLocality sensitive hashing
Locality sensitive hashing
 
Pontificating quantification
Pontificating quantificationPontificating quantification
Pontificating quantification
 
Fancy talk
Fancy talkFancy talk
Fancy talk
 
Querying your database in natural language by Daniel Moisset PyData SV 2014
Querying your database in natural language by Daniel Moisset PyData SV 2014Querying your database in natural language by Daniel Moisset PyData SV 2014
Querying your database in natural language by Daniel Moisset PyData SV 2014
 
Quepy
QuepyQuepy
Quepy
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
 
PyCon2009_AI_Alt
PyCon2009_AI_AltPyCon2009_AI_Alt
PyCon2009_AI_Alt
 

Mais de osfameron

Writing a Tile-Matching Game - FP Style
Writing a Tile-Matching Game - FP StyleWriting a Tile-Matching Game - FP Style
Writing a Tile-Matching Game - FP Styleosfameron
 
Data Structures for Text Editors
Data Structures for Text EditorsData Structures for Text Editors
Data Structures for Text Editorsosfameron
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?osfameron
 
Rewriting the Apocalypse
Rewriting the ApocalypseRewriting the Apocalypse
Rewriting the Apocalypseosfameron
 
Global Civic Hacking 101 (lightning talk)
Global Civic Hacking 101 (lightning talk)Global Civic Hacking 101 (lightning talk)
Global Civic Hacking 101 (lightning talk)osfameron
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperosfameron
 
Adventures in civic hacking
Adventures in civic hackingAdventures in civic hacking
Adventures in civic hackingosfameron
 
Oyster: an incubator for perls in the cloud
Oyster: an incubator for perls in the cloudOyster: an incubator for perls in the cloud
Oyster: an incubator for perls in the cloudosfameron
 
Semantic Pipes (London Perl Workshop 2009)
Semantic Pipes (London Perl Workshop 2009)Semantic Pipes (London Perl Workshop 2009)
Semantic Pipes (London Perl Workshop 2009)osfameron
 
Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)osfameron
 
Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2osfameron
 
Functional Pe(a)rls
Functional Pe(a)rlsFunctional Pe(a)rls
Functional Pe(a)rlsosfameron
 
Readable Perl
Readable PerlReadable Perl
Readable Perlosfameron
 

Mais de osfameron (14)

Writing a Tile-Matching Game - FP Style
Writing a Tile-Matching Game - FP StyleWriting a Tile-Matching Game - FP Style
Writing a Tile-Matching Game - FP Style
 
Data Structures for Text Editors
Data Structures for Text EditorsData Structures for Text Editors
Data Structures for Text Editors
 
Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
 
Rewriting the Apocalypse
Rewriting the ApocalypseRewriting the Apocalypse
Rewriting the Apocalypse
 
Global Civic Hacking 101 (lightning talk)
Global Civic Hacking 101 (lightning talk)Global Civic Hacking 101 (lightning talk)
Global Civic Hacking 101 (lightning talk)
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
 
Adventures in civic hacking
Adventures in civic hackingAdventures in civic hacking
Adventures in civic hacking
 
Oyster: an incubator for perls in the cloud
Oyster: an incubator for perls in the cloudOyster: an incubator for perls in the cloud
Oyster: an incubator for perls in the cloud
 
Semantic Pipes (London Perl Workshop 2009)
Semantic Pipes (London Perl Workshop 2009)Semantic Pipes (London Perl Workshop 2009)
Semantic Pipes (London Perl Workshop 2009)
 
Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)
 
Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
 
Functional Pe(a)rls
Functional Pe(a)rlsFunctional Pe(a)rls
Functional Pe(a)rls
 
Readable Perl
Readable PerlReadable Perl
Readable Perl
 
Bigbadwolf
BigbadwolfBigbadwolf
Bigbadwolf
 

Haskell in the Real World

  • 1. Haskell in the Real World Functional Programming Night Geekup Liverpool, 31st May, 2011 hakim.cassimally@gmail.com http://www.fickr.com/photos/jef_saf/3493852795/
  • 2. What makes FP different? ● MJD quoting Norvig (on Lisp): ● “big, important features, features like frst-class functions, dynamic access to the symbol table, and automatic storage management.” ● gluing functions together ● declarative
  • 3. Popular FP languages ● Excel ● SQL? ● Linq (based on Haskell's monads) ● Lisp → Scheme → Clojure ● Strongly Typed FP (Hindley/Milner) ● ML → Ocaml → F# ● Haskell
  • 4. What makes Haskell different? ● Purity ● Laziness ● High Level ● Strong Typing ● Memory Managed ● Modular ● Mathematical rigour ● category theory
  • 5. Sounds a bit ivory tower? ● http://prog21.dadgum.com/31.html ● Q “When will Haskell fnally go mainstream?” ● A “most of it already has.”
  • 6. Imperative programming ● records = [ "one", "two", "three", "four", "five" ] filtered = []; j = 0; for (i = 0; i < length records; i++) { if (records[i] matches “o”) { filtered[j++] = records[i]; } }
  • 7. Imperative programming ● records = [ "one", "two", "three", "four", "five" ] filtered = []; j = 0; for (i = 0; i < length records; i++) { if (records[i] matches “o”) { filtered[j++] = records[i]; } }
  • 8. Functional version ● filtered = filter (=~ “o”) records
  • 9. Why is this better? ● less code. less bugs ● no synthetic variables ● i, j, length records ● no risk of off-by-one error ● intent clear from skimming ● intent clear to compiler ● parallelize (MapReduce, Hadoop)
  • 10. Why is this better? ● fewer codes. fewer bugs ● no synthetic variables ● i, j, length records ● no risk of off-by-one error ● intent clear from skimming ● intent clear to compiler ● parallelize (MapReduce, Hadoop)
  • 11. Your language has this construct ● Perl: my @filtered = grep /o/, @records; ● .Net: var filtered = from r in records where r.match('o') select r ● Ruby: @filtered = @records.grep /o/ ● Python: filtered = [x for x in records if re.match('o', x)] ● etc.
  • 12. Another example ● countCaps = length . filter (isUpper . head) . words > countCaps “Hello there, Fred” 2
  • 13. Real World Haskell ● JSON library ● barcode reading ● database
  • 14. Quizzes ● important subsystem of Makini's attention management system ● real world (has customers, pays wages) ● currently written in Perl ● could it be ported to Haskell?
  • 15. Haskell Quiz – proof of concept ● full code at: ● https://github.com/ osfameron/geekup-talk-haskell/ ● overview, to give a favour of programming in Haskell
  • 22. Quiz tree data types ● Quizzes ● Sections ● (randomized sections) ● Questions
  • 23. Quiz data type ● data QuizNode = Quiz Name [QuizNode] | Section Name Score [QuizNode] | RandomSection Name Score Choose [QuizNode] | Question Name Score Answer
  • 24. Quiz data type ● data QuizNode = Quiz Name [QuizNode] | Section Name Score [QuizNode] | RandomSection Name Score Choose [QuizNode] | Question Name Score Answer ● type Name = String type Score = Int type Choose = Int
  • 25. Quiz data type ● data QuizNode = Quiz Name [QuizNode] | Section Name Score [QuizNode] | RandomSection Name Score Choose [QuizNode] | Question Name Score Answer ● data Answer = MultiChoice [BoolAnswer] | StringChoice [String]
  • 26. Quiz data type ● data QuizNode = Quiz Name [QuizNode] | Section Name Score [QuizNode] | RandomSection Name Score Choose [QuizNode] | Question Name Score Answer ● data Answer = MultiChoice [BoolAnswer] | StringChoice [String] ● data BoolAnswer = BoolAnswer Bool String
  • 27. Quiz data type quiz,geo,pop :: QuizNode quiz = Quiz “General Knowledge Quiz” [ pop, geo ] geo = RandomSection “Geography” 40 2 [ Question “What is the capital of England?” 2 $ StringChoice [“London”], Question “What is the capital of France?” 2 $ StringChoice [“Paris”], Question “What is the capital of Finland?” 2 $ StringChoice [“Helsinki”], Question “What is the capital of Italy?” 2 $ StringChoice [“Rome”, “Roma”], ]
  • 28. Quiz data type quiz,geo,pop :: QuizNode quiz = Quiz “General Knowledge Quiz” [ pop, geo ] geo = RandomSection “Geography” 40 2 [ Question “What is the capital of England?” 2 $ StringChoice [“London”], Question “What is the capital of France?” 2 $ StringChoice [“Paris”], Question “What is the capital of Finland?” 2 $ StringChoice [“Helsinki”], Question “What is the capital of Italy?” 2 $ StringChoice [“Rome”, “Roma”], ]
  • 29. Quiz data type quiz,geo,pop :: QuizNode quiz = Quiz “General Knowledge Quiz” [ pop, geo ] geo = RandomSection “Geography” 40 2 [ Question “What is the capital of England?” 2 $ StringChoice [“London”], Question “What is the capital of France?” 2 $ StringChoice [“Paris”], Question “What is the capital of Finland?” 2 $ StringChoice [“Helsinki”], Question “What is the capital of Italy?” 2 $ StringChoice [“Rome”, “Roma”], ]
  • 30. Quiz data type pop = Section “Pop music” 60 [ Question “Which of these are Beatles?” 5 $ MultiChoice [ y “John”, y “Paul”, y “George”, y “Ringo”, n “Bob”, n “Jason” ], ...
  • 31. Quiz data type pop = Section “Pop music” 60 [ Question “Which of these are Beatles?” 5 $ MultiChoice [ BoolAnswer True “John”, BoolAnswer True “Paul”, BoolAnswer True “George”, BoolAnswer True “Ringo”, BoolAnswer False “Bob”, BoolAnswer False “Jason” ], ...
  • 32. Quiz data type pop = Section “Pop music” 60 [ Question “Which of these are Beatles?” 5 $ MultiChoice [ y “John”, y “Paul”, y “George”, y “Ringo”, n “Bob”, n “Jason” ], ... y,n :: String -> BoolAnswer y = BoolAnswer True n = BoolAnswer False
  • 35. Stamping the quiz stamp :: QuizNode → ... 1x 2x
  • 36. Stamping the quiz stamp :: QuizNode → QuizNode? 1x 2x
  • 37. Functions ● increment :: Num → Num ● increment 4 => 5 ● increment 10 => 11
  • 38. Functions ● increment :: Num → Num ● increment 4 => 5 ● increment 10 => 11
  • 39. Functions ● increment :: Num → Num ● increment 4 => 5 ● increment 10 => 11
  • 40. Functions ● increment :: Num → Num ● increment x = x+1
  • 41. Functions let x = 42 addx :: Num → Num add y = x + y
  • 42. Functions (cannot let x = 42 change!) addx :: Num → Num add y = x + y
  • 43. Functions let x = 42 addx :: Num → Num add y = x + y
  • 44. Stamping the quiz stamp :: QuizNode → QuizNode? 1x 2x
  • 45. Stamping the quiz stamp :: QuizNode → QuizNode? 1x 2x
  • 46. Stamping the quiz stamp :: QuizNode → IO QuizNode 1x 2x
  • 47. Monads ● Useful data-structure ● Lets us model various thing... ● including IO in a pure language ● Concept is a little confusing ● Using them is (mostly) not too bad.
  • 48. Stamping the quiz stamp :: QuizNode → IO QuizNode
  • 49. Stamping the quiz stamp :: QuizNode → IO QuizNode 1x 2x
  • 50. Stamping the quiz stamp :: QuizNode → IO QuizNode 1x 2x
  • 51. Stamping the quiz stamp :: QuizNode → IO QuizNode
  • 52. Stamping the quiz stamp :: QuizNode → IO QuizNode
  • 53. The stamp function stamp :: QuizNode -> IO QuizNode stamp q@(Question _ _ _) = return q stamp (Quiz s ns) = Quiz s <$> mapM stamp ns stamp (Section s i ns) = Section s i <$> mapM stamp ns stamp (RandomSection s i r ns) = do selected <- pickN r ns Section s i <$> mapM stamp selected
  • 54. The stamp function stamp :: QuizNode -> IO QuizNode stamp q@(Question _ _ _) = return q stamp (Quiz s ns) = Quiz s <$> mapM stamp ns stamp (Section s i ns) = Section s i <$> mapM stamp ns stamp (RandomSection s i r ns) = do selected <- pickN r ns Section s i <$> mapM stamp selected
  • 55. The stamp function map stamp ns stamp :: QuizNode -> IO QuizNode – “stamp all the child nodes in stamp q@(Question _ _ _) = return q turn” stamp (Quiz s ns) = Quiz s <$> mapM stamp ns stamp (Section s i ns) = Section s i <$> mapM stamp ns stamp (RandomSection s i r ns) = do selected <- pickN r ns Section s i <$> mapM stamp selected
  • 56. The stamp function stamp :: QuizNode -> IO QuizNode stamp q@(Question _ _ _) = return q stamp (Quiz s ns) = Quiz s <$> mapM stamp ns stamp (Section s i ns) = Section s i <$> mapM stamp ns stamp (RandomSection s i r ns) = do selected <- pickN r ns Section s i <$> mapM stamp selected
  • 57. The stamp function stamp :: QuizNode -> IO QuizNode stamp q@(Question _ _ _) = return q stamp (Quiz s ns) = Quiz s <$> mapM stamp ns stamp (Section s i ns) = Section s i <$> mapM stamp ns stamp (RandomSection s i r ns) = do selected <- pickN r ns Section s i <$> mapM stamp selected 1x
  • 58. Taking the quiz! ● takeNode :: QuizNode -> IO CompletedNode ● printQuestion :: QuizNode -> IO () ● showBoolTextAnswers :: [BoolAnswer] -> String ● checkAnswer :: String -> Answer -> Bool
  • 59. Taking the quiz! ● takeNode :: QuizNode -> IO CompletedNode ● printQuestion :: QuizNode -> IO () ● showBoolTextAnswers :: [BoolAnswer] -> String ● checkAnswer :: String -> Answer -> Bool
  • 60. Taking the quiz! ● takeNode :: QuizNode -> IO CompletedNode ● printQuestion :: QuizNode -> IO () ● showBoolTextAnswers :: [BoolAnswer] -> String ● checkAnswer :: String -> Answer -> Bool
  • 61. Taking the quiz! ● takeNode :: QuizNode -> IO CompletedNode ● printQuestion :: QuizNode -> IO () ● showBoolTextAnswers :: [BoolAnswer] -> String ● checkAnswer :: String -> Answer -> Bool
  • 62. takeNode takeNode node@(Question s i a) = do printQuestion node ans <- getLine let correct = checkAnswer ans a let score = if correct then (i,i) else (0,i) putStrLn $ if correct then “Correct!” else “Wrong!” return $ CompletedNode ans score [] node
  • 63. main main :: IO () main = stamp quiz >>= takeQuiz Function, not entrypoint
  • 64. main main :: IO () main = stamp quiz >>= takeQuiz Live Demo!
  • 65. Should you go Haskell? ● Power ● Speed? ● can be faster than C (supercompilation) ● can be tricky to optimize ● Jobs? ● In NorthWestUK? ● Libraries & Tools ● Haskell Platform. Hackage. Cabal
  • 66. Should you learn Haskell? ● Powerful ● Interesting techniques ● … and ways of thinking about problems ● Ready for future shift to FP ● … possibly in your own language
  • 67. Thank you! Questions? ● full code at: ● https://github.com/ osfameron/geekup-talk-haskell/ ● hakim.cassimally@gmail.com http://www.fickr.com/photos/jef_saf/3493852795/