SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Refresher

                 Sebastian Rettig


“Work on Haskell began in 1987 when aa committee of
 “Work on Haskell began in 1987 when committee of
researchers got together to design aa kick-asslanguage.” ([1])
 researchers got together to design kick-ass language.” ([1])
Imperative Programming
●   Variables (value placeholder)
       –   Value can change during program flow
●   Modules, Classes, Functions, Procedures
●   Control Flow Structures (IF THEN ELSE,
     Loops (WHILE), Goto)
Functional Programming
●   No Variables
●   Functions only, eventually stored in
     Modules
       –   Behavior do not change, once defined
       –   → Function called with same parameter
            calculates always the same result
●   Function definitions (Match Cases)
●   Recursion
Haskell Refresher Quiz
●   What's the red one ?
●




maxList :: (Ord a) => [a] -> a

maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●




maxList :: (Ord a) => [a] -> a
                                 Function
maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●




maxList :: (Ord a) => [a] -> a

maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●




maxList :: (Ord a) => [a] -> a
                                 Function Header
maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
    maxList :: [Int] -> Int

    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail
     where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●
    maxList :: [Int] -> Int

●   maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)
     | x > maxTail = x            Function Body
     | otherwise = maxTail
     where maxTail = maxList xs
Haskell Functions
●   function contains header and body
●   header consists of type definition:
    <funcname> :: <param> [ -> <param_n>] -> <result>
●   body consists of pattern rules and calculation
     <funcname> <paramalias_1> [<paramalias_n>] =
    {calc}
●   Example (2 params if type [Int] & Int, result Bool):
          isHead :: [Int] -> Int -> Bool
          isHead xs i = i==head xs
Haskell Refresher Quiz
●    What's the red one ?
●




    maxList :: [Int] ->   Int

    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail
     where maxTail = maxList xs
Haskell Refresher Quiz
●    What's the red one ?
●




    maxList :: [Int] ->   Int
                                  Type
    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail
     where maxTail = maxList xs
Types in Haskell (1)
Starts with uppercase first character

●   Int bounded from -2147483648 to 2147483647
●   Integer unbounded (for big numbers) but slower than Int
●   Float floating point (single precision)
●   Double floating point (double precision)
●   Bool boolean
●   Char character
●   String list of Char (String == [Char])
Types in Haskell (2)
●   Lists: must be homogenous (entries from the same type)
        –   [] empty List
        –   [Int] List of Int
        –   But e.g. [Int, Bool] not allowed (not homogenous)!
●   Tuples: can contain different types BUT have fixed length
        –   () empty tuple (has only 1 value)
        –   (Int, Bool) tuple of a pair Int, Bool
        –   (Int, Bool, Bool) tuple of Int, Bool, Bool
Lists & List Comprehension
●   Example: double entries in list
           doubleList [] = []
           doubleList (x:xs) = x:x:doubleList xs
       –   e.g. [1,2,3] → x=1; xs=[2,3]
●   Multiplication of a list of values:
           Hugs> product [1..5]
             120
●   or in a function:
           fac n = product [1..n]
Haskell Refresher Quiz
●    What's the red one ?
●
maxList :: [Int] -> Int

maxList [] =          error “empty”
maxList [x] = x
maxList (x:xs)

    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maxList xs
Haskell Refresher Quiz
●    What's the red one ?
●
maxList :: [Int] -> Int

maxList [] =
maxList [x] = x
                      error “empty”
                                       Pattern
maxList (x:xs)
                                      Matching
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●   maxList :: [Int] -> Int

    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)

     | x > maxTail = x
     | otherwise = maxTail

     where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●


    maxList :: [Int] -> Int

    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)

     | x > maxTail = x
     | otherwise = maxTail        Guards
     where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●
    maxList :: [Int] -> Int

    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail


     where maxTail = maxList xs
Haskell Refresher Quiz
●   What's the red one ?
●
    maxList :: [Int] -> Int

    maxList [] = error “empty”
    maxList [x] = x
    maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail
                                      Additional
     where maxTail = maxList xs
                                  'where' clause
Pattern Matching (1)
●   create matching rules:
        fac 0 = 1
        fac n = n * fac (n-1)
●   use wildcards to ignore parameters in
     pattern:
        take 0 _ = []
        take _ [] = []
        take n (x:xs) = [x] ++ take (n-1) xs
