SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
Handling

                 Sebastian Rettig

“Recursion is important to Haskell because unlike imperative
 “Recursion is important to Haskell because unlike imperative
languages, you do computations in Haskell by declaring
 languages, you do computations in Haskell by declaring
what something is instead of declaring how you get it.” ([1])
 what something is instead of declaring how you get it.” ([1])
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 (Memory)
Haskell Features
●   Pure Functional Programming Language
●   Lazy Evaluation
●   Pattern Matching and Guards
●   List Comprehension
●   Type Polymorphism
How to write Functions?
●   eventually think about imperative function
●   and translate into recursive function
●   → generally the same schema to go for:
       –   1. define simple cases (recursion anchor)
       –   2. define the recursion call
●   lets start with imperative functions
How to implement the Factorial?
●   Remember:
    “Recursion is important to Haskell because unlike imperative
      languages, you do computations in Haskell by declaring what
      something is instead of declaring how you get it.” ([1])
●   Okay, then look at the definition:
         –   Imperative definition


         –   Recursive definition
Let's look at the imperative way...
●   Imperative                    ●   Recursive
    function factorial(n) {
      int result = 1;
      if (n == 0)
        return result;
      }
      for (int i=1; i<n; i++) {
        result *= i;
      }
      return result;
    }
…and translate to the functional way
●   Imperative                    ●   Recursive
    function fact(n) {                fact 0 = 1
      int result = 1;                 fact n = n * fact (n-1)
      if (n == 0)                 ●   and in comparison with the definition:
        return result;
      }
      for (int i=1; i<n; i++) {
        result *= i;
      }                           ●   BUT imperative also possible:
      return result;
                                      fact' 0 = 1
    }
                                      fact' n = product [1..n]
                                  ●   compared with the definition:
Recursion (1)
●   we have no loops → use Recursion:
    myMap :: Int -> [Int] -> [Int]
    myMap v [] = []   --    Recursion Anchor!
    myMap v (x:xs) = [v*x] ++ myMap v xs
●   Recursion Anchor contains the break rule
       –   endless loop = anchorless recursion
           isTrue :: Bool    Bool
           isTrue b = b && isTrue b
Recursion (2)
●   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
Where & let .. in
●   additional definitions
●   let .. in defines scope of usage
       –   let = definition
       –   in = scope of definition
       –   e.g.: add   x = let a=9 in a + x
●   where has scope in whole function
       –   e.g.: add x = a + x
                    where a=9
The maximum value of a List?
●   Remember:
    “Recursion is important to Haskell because unlike imperative
      languages, you do computations in Haskell by declaring what
      something is instead of declaring how you get it.” ([1])
●   Okay, then look at the definition:
Let's look at the imperative way...
●   Imperative                        ●   Recursive
    function max(array list) {
      if (empty(list)) {
        throw new Exception();
      }
      max = list[0]
      for (int i=0; i<length(list);
       i++) {
        if (list[i] > max) {
          max = list[i];
        }
      }
      return max;
    }
…and translate to the functional way
●   Imperative                        ●   Recursive
    function max(array list) {            maxList [] = error “empty”
      if (empty(list)) {                  maxList [x] = x
        throw new Exception();            maxList (x:xs)
      }                                     | x > maxTail = x
      max = list[0]                         | otherwise = maxTail
      for (int i=0; i<length(list);         where maxTail = maxList xs
       i++) {
        if (list[i] > max) {
                                      ●   or simpler:
          max = list[i];                  maxList [] = error “empty”
        }                                 maxList [x] = x
      }                                   maxList (x:xs) =
      return max;                              max x (maxList xs)
    }                                 ●   and in comparison with the
                                            definition:
Final Recursion
●   Get maximum element of list in final recursion
    maxFinal :: [Int] -> Int -> Int
    maxFinal [] accu = accu
    maxFinal (x:xs) accu
           | x > accu = maxFinal xs x
           | otherwise = maxFinal xs accu

●   often the same Schema to program
●   → there exist functions in haskell to simplify the
     all day work :)
Simple Recursion Helper
●   map
●   foldl, foldr, foldl1, foldr1
●   scanl, scanr, scanl1, scanr1
●   etc...
Lambda Functions
●   often called as Inline Functions in other
      languages
●   Syntax:
       –   <param> <param> → <operation>
       –   e.g.:
                       a b -> a+b
       –   map (x -> x+3) [2,3,4]
                   ●   returns [5,6,7]
Folding, Scanning (1)
●   e.g.: How to get the max of an array?
       –   imperative:
           int max = 0;
           foreach (entry in list) {
                  max = (entry > max) ? entry : max;
           }

       –   functional:
           let list = [8,6,4,1,7,3,5]
           foldl (acc x -> if x > acc then x else acc) 0 list
