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

         Sebastian Rettig


Every function in haskell consumes exactly
 Every function in haskell consumes exactly
    one parameter and returns aa value.
     one parameter and returns value.
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
Nice to remember (1)
    Typeclasses:
●   define properties of the types
●   like an interface
         –   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'])
Nice to remember (2)
  Typeclass-Membership:
1. derive from existing Memberships of used types
  data Vector2D = Vector Float Float deriving (Show, Eq)

2. implement Membership by your own
  instance Show Vector2D where
    show Vector a b = “x: ” ++ [a] ++ “ ; y: ” ++ [b]
Curried Functions (1)
●   let's look at the Function header again, e.g:
    max :: (Ord a) => a -> a -> a
        1. we have a Typeclass restriction for Ord
        2. we have 2 Parameters of Types, who have a
            membership for the Ord Typeclass
        3. we have a return value of the same type
●   But, why is the syntax not separating the parameters
      better from the result set?
Curried Functions (2)
●   every function in haskell consumes exactly one
      parameter and returns a value
●   so we could write the function header instead of:
    max :: (Ord a) => a -> a -> a
●   also in the following way:
    max :: (Ord a) => a -> (a -> a)
        –   max is a function which consumes a parameter and
              returns a function
        –   these function consumes a parameter and returns a
              value (the max of both values)
●
    → Partial Application
Curried Functions (3)
●   some examples:
       –   :t max returns
                  max :: (Ord a) => a -> a -> a
       –   max 4 5 returns 5
       –   (max 4) 5 returns 5
       –   :t max 4 returns
                 max 4 :: (Num a, Ord a) => a -> a
       –   let foo = max 4
                  foo 5 returns 5
       –   :t max 4 5 returns
                  max 4 5 :: (Num a, Ord a) => a
Curried Functions (4)
●   we can also partial apply infix functions
    (/10) 2   returns    0.2
    (10/) 2   returns    5
    (++ “bar”) “foo”           returns “foobar”
    (“bar” ++) “foo”           returns “barfoo”
    :t (`elem` ['a'..'z'])
      (`elem` ['a'..'z']) :: Char -> Bool
    :t ('a' `elem`)
      (`elem` ['a'..'z']) :: [Char] -> Bool
    :t elem
      elem :: Eq a => a -> [a] -> Bool
Pointless Style
●   let's say, we have the following function:
    maxWithFour :: (Num a, Ord a) => a -> a
    maxWithFour x = max 4 x
●   what is the result of max 4 again?
    :t max 4 returns max 4 :: (Num a, Ord a) => a -> a
●   max 4 returns already a function which consumes a
      parameter, so we can simplify our function:
    maxWithFour :: (Num a, Ord a) => a -> a
    maxWithFour = max 4
●   but how can we achieve that with the following function?
    fn x = ceiling (negate (tan (cos (max 50 x))))
Function Application (1)
●   used with ($)
●   has the following header:
    :t ($)
      ($) :: (a -> b) -> a -> b
●   compared with SPACE (normal function application)
        –   ($) has lowest priority
        –   ($) is right associative   f $ g $ a b   = (f (g (a b)))
        –   SPACE has highest priority
        –   SPACE is left associative     f a b c    = (((f a) b) c)
Function Application (2)
●   what can we do with ($) ?
●   helps us to avoid parentheses:
        –   instead of:
              sum (map sqrt [1..20])
        –   we can write:
              sum $ map sqrt [1..20]
●   allows us also to wrap a value in a function:
    map ($ 3) [(4+), (10*), (^2), sqrt]
      returns
       [7.0,30.0,9.0,1.7320508075688772]
Function Composition (1)
●   Definition:
●   used with (.)
●   has the following header:
    :t (.)
      (.) :: (b -> c) -> (a -> b) -> a -> c
●   composing two functions produces a new function
●   good for on-the-fly pass of a function to the next
      function
Function Composition (2)
●   what can we do with (.) ?
●   helps us also to avoid parentheses
●   → unwraps the parameter out of parentheses
        –   instead of:
            map (xs -> negate (sum (tail xs))) [[1..5],
              [3..6],[1..7]]
        –   we can write:
            map (negate . sum . tail) [[1..5],[3..6],
              [1..7]]
Composition vs. Application (1)
●   IMPORTANT to know the difference between ($) and (.)
●   best to compare both headers again:
        –   ($) :: (a -> b) -> a -> b
        –   (.) :: (b -> c) -> (a -> b) -> a -> c