Pattern Matching (2)
●   use Guards to separate a matching case deeper:
            myFilter _ [] = []
            myFilter f (x:xs)
               | f==x = x:myFilter g xs
               | otherwise = myFilter f xs
               where g = 2*f
        –   like an IF THEN ELSE
        –   Guard Condition evaluate to Bool (True/False)
●   eventually define values with where-clause
            myFilter 2 [1,2,3,4,5,6] results to [2,4]
Recursion
●   Recursion vs. Final Recursion:
countX :: Int -> [Int] -> Int           ●   Hugs> countX 3 [1,4,3,5,3]
countX x [] = 0                              2
countX x (y:ys)
  | x==y = 1 + countX x ys
  | otherwise = countX x ys

                     countXFinal :: Int -> [Int] -> Int -> Int
                     countXFinal x [] accu = accu
                     countXFinal x (y:ys) accu
                       | x==y = countXFinal x ys accu+1
                       | otherwise = countXFinal x ys accu
●   use accumulator to reduce stack usage
●   Hugs> countXFinal 3 [1,4,3,5,3] 0
        2
Haskell Refresher Quiz
  ●   What's the red one ?
  ●




maxList ::   (Ord a) =>   [a] -> a

maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
 | x > maxTail = x
 | otherwise = maxTail
 where maxTail = maxList xs
Haskell Refresher Quiz
  ●   What's the red one ?
  ●




maxList ::   (Ord a) =>   [a] -> a
                                     Typeclass
maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
 | x > maxTail = x
 | otherwise = maxTail
 where maxTail = maxList xs
Haskell Refresher Quiz
 ●     What's the red one ?
 ●




maxList :: (Ord       a   ) =>    [a] -> a

maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail
     where maxTail = maxList xs
Haskell Refresher Quiz
 ●     What's the red one ?
 ●




maxList :: (Ord       a   ) =>    [a] -> a
                                             Type variable
maxList [] = error “empty”
maxList [x] = x
maxList (x:xs)
     | x > maxTail = x
     | otherwise = maxTail
     where maxTail = maxList xs
Type Polymorphism (1)
●   Statically typed, but Compiler can read type from
      context (type inference)
●   → no need to set type explicitly
●   → makes function more generic for different
     kinds of types (type polymorphism)
       –   Why should I use quicksort :: [Int] -> [Int]
       –   even if I also want to sort character?
           Hugs> quicksort ['f','a','d','b']
              "abdf"
Type Polymorphism (2)
●   the header of our previous implementations could be
    fact :: Int -> Int
    maxList :: [Int] -> Int
●   but is only limited to Int, but maxList could also
      handle Char
●   → why not make it generic?
    maxList :: [a] -> a
●   but what happens, if the corresponding Type is not
      comparable or cannot be ordered?
Type Polymorphism (3)
●   Solution: use Typeclasses
    maxList :: (Ord a) => [a] -> a
●   then we can be sure to use (<,<=, ==, /=, >=, >)
●   function header can contain multiple typeclasses
    maxList :: (Ord a, Eq b) => [a] -> [b] -> a
●   In Haskell-Interpreter: to list the function header
    :t <function_name>
Typeclasses (1)
●   define properties of the types
●   like an interface
●   Typeclasses:
         –   Eq can be compared
         –   Ord can be ordered (>, <, >=, <=) (extending Eq)
         –   Show can be shown as string
         –   Read opposite of Show
         –   Enum sequentially ordered types (can be enumerated
             and usable in List-Ranges ['a'..'e'])
Typeclasses (2)
●   Typeclasses:
         –   Bounded upper/lower bound (minBound, maxBound)
         –   Num types behave like numbers (must already be Show, Eq)
         –   Integral contains only integrals (subclass of Num)
         –   Floating corresponding real numbers (subclass of Num)
●   if all Types of tuple are in same Typeclass → Tuple also in
        Typeclass
Haskell Refresher Quiz
●   Which will terminate?
    (1)   head [1..]
    (2)   last [1..]
    (3)   tail [1,2,3,4,5,6]
    (4)   init (take 5 (cycle [1..]))
Haskell Refresher Quiz
●   Which will terminate?
    (1) head [1..]
    (2) last [1..]
    (3) tail [1,2,3,4,5,6]
    (4) init (take 5 (cycle [1..]))