Folding, Scanning (2)
●   scan shows the accumulator state on
      every recursion step:
           scanl (acc x -> if x > acc then x else acc) 0 list

       –   returns:
           [0,8,8,8,8,8,8,8]

       –   good for debugging
       –   good to understand recursion
Folding, Scanning (3)
●   foldl versus foldr:
       –   first we look at the Header of the functions:
           Prelude> :t foldl
           foldl :: (a -> b -> a) -> a -> [b] -> a
           Prelude> :t foldr
           foldr :: (a -> b -> b) -> b -> [a] -> b

       –   What is the difference?
Folding, Scanning (4)
●   foldl versus foldr:
       –   first we look at the Header of the functions:
           Prelude> :t foldl
           foldl :: (a -> b -> a) -> a -> [b] -> a
           Prelude> :t foldr
           foldr :: (a -> b -> b) -> b -> [a] -> b

       –   What is the difference?
                ●   accumulator and parameter are
                     switched!!!
Infix, Prefix, Postfix
●   Infix (usable in Haskell):
       –   2 + 3
       –   2 `mod` 3
●   Prefix (usable in Haskell):
       –   (+) 2 3
       –   mod 2 3
●   Postfix (used in stack machines):
       –   32+
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)

Mais conteúdo relacionado

Mais procurados

Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!priort
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsKirill Kozlov
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a categorysamthemonad
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
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...Philip Schwarz
 
03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quizSebastian Rettig
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)stasimus
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional ProgrammingLuka Jacobowitz
 
The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189Mahmoud Samir Fayed
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In ScalaKnoldus Inc.
 

Mais procurados (19)

Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!Beginning Haskell, Dive In, Its Not That Scary!
Beginning Haskell, Dive In, Its Not That Scary!
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Monad presentation scala as a category
Monad presentation   scala as a categoryMonad presentation   scala as a category
Monad presentation scala as a category
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
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...
 
03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
V8
V8V8
V8
 
Python GC
Python GCPython GC
Python GC
 
Testing in the World of Functional Programming
Testing in the World of Functional ProgrammingTesting in the World of Functional Programming
Testing in the World of Functional Programming
 
The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189The Ring programming language version 1.6 book - Part 35 of 189
The Ring programming language version 1.6 book - Part 35 of 189
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 

Semelhante a 04. haskell handling

Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
Multinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkDB Tsai
 
Alpine Spark Implementation - Technical
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technicalalpinedatalabs
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programmingchriseidhof
 
III_Data Structure_Module_1.ppt
III_Data Structure_Module_1.pptIII_Data Structure_Module_1.ppt
III_Data Structure_Module_1.pptshashankbhadouria4
 
III_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxIII_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxshashankbhadouria4
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursionDavid Atchley
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programmingkenbot
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using HaskellFunctional Thursday
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and FuturePushkar Kulkarni
 

Semelhante a 04. haskell handling (20)

A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Chapter7
Chapter7Chapter7
Chapter7
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
iPython
iPythoniPython
iPython
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Multinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache SparkMultinomial Logistic Regression with Apache Spark
Multinomial Logistic Regression with Apache Spark
 
Alpine Spark Implementation - Technical
Alpine Spark Implementation - TechnicalAlpine Spark Implementation - Technical
Alpine Spark Implementation - Technical
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Scheme 核心概念(一)
Scheme 核心概念(一)Scheme 核心概念(一)
Scheme 核心概念(一)
 
III_Data Structure_Module_1.ppt
III_Data Structure_Module_1.pptIII_Data Structure_Module_1.ppt
III_Data Structure_Module_1.ppt
 
III_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptxIII_Data Structure_Module_1.pptx
III_Data Structure_Module_1.pptx
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Good functional programming is good programming
Good functional programming is good programmingGood functional programming is good programming
Good functional programming is good programming
 
Practical cats
Practical catsPractical cats
Practical cats
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell
 
Functional Programming - Past, Present and Future
Functional Programming - Past, Present and FutureFunctional Programming - Past, Present and Future
Functional Programming - Past, Present and Future
 