●   combination of both allows us parenthesis-less writing
●   shorter code and mostly easier to read
●   → possibility to write pointless-style functions with more
     then one function call
Composition vs. Application (2)
●   example with parameter:
        –   foo xs = sum (filter (> 10) (map (*2) xs))
        –   foo xs = sum $ filter (> 10) $ map (*2 ) xs
●   example without parameter (pointless-style):
        –   foo xs = sum (filter (> 10) (map (*2) xs))
        –   foo = sum . filter (> 10) . map (*2)
Useful Types
●   Maybe:
    data Maybe a = Nothing | Just a
        –     contains maybe a type a or Nothing
        –     good for handling e.g. Hashmap lookup
                   ●   Nothing if key not exist, else Value of type a
●   Either:
    data Either a b = Left a | Right b
      deriving (Eq, Ord, Read, Show)
        –     can contain type a or type b
        –     Left for e.g. Error Messages, Right for value
        –     like an extended Maybe with information for Nothing
Functor Typeclass (1)
    class Functor f where
      fmap :: (a -> b) -> f a -> f b
●   for things that can be mapped over
●   !!! Functor needs Types with 1 Typeparameter !!!
●   fmap gets a function and a type and maps the function over
      the type variable
●   Instance for List:
         –   Remember: List has 1 Typeparameter [a], but is just
               Syntactic Sugar for ([] a)
    instance Functor [] where
      fmap = map
         –   Example: fmap (*2) [2,3,4] returns [4,6,8]
Functor Typeclass (2)
    class Functor f where
      fmap :: (a -> b) -> f a -> f b
●   Instance for Maybe
    instance Functor Maybe where
      fmap g (Just x) = Just (g x)
      fmap g Nothing = Nothing
●   Example:
        –   fmap (+3) Nothing returns Nothing
        –   fmap (+3) (Just 4) returns (Just 7)
Functor Typeclass (3)
    class Functor f where
      fmap :: (a -> b) -> f a -> f b
●   Instance for Either
    instance Functor (Either a) where
      fmap f (Right x) = Right (f x)
      fmap f (Left x) = Left x
●   Either is a type with 2 Typeparameters!
●   → we have to permanently include the first parameter in the
      instance (curried function, partial application)
●   → fmap do not change the 1st Typeparameter, only the 2nd
●   → Left Type-Constructor of Either is often used for Error
      Messages
Functor Typeclass (4)
    class Functor f where
      fmap :: (a -> b) -> f a -> f b
●   Example:
         –   fmap (+3) (Left 4) returns (Left 4)
         –   fmap (+3) (Right 4) returns (Right 7)
●   what happens, if we try to do that?
      fmap (+) (Just 4)
●   let's look at the type:
                        :t fmap (+) (Just 4)
      fmap (+) (Just 4) :: Num a => Maybe (a -> a)
●   partial application, BUT we can not use the Functor instance
      on the result!
●   → we need an extension → Applicative Functors
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

Linear Types in Haskell
Linear Types in HaskellLinear Types in Haskell
Linear Types in HaskellDavid Overton
 
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
 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2Hang Zhao
 
Extensible Effects in Dotty
Extensible Effects in DottyExtensible Effects in Dotty
Extensible Effects in DottySanshiro Yoshida
 
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
 
Constraint Programming in Haskell
Constraint Programming in HaskellConstraint Programming in Haskell
Constraint Programming in HaskellDavid Overton
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskellLuca Molteni
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsPhilip Schwarz
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Philip Schwarz
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Philip Schwarz
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskellfaradjpour
 
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
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1Philip Schwarz
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monadsrkaippully
 

What's hot (19)

Linear Types in Haskell
Linear Types in HaskellLinear Types in Haskell
Linear Types in Haskell
 
Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
Fp in scala with adts part 2
Fp in scala with adts part 2Fp in scala with adts part 2
Fp in scala with adts part 2
 
Comonads in Haskell
Comonads in HaskellComonads in Haskell
Comonads in Haskell
 
Extensible Effects in Dotty
Extensible Effects in DottyExtensible Effects in Dotty
Extensible Effects in Dotty
 
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!
 
Constraint Programming in Haskell
Constraint Programming in HaskellConstraint Programming in Haskell
Constraint Programming in Haskell
 