●   (1), (3) and (4) because of
    Lazy Evaluation
Lazy Evaluation
●   Function execution only if result is needed
●   → Program = series of data-transformations
●   Example: A(B(C(x)))
       –   If A needs result from B → call B
       –   If B needs result from C → call C
Haskell Refresher Quiz
●   Which one is faster?
    (1)   head (take 5 [1,2,3,4,5,6])
    (2)   head (take 5 [1..10])
    (3)   head (take 5 [1..])
    (4)   head (take 5 (cycle [1..10]))
Haskell Refresher Quiz
●   Which one is faster?
    (1) head (take 5 [1,2,3,4,5,6])
    (2) head (take 5 [1..10])
    (3) head (take 5 [1..])
    (4) head (take 5 (cycle [1..10]))
●   Everyone is equal because of
    Lazy Loading
Sources
[1] Haskell-Tutorial: Learn you a Haskell (http://learnyouahaskell.com/,
    2012/03/15)
[2] The Hugs User-Manual (
    http://cvs.haskell.org/Hugs/pages/hugsman/index.html, 2012/03/15)
[3] The Haskellwiki (http://www.haskell.org/haskellwiki, 2012/03/15)

Weitere ähnliche Inhalte

Was ist angesagt?

Simple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graphSimple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graph
Miguel Pereira
 
Pertemuan 2-pemecahan-masalah-ai
Pertemuan 2-pemecahan-masalah-aiPertemuan 2-pemecahan-masalah-ai
Pertemuan 2-pemecahan-masalah-ai
willyhayon
 

Was ist angesagt? (20)

5 penjadwalan aplod
5 penjadwalan aplod5 penjadwalan aplod
5 penjadwalan aplod
 
Bağli li̇steler (Linked List) – Yiğinlar (Stack) - Kuyruklar Konu Anlatımı
Bağli li̇steler (Linked List) – Yiğinlar (Stack) - Kuyruklar Konu Anlatımı Bağli li̇steler (Linked List) – Yiğinlar (Stack) - Kuyruklar Konu Anlatımı
Bağli li̇steler (Linked List) – Yiğinlar (Stack) - Kuyruklar Konu Anlatımı
 
0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM0-1 KNAPSACK PROBLEM
0-1 KNAPSACK PROBLEM
 
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycleBacktracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
Backtracking-N Queens Problem-Graph Coloring-Hamiltonian cycle
 
Greedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.pptGreedy Algorithms WITH Activity Selection Problem.ppt
Greedy Algorithms WITH Activity Selection Problem.ppt
 
Theory of Automata and formal languages unit 1
Theory of Automata and formal languages unit 1Theory of Automata and formal languages unit 1
Theory of Automata and formal languages unit 1
 
Algoritma dan Struktur Data - Sequential Search
Algoritma dan Struktur Data - Sequential SearchAlgoritma dan Struktur Data - Sequential Search
Algoritma dan Struktur Data - Sequential Search
 
Pertemuan 1 Sistem DataBase
Pertemuan 1 Sistem DataBasePertemuan 1 Sistem DataBase
Pertemuan 1 Sistem DataBase
 
Closure properties of context free grammar
Closure properties of context free grammarClosure properties of context free grammar
Closure properties of context free grammar
 
Knapsack Problem (DP & GREEDY)
Knapsack Problem (DP & GREEDY)Knapsack Problem (DP & GREEDY)
Knapsack Problem (DP & GREEDY)
 
Simple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graphSimple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graph
 
Coding using jscript test complete
Coding using jscript test completeCoding using jscript test complete
Coding using jscript test complete
 
Introduction To Autumata Theory
 Introduction To Autumata Theory Introduction To Autumata Theory
Introduction To Autumata Theory
 
Optimal Binary Search tree ppt seminar.pptx
Optimal Binary Search tree ppt seminar.pptxOptimal Binary Search tree ppt seminar.pptx
Optimal Binary Search tree ppt seminar.pptx
 
Struktur Data Tree
Struktur Data TreeStruktur Data Tree
Struktur Data Tree
 
Recursion
RecursionRecursion
Recursion
 
Heap sort
Heap sort Heap sort
Heap sort
 
Algoritma greedy
Algoritma greedyAlgoritma greedy
Algoritma greedy
 
Pertemuan 2-pemecahan-masalah-ai
Pertemuan 2-pemecahan-masalah-aiPertemuan 2-pemecahan-masalah-ai
Pertemuan 2-pemecahan-masalah-ai
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
 

Ähnlich wie 03. haskell refresher quiz

High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 

Ähnlich wie 03. haskell refresher quiz (20)

04. haskell handling
04. haskell handling04. haskell handling
04. haskell handling
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
02. haskell motivation
02. haskell motivation02. haskell motivation
02. haskell motivation
 
bobok
bobokbobok
bobok
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Practical cats
Practical catsPractical cats
Practical cats
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Beyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheckBeyond xUnit example-based testing: property-based testing with ScalaCheck
Beyond xUnit example-based testing: property-based testing with ScalaCheck
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Functional programming with_scala
Functional programming with_scalaFunctional programming with_scala
Functional programming with_scala
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 

03. haskell refresher quiz

  • 1. Refresher Sebastian Rettig “Work on Haskell began in 1987 when aa committee of “Work on Haskell began in 1987 when committee of researchers got together to design aa kick-asslanguage.” ([1]) researchers got together to design kick-ass language.” ([1])
  • 2. Imperative Programming ● Variables (value placeholder) – Value can change during program flow ● Modules, Classes, Functions, Procedures ● Control Flow Structures (IF THEN ELSE, Loops (WHILE), Goto)
  • 3. Functional Programming ● No Variables ● Functions only, eventually stored in Modules – Behavior do not change, once defined – → Function called with same parameter calculates always the same result ● Function definitions (Match Cases) ● Recursion
  • 4. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a) => [a] -> a maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 5. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a) => [a] -> a Function maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 6. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a) => [a] -> a maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 7. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a) => [a] -> a Function Header maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 8. Haskell Refresher Quiz ● What's the red one ? maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 9. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int ● maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x Function Body | otherwise = maxTail where maxTail = maxList xs
  • 10. Haskell Functions ● function contains header and body ● header consists of type definition: <funcname> :: <param> [ -> <param_n>] -> <result> ● body consists of pattern rules and calculation <funcname> <paramalias_1> [<paramalias_n>] = {calc} ● Example (2 params if type [Int] & Int, result Bool): isHead :: [Int] -> Int -> Bool isHead xs i = i==head xs
  • 11. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 12. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int Type maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 13. Types in Haskell (1) Starts with uppercase first character ● Int bounded from -2147483648 to 2147483647 ● Integer unbounded (for big numbers) but slower than Int ● Float floating point (single precision) ● Double floating point (double precision) ● Bool boolean ● Char character ● String list of Char (String == [Char])
  • 14. Types in Haskell (2) ● Lists: must be homogenous (entries from the same type) – [] empty List – [Int] List of Int – But e.g. [Int, Bool] not allowed (not homogenous)! ● Tuples: can contain different types BUT have fixed length – () empty tuple (has only 1 value) – (Int, Bool) tuple of a pair Int, Bool – (Int, Bool, Bool) tuple of Int, Bool, Bool
  • 15. Lists & List Comprehension ● Example: double entries in list doubleList [] = [] doubleList (x:xs) = x:x:doubleList xs – e.g. [1,2,3] → x=1; xs=[2,3] ● Multiplication of a list of values: Hugs> product [1..5] 120 ● or in a function: fac n = product [1..n]
  • 16. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 17. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = maxList [x] = x error “empty” Pattern maxList (x:xs) Matching | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 18. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 19. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail Guards where maxTail = maxList xs
  • 20. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 21. Haskell Refresher Quiz ● What's the red one ? ● maxList :: [Int] -> Int maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail Additional where maxTail = maxList xs 'where' clause
  • 22. Pattern Matching (1) ● create matching rules: fac 0 = 1 fac n = n * fac (n-1) ● use wildcards to ignore parameters in pattern: take 0 _ = [] take _ [] = [] take n (x:xs) = [x] ++ take (n-1) xs
  • 23. Pattern Matching (2) ● use Guards to separate a matching case deeper: myFilter _ [] = [] myFilter f (x:xs) | f==x = x:myFilter g xs | otherwise = myFilter f xs where g = 2*f – like an IF THEN ELSE – Guard Condition evaluate to Bool (True/False) ● eventually define values with where-clause myFilter 2 [1,2,3,4,5,6] results to [2,4]
  • 24. Recursion ● Recursion vs. Final Recursion: countX :: Int -> [Int] -> Int ● Hugs> countX 3 [1,4,3,5,3] countX x [] = 0 2 countX x (y:ys) | x==y = 1 + countX x ys | otherwise = countX x ys countXFinal :: Int -> [Int] -> Int -> Int countXFinal x [] accu = accu countXFinal x (y:ys) accu | x==y = countXFinal x ys accu+1 | otherwise = countXFinal x ys accu ● use accumulator to reduce stack usage ● Hugs> countXFinal 3 [1,4,3,5,3] 0 2
  • 25. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a) => [a] -> a maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 26. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a) => [a] -> a Typeclass maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 27. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a ) => [a] -> a maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 28. Haskell Refresher Quiz ● What's the red one ? ● maxList :: (Ord a ) => [a] -> a Type variable maxList [] = error “empty” maxList [x] = x maxList (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maxList xs
  • 29. Type Polymorphism (1) ● Statically typed, but Compiler can read type from context (type inference) ● → no need to set type explicitly ● → makes function more generic for different kinds of types (type polymorphism) – Why should I use quicksort :: [Int] -> [Int] – even if I also want to sort character? Hugs> quicksort ['f','a','d','b'] "abdf"
  • 30. Type Polymorphism (2) ● the header of our previous implementations could be fact :: Int -> Int maxList :: [Int] -> Int ● but is only limited to Int, but maxList could also handle Char ● → why not make it generic? maxList :: [a] -> a ● but what happens, if the corresponding Type is not comparable or cannot be ordered?
  • 31. Type Polymorphism (3) ● Solution: use Typeclasses maxList :: (Ord a) => [a] -> a ● then we can be sure to use (<,<=, ==, /=, >=, >) ● function header can contain multiple typeclasses maxList :: (Ord a, Eq b) => [a] -> [b] -> a ● In Haskell-Interpreter: to list the function header :t <function_name>
  • 32. Typeclasses (1) ● define properties of the types ● like an interface ● Typeclasses: – Eq can be compared – Ord can be ordered (>, <, >=, <=) (extending Eq) – Show can be shown as string – Read opposite of Show – Enum sequentially ordered types (can be enumerated and usable in List-Ranges ['a'..'e'])
  • 33. Typeclasses (2) ● Typeclasses: – Bounded upper/lower bound (minBound, maxBound) – Num types behave like numbers (must already be Show, Eq) – Integral contains only integrals (subclass of Num) – Floating corresponding real numbers (subclass of Num) ● if all Types of tuple are in same Typeclass → Tuple also in Typeclass
  • 34. Haskell Refresher Quiz ● Which will terminate? (1) head [1..] (2) last [1..] (3) tail [1,2,3,4,5,6] (4) init (take 5 (cycle [1..]))
  • 35. Haskell Refresher Quiz ● Which will terminate? (1) head [1..] (2) last [1..] (3) tail [1,2,3,4,5,6] (4) init (take 5 (cycle [1..])) ● (1), (3) and (4) because of Lazy Evaluation
  • 36. Lazy Evaluation ● Function execution only if result is needed ● → Program = series of data-transformations ● Example: A(B(C(x))) – If A needs result from B → call B – If B needs result from C → call C
  • 37. Haskell Refresher Quiz ● Which one is faster? (1) head (take 5 [1,2,3,4,5,6]) (2) head (take 5 [1..10]) (3) head (take 5 [1..]) (4) head (take 5 (cycle [1..10]))
  • 38. Haskell Refresher Quiz ● Which one is faster? (1) head (take 5 [1,2,3,4,5,6]) (2) head (take 5 [1..10]) (3) head (take 5 [1..]) (4) head (take 5 (cycle [1..10])) ● Everyone is equal because of Lazy Loading
  • 39. Sources [1] Haskell-Tutorial: Learn you a Haskell (http://learnyouahaskell.com/, 2012/03/15) [2] The Hugs User-Manual ( http://cvs.haskell.org/Hugs/pages/hugsman/index.html, 2012/03/15) [3] The Haskellwiki (http://www.haskell.org/haskellwiki, 2012/03/15)