04. haskell handling

  • 1. Handling Sebastian Rettig “Recursion is important to Haskell because unlike imperative “Recursion is important to Haskell because unlike imperative languages, you do computations in Haskell by declaring languages, you do computations in Haskell by declaring what something is instead of declaring how you get it.” ([1]) what something is instead of declaring how you get it.” ([1])
  • 2. 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 (Memory)
  • 3. Haskell Features ● Pure Functional Programming Language ● Lazy Evaluation ● Pattern Matching and Guards ● List Comprehension ● Type Polymorphism
  • 4. How to write Functions? ● eventually think about imperative function ● and translate into recursive function ● → generally the same schema to go for: – 1. define simple cases (recursion anchor) – 2. define the recursion call ● lets start with imperative functions
  • 5. How to implement the Factorial? ● Remember: “Recursion is important to Haskell because unlike imperative languages, you do computations in Haskell by declaring what something is instead of declaring how you get it.” ([1]) ● Okay, then look at the definition: – Imperative definition – Recursive definition
  • 6. Let's look at the imperative way... ● Imperative ● Recursive function factorial(n) { int result = 1; if (n == 0) return result; } for (int i=1; i<n; i++) { result *= i; } return result; }
  • 7. …and translate to the functional way ● Imperative ● Recursive function fact(n) { fact 0 = 1 int result = 1; fact n = n * fact (n-1) if (n == 0) ● and in comparison with the definition: return result; } for (int i=1; i<n; i++) { result *= i; } ● BUT imperative also possible: return result; fact' 0 = 1 } fact' n = product [1..n] ● compared with the definition:
  • 8. Recursion (1) ● we have no loops → use Recursion: myMap :: Int -> [Int] -> [Int] myMap v [] = [] -- Recursion Anchor! myMap v (x:xs) = [v*x] ++ myMap v xs ● Recursion Anchor contains the break rule – endless loop = anchorless recursion isTrue :: Bool Bool isTrue b = b && isTrue b
  • 9. Recursion (2) ● 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
  • 10. Where & let .. in ● additional definitions ● let .. in defines scope of usage – let = definition – in = scope of definition – e.g.: add x = let a=9 in a + x ● where has scope in whole function – e.g.: add x = a + x where a=9
  • 11. The maximum value of a List? ● Remember: “Recursion is important to Haskell because unlike imperative languages, you do computations in Haskell by declaring what something is instead of declaring how you get it.” ([1]) ● Okay, then look at the definition:
  • 12. Let's look at the imperative way... ● Imperative ● Recursive function max(array list) { if (empty(list)) { throw new Exception(); } max = list[0] for (int i=0; i<length(list); i++) { if (list[i] > max) { max = list[i]; } } return max; }
  • 13. …and translate to the functional way ● Imperative ● Recursive function max(array list) { maxList [] = error “empty” if (empty(list)) { maxList [x] = x throw new Exception(); maxList (x:xs) } | x > maxTail = x max = list[0] | otherwise = maxTail for (int i=0; i<length(list); where maxTail = maxList xs i++) { if (list[i] > max) { ● or simpler: max = list[i]; maxList [] = error “empty” } maxList [x] = x } maxList (x:xs) = return max; max x (maxList xs) } ● and in comparison with the definition:
  • 14. Final Recursion ● Get maximum element of list in final recursion maxFinal :: [Int] -> Int -> Int maxFinal [] accu = accu maxFinal (x:xs) accu | x > accu = maxFinal xs x | otherwise = maxFinal xs accu ● often the same Schema to program ● → there exist functions in haskell to simplify the all day work :)
  • 15. Simple Recursion Helper ● map ● foldl, foldr, foldl1, foldr1 ● scanl, scanr, scanl1, scanr1 ● etc...
  • 16. Lambda Functions ● often called as Inline Functions in other languages ● Syntax: – <param> <param> → <operation> – e.g.: a b -> a+b – map (x -> x+3) [2,3,4] ● returns [5,6,7]
  • 17. Folding, Scanning (1) ● e.g.: How to get the max of an array? – imperative: int max = 0; foreach (entry in list) { max = (entry > max) ? entry : max; } – functional: let list = [8,6,4,1,7,3,5] foldl (acc x -> if x > acc then x else acc) 0 list
  • 18. Folding, Scanning (2) ● scan shows the accumulator state on every recursion step: scanl (acc x -> if x > acc then x else acc) 0 list – returns: [0,8,8,8,8,8,8,8] – good for debugging – good to understand recursion
  • 19. Folding, Scanning (3) ● foldl versus foldr: – first we look at the Header of the functions: Prelude> :t foldl foldl :: (a -> b -> a) -> a -> [b] -> a Prelude> :t foldr foldr :: (a -> b -> b) -> b -> [a] -> b – What is the difference?
  • 20. Folding, Scanning (4) ● foldl versus foldr: – first we look at the Header of the functions: Prelude> :t foldl foldl :: (a -> b -> a) -> a -> [b] -> a Prelude> :t foldr foldr :: (a -> b -> b) -> b -> [a] -> b – What is the difference? ● accumulator and parameter are switched!!!
  • 21. Infix, Prefix, Postfix ● Infix (usable in Haskell): – 2 + 3 – 2 `mod` 3 ● Prefix (usable in Haskell): – (+) 2 3 – mod 2 3 ● Postfix (used in stack machines): – 32+
  • 22. 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)