Introduction to haskell
Introduction to haskellIntroduction to haskell
Introduction to haskell
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'Simple IO Monad in 'Functional Programming in Scala'
Simple IO Monad in 'Functional Programming in Scala'
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Functor Composition
Functor CompositionFunctor Composition
Functor Composition
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
 
Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)Introduction to Monads in Scala (1)
Introduction to Monads in Scala (1)
 
Monad Transformers - Part 1
Monad Transformers - Part 1Monad Transformers - Part 1
Monad Transformers - Part 1
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 

Viewers also liked

Viewers also liked (6)

06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
04. haskell handling
04. haskell handling04. haskell handling
04. haskell handling
 
03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
 
02. haskell motivation
02. haskell motivation02. haskell motivation
02. haskell motivation
 

Similar to 08. haskell Functions

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 from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentalsMauro Palsgraaf
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2Hang Zhao
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesWim Vanderbauwhede
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabMohan Raj
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursionDavid Atchley
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programmingVisnuDharsini
 
Monadic Computations in C++14
Monadic Computations in C++14Monadic Computations in C++14
Monadic Computations in C++14Ovidiu Farauanu
 
Functions and graphs
Functions and graphsFunctions and graphs
Functions and graphsSujata Tapare
 

Similar to 08. haskell Functions (20)

07. haskell Membership
07. haskell Membership07. haskell Membership
07. haskell Membership
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Practical cats
Practical catsPractical cats
Practical cats
 
Functional programming from its fundamentals
Functional programming from its fundamentalsFunctional programming from its fundamentals
Functional programming from its fundamentals
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Fp in scala part 2
Fp in scala part 2Fp in scala part 2
Fp in scala part 2
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Java 8
Java 8Java 8
Java 8
 
List-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic LanguagesList-based Monadic Computations for Dynamic Languages
List-based Monadic Computations for Dynamic Languages
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
Mbd2
Mbd2Mbd2
Mbd2
 
Monadic Computations in C++14
Monadic Computations in C++14Monadic Computations in C++14
Monadic Computations in C++14
 
Functions and graphs
Functions and graphsFunctions and graphs
Functions and graphs
 

