SlideShare a Scribd company logo
1 of 22
Download to read offline
Motivation

                 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
When you start...
●   You want to do big projects with Haskell?
●   Then start simple, because:
          –   a function is Simple and...


    Abstraction-             Simple
    Level
                        Simple    Simple
                                                      BIG
                   Simple    Simple    Simple        Project
              Simple    Simple    Simple    Simple
Let's start simple
●   You need a Framework to start with Haskell?
        –   then write one, if you really think you need one :)
        –   but be aware of
                  ●   Haskell == simple
                  ●   Framework == should also be simple
●   a simple function:
        –   just ignore the function header at the beginning
    countNum 1 = “One”
    countNum 2 = “Two”
    countNum x = “toooo difficult to count...”
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:
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:
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
List-Functions
●   head returns first element of list
         –   head [1,2,3] returns 1
●   tail returns list without first element
         –   tail [1,2,3] returns [2,3]
●   init returns list without last element
         –   init [1,2,3] returns [1,2]
●   last returns last element of list
         –   last [1,2,3] returns 3
Tuple-Functions
●   fst returns first element of a pair
             fst (1, “one”) returns 1

         –   only usable on Tuples of Pairs!!!
             fst (1,”one”,True) throws Exception!!!
●   snd returns second element of a pair
             snd (1, “one”) returns “one”

         –   only usable on Tuples of Pairs!!!
         –   snd (1,”one”,True) throws Exception!!!
●   zip creates a list of tuples from two lists
         –   zip [1,2,3] [“one”,“two”,”three”] returns [(1,“one”),
               (2,”two”),(3,”three”)]
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
Lazy Evaluation
●   What happens, if I do this? (Yes it makes no
     sense, but just for demonstration)
    max a b
      | a > b = a
      | otherwise = b
      where temp = cycle “LOL ”
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)

More Related Content

What's hot

Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Bryan O'Sullivan
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Bryan O'Sullivan
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Bryan O'Sullivan
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Bryan O'Sullivan
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Bryan O'Sullivan
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Bryan O'Sullivan
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of LambdasEsther Lozano
 
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
 

What's hot (20)

Real World Haskell: Lecture 2
Real World Haskell: Lecture 2Real World Haskell: Lecture 2
Real World Haskell: Lecture 2
 
Real World Haskell: Lecture 6
Real World Haskell: Lecture 6Real World Haskell: Lecture 6
Real World Haskell: Lecture 6
 
Real World Haskell: Lecture 3
Real World Haskell: Lecture 3Real World Haskell: Lecture 3
Real World Haskell: Lecture 3
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Real World Haskell: Lecture 7
Real World Haskell: Lecture 7Real World Haskell: Lecture 7
Real World Haskell: Lecture 7
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Python by ganesh kavhar
Python by ganesh kavharPython by ganesh kavhar
Python by ganesh kavhar
 
Why Haskell
Why HaskellWhy Haskell
Why Haskell
 
Real World Haskell: Lecture 5
Real World Haskell: Lecture 5Real World Haskell: Lecture 5
Real World Haskell: Lecture 5
 
Real World Haskell: Lecture 4
Real World Haskell: Lecture 4Real World Haskell: Lecture 4
Real World Haskell: Lecture 4
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
python
pythonpython
python
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
The... Wonderful? World of Lambdas
The... Wonderful? World of LambdasThe... Wonderful? World of Lambdas
The... Wonderful? World of Lambdas
 
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!
 

Similar to 02. haskell motivation

03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quizSebastian Rettig
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaAyush Mishra
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp languageDavid Gu
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture TwoAngelo Corsaro
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
Sort Characters in a Python String Alphabetically
Sort Characters in a Python String AlphabeticallySort Characters in a Python String Alphabetically
Sort Characters in a Python String AlphabeticallyKal Bartal
 
Introduction to Erlang Part 1
Introduction to Erlang Part 1Introduction to Erlang Part 1
Introduction to Erlang Part 1Dmitry Zinoviev
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in ScalaAyush Mishra
 
Intro To Erlang
Intro To ErlangIntro To Erlang
Intro To Erlangasceth
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospectivechenge2k
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 

Similar to 02. haskell motivation (20)

08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
A brief introduction to lisp language
A brief introduction to lisp languageA brief introduction to lisp language
A brief introduction to lisp language
 
07. haskell Membership
07. haskell Membership07. haskell Membership
07. haskell Membership
 
Programming in Scala - Lecture Two
Programming in Scala - Lecture TwoProgramming in Scala - Lecture Two
Programming in Scala - Lecture Two
 
Lisp
LispLisp
Lisp
 
Scala qq
Scala qqScala qq
Scala qq
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Sort Characters in a Python String Alphabetically
Sort Characters in a Python String AlphabeticallySort Characters in a Python String Alphabetically
Sort Characters in a Python String Alphabetically
 
Introduction to Erlang Part 1
Introduction to Erlang Part 1Introduction to Erlang Part 1
Introduction to Erlang Part 1
 
Elm kyivfprog 2015
Elm kyivfprog 2015Elm kyivfprog 2015
Elm kyivfprog 2015
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
Introducing Pattern Matching in Scala
 Introducing Pattern Matching  in Scala Introducing Pattern Matching  in Scala
Introducing Pattern Matching in Scala
 
Intro To Erlang
Intro To ErlangIntro To Erlang
Intro To Erlang
 
10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
Haskell retrospective
Haskell retrospectiveHaskell retrospective
Haskell retrospective
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Recently uploaded (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

02. haskell motivation

  • 1. Motivation 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. When you start... ● You want to do big projects with Haskell? ● Then start simple, because: – a function is Simple and... Abstraction- Simple Level Simple Simple BIG Simple Simple Simple Project Simple Simple Simple Simple
  • 5. Let's start simple ● You need a Framework to start with Haskell? – then write one, if you really think you need one :) – but be aware of ● Haskell == simple ● Framework == should also be simple ● a simple function: – just ignore the function header at the beginning countNum 1 = “One” countNum 2 = “Two” countNum x = “toooo difficult to count...”
  • 6. 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
  • 7. 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; }
  • 8. …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:
  • 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:
  • 10. 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; }
  • 11. …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:
  • 12. 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])
  • 13. 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
  • 14. List-Functions ● head returns first element of list – head [1,2,3] returns 1 ● tail returns list without first element – tail [1,2,3] returns [2,3] ● init returns list without last element – init [1,2,3] returns [1,2] ● last returns last element of list – last [1,2,3] returns 3
  • 15. Tuple-Functions ● fst returns first element of a pair fst (1, “one”) returns 1 – only usable on Tuples of Pairs!!! fst (1,”one”,True) throws Exception!!! ● snd returns second element of a pair snd (1, “one”) returns “one” – only usable on Tuples of Pairs!!! – snd (1,”one”,True) throws Exception!!! ● zip creates a list of tuples from two lists – zip [1,2,3] [“one”,“two”,”three”] returns [(1,“one”), (2,”two”),(3,”three”)]
  • 16. 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"
  • 17. 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?
  • 18. 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>
  • 19. 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'])
  • 20. 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
  • 21. Lazy Evaluation ● What happens, if I do this? (Yes it makes no sense, but just for demonstration) max a b | a > b = a | otherwise = b where temp = cycle “LOL ”
  • 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)