Recently uploaded

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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 DevelopmentsTrustArc
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Recently uploaded (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

08. haskell Functions

  • 1. Functions Sebastian Rettig Every function in haskell consumes exactly Every function in haskell consumes exactly one parameter and returns aa value. one parameter and returns value.
  • 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. Nice to remember (1) Typeclasses: ● define properties of the types ● like an interface – 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'])
  • 5. Nice to remember (2) Typeclass-Membership: 1. derive from existing Memberships of used types data Vector2D = Vector Float Float deriving (Show, Eq) 2. implement Membership by your own instance Show Vector2D where show Vector a b = “x: ” ++ [a] ++ “ ; y: ” ++ [b]
  • 6. Curried Functions (1) ● let's look at the Function header again, e.g: max :: (Ord a) => a -> a -> a 1. we have a Typeclass restriction for Ord 2. we have 2 Parameters of Types, who have a membership for the Ord Typeclass 3. we have a return value of the same type ● But, why is the syntax not separating the parameters better from the result set?
  • 7. Curried Functions (2) ● every function in haskell consumes exactly one parameter and returns a value ● so we could write the function header instead of: max :: (Ord a) => a -> a -> a ● also in the following way: max :: (Ord a) => a -> (a -> a) – max is a function which consumes a parameter and returns a function – these function consumes a parameter and returns a value (the max of both values) ● → Partial Application
  • 8. Curried Functions (3) ● some examples: – :t max returns max :: (Ord a) => a -> a -> a – max 4 5 returns 5 – (max 4) 5 returns 5 – :t max 4 returns max 4 :: (Num a, Ord a) => a -> a – let foo = max 4 foo 5 returns 5 – :t max 4 5 returns max 4 5 :: (Num a, Ord a) => a
  • 9. Curried Functions (4) ● we can also partial apply infix functions (/10) 2 returns 0.2 (10/) 2 returns 5 (++ “bar”) “foo” returns “foobar” (“bar” ++) “foo” returns “barfoo” :t (`elem` ['a'..'z']) (`elem` ['a'..'z']) :: Char -> Bool :t ('a' `elem`) (`elem` ['a'..'z']) :: [Char] -> Bool :t elem elem :: Eq a => a -> [a] -> Bool
  • 10. Pointless Style ● let's say, we have the following function: maxWithFour :: (Num a, Ord a) => a -> a maxWithFour x = max 4 x ● what is the result of max 4 again? :t max 4 returns max 4 :: (Num a, Ord a) => a -> a ● max 4 returns already a function which consumes a parameter, so we can simplify our function: maxWithFour :: (Num a, Ord a) => a -> a maxWithFour = max 4 ● but how can we achieve that with the following function? fn x = ceiling (negate (tan (cos (max 50 x))))
  • 11. Function Application (1) ● used with ($) ● has the following header: :t ($) ($) :: (a -> b) -> a -> b ● compared with SPACE (normal function application) – ($) has lowest priority – ($) is right associative f $ g $ a b = (f (g (a b))) – SPACE has highest priority – SPACE is left associative f a b c = (((f a) b) c)
  • 12. Function Application (2) ● what can we do with ($) ? ● helps us to avoid parentheses: – instead of: sum (map sqrt [1..20]) – we can write: sum $ map sqrt [1..20] ● allows us also to wrap a value in a function: map ($ 3) [(4+), (10*), (^2), sqrt] returns [7.0,30.0,9.0,1.7320508075688772]
  • 13. Function Composition (1) ● Definition: ● used with (.) ● has the following header: :t (.) (.) :: (b -> c) -> (a -> b) -> a -> c ● composing two functions produces a new function ● good for on-the-fly pass of a function to the next function
  • 14. Function Composition (2) ● what can we do with (.) ? ● helps us also to avoid parentheses ● → unwraps the parameter out of parentheses – instead of: map (xs -> negate (sum (tail xs))) [[1..5], [3..6],[1..7]] – we can write: map (negate . sum . tail) [[1..5],[3..6], [1..7]]
  • 15. Composition vs. Application (1) ● IMPORTANT to know the difference between ($) and (.) ● best to compare both headers again: – ($) :: (a -> b) -> a -> b – (.) :: (b -> c) -> (a -> b) -> a -> c ● combination of both allows us parenthesis-less writing ● shorter code and mostly easier to read ● → possibility to write pointless-style functions with more then one function call
  • 16. Composition vs. Application (2) ● example with parameter: – foo xs = sum (filter (> 10) (map (*2) xs)) – foo xs = sum $ filter (> 10) $ map (*2 ) xs ● example without parameter (pointless-style): – foo xs = sum (filter (> 10) (map (*2) xs)) – foo = sum . filter (> 10) . map (*2)
  • 17. Useful Types ● Maybe: data Maybe a = Nothing | Just a – contains maybe a type a or Nothing – good for handling e.g. Hashmap lookup ● Nothing if key not exist, else Value of type a ● Either: data Either a b = Left a | Right b deriving (Eq, Ord, Read, Show) – can contain type a or type b – Left for e.g. Error Messages, Right for value – like an extended Maybe with information for Nothing
  • 18. Functor Typeclass (1) class Functor f where fmap :: (a -> b) -> f a -> f b ● for things that can be mapped over ● !!! Functor needs Types with 1 Typeparameter !!! ● fmap gets a function and a type and maps the function over the type variable ● Instance for List: – Remember: List has 1 Typeparameter [a], but is just Syntactic Sugar for ([] a) instance Functor [] where fmap = map – Example: fmap (*2) [2,3,4] returns [4,6,8]
  • 19. Functor Typeclass (2) class Functor f where fmap :: (a -> b) -> f a -> f b ● Instance for Maybe instance Functor Maybe where fmap g (Just x) = Just (g x) fmap g Nothing = Nothing ● Example: – fmap (+3) Nothing returns Nothing – fmap (+3) (Just 4) returns (Just 7)
  • 20. Functor Typeclass (3) class Functor f where fmap :: (a -> b) -> f a -> f b ● Instance for Either instance Functor (Either a) where fmap f (Right x) = Right (f x) fmap f (Left x) = Left x ● Either is a type with 2 Typeparameters! ● → we have to permanently include the first parameter in the instance (curried function, partial application) ● → fmap do not change the 1st Typeparameter, only the 2nd ● → Left Type-Constructor of Either is often used for Error Messages
  • 21. Functor Typeclass (4) class Functor f where fmap :: (a -> b) -> f a -> f b ● Example: – fmap (+3) (Left 4) returns (Left 4) – fmap (+3) (Right 4) returns (Right 7) ● what happens, if we try to do that? fmap (+) (Just 4) ● let's look at the type: :t fmap (+) (Just 4) fmap (+) (Just 4) :: Num a => Maybe (a -> a) ● partial application, BUT we can not use the Functor instance on the result! ● → we need an extension → Applicative Functors
  • 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)