SlideShare a Scribd company logo
1 of 23
Download to read offline
Modules

              Sebastian Rettig


A Haskell module is aa collection of related functions,
 A Haskell module is collection of related functions,
              types and typeclasses.
               types and typeclasses.
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
●   Curried Functions
Nice to remember (1)
    Applicative Context:
         –   Maybe, Either for things which can fail
         –   [] as non-deterministic result
         –   IO as values send or get from outside
●   Applicative functors allows us to operate in applicative types
      like normal types and provide the context!
●   → We don't need to pattern match against the Context in
      every operation we use in our functions!
Nice to remember (2)
    Typeclasses:
●   define properties of the types
●   an interface for types who have some behavior in common:
         –   Eq can be compared
         –   Ord can be ordered (>, <, >=, <=) (extending Eq)
         –   Show can be shown as string
         –   Read opposite of Show
         –   Functor something that can be mapped over
         –   Applicative handle functions wrapped in a Functor
Nice to remember (3)
  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]
Nice to remember (4)
    Curried Function:
●   every function in haskell consumes exactly one
      parameter and returns a value
●   PARTIAL APPLICATION
●   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)
Nice to remember (5)
    Pointless Style:
●   based on partial Application → simpler code
           maxWithFour x = max 4 x
             is the same as
           maxWithFour = max 4
●   use Function Application ($) to avoid Parenthesis on
      function call with parameters
           sqrt $ 3 + 4 + 9
●   use Function Composition (.) to avoid Parenthesis on
      chaining functions
           fn = ceiling . negate . tan . cos . max 50
Nice to remember (6)
    Kind:
●   explains the steps which are necessary to evaluate the data
      from that type
●   → evaluate = the type is fully applied
●   can be used to find out the parameter-count of a type
●   GHCi- Command       :k
●   :k Int returns Int :: *
●   data MyVector4 a   b c = Nirvana4
                   |   Single4 {x'' :: a}
                   |   Tuple4 {x'' :: a, y :: b}
                   |   Triple4 {x'' :: a, y'' :: b, z'' :: c}
      :k MyVector4 returns MyVector4 :: * -> * -> * -> *
Nice to remember (7)
    DO-Notation:
      main :: IO ()
      main = do
        putStrLn “Say me your Name!”
        name <- getLine
        putStrLn $ “Hello” ++ name
●   do syntax glues IO actions together
●   bind operator <- get the data out of IO and bind result to a
       placeholder
●   :t getLine returns getLine :: IO String

         –   name has the type String
●   ! The last action in a do-block can not be bound !
Nice to remember (8)
    Fold & Scan:
●   foldl :: (a -> b -> a) -> a -> [b] -> a
●   foldr :: (a -> b -> b) -> b -> [a] -> b
●   scanl :: (a -> b -> a) -> a -> [b] -> [a]
●   scanr :: (a -> b -> b) -> b -> [a] -> [b]
●   folding is a general approach for simple recursion
●   scan is like fold, but returns the accumulator state of every
      recursion step instead of the accumulator
Modules (1)
●   types and functions are managed in modules
●   main module can load other modules
●   prelude.hs loads mostly used modules on startup
●   import modules at the beginning of a File:
             import Data.List
●   Selective Import of only some functions of module
             import Data.List (nub, sort)
         –   import only functions nub and sort
         –   import Data.List hiding (nub)
         –   import all functions but not nub
Modules (2)
●   use qualified imports if you have name conflicts
●   often occurs on import modules which are already selective
       imported by prelude.hs
             import Data.Map as M
         –   use reference to call qualified imports, e.g.
             M.filter (>5) [3,6,2]
Modules (3)
●   create own modules, e.g. File Geometry.hs
       module Geometry
       ( sphereVolume
       , sphereArea
       ) where
       //Implementation
●   modules in a namespace must be in same parent Folder, e.g.
      module Geometry.Sphere
      ( volume
      , area
      ) where
        –   Sphere.hs in folder Geometry
Functor Typeclass (1)
    class Functor f where
      fmap :: (a -> b) -> f a -> f b
●   general Interface for things that can be mapped over
●   !!! Functor needs Types with kind * -> * !!!
●   fmap gets a function and a type and maps the function
      over the type variable
●   Instance for List:
    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
●   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 Just (4+)
●   → we need an extension → Applicative Functors
Applicative Functor (1)
    class (Functor f) => Applicative f where
      pure :: a -> f a
      (<*>) :: f (a -> b) -> f a -> f b
●   pure is a function who wraps a normal value into applicative
         –   creates a minimal context
●   (<*>) takes a functor with a function in it and another functor
         –   extracts that function from the first functor
         –   and then maps it over the second one
●   pure f <*> x equals fmap f x              → specific function exists:
    (<$>) :: (Functor f) => (a -> b) -> f a -> f b
      f <$> x = fmap f x
Applicative Functor (2)
●   Instance for Maybe
    instance Applicative Maybe where
      pure = Just
      Nothing <*> _ = Nothing
      (Just f) <*> something = fmap f something
●   Instance for IO
    instance Applicative IO where
      pure = return
      a <*> b = do
        f <- a
        x <- b
        return (f x)
Applicative Functor (3)
    Examples:
●   Just (+3) <*> Just 9   returns Just 12
●   pure (+3) <*> Just 10 returns Just 13
●   Just (++"hah") <*> Nothing returns Nothing
●   [(+100),(^2)] <*> [1,2,3] returns [101,102,103,1,4,9]
●   pure "Hey" :: [String] returns ["Hey"]
●   [(+),(*)] <*> [1,2] <*> [3,4] returns [4,5,5,6,3,4,6,8]
●   (++) <$> Just "foo" <*> Just "bar" returns Just "foobar"
●   main = do
      a <- (++) <$> getLine <*> getLine
      putStrLn $ "The two lines concatenated is: " ++ a
Lifting a Function (Functor)
●   if we partial apply fmap, the header has the following structure
    :t fmap (*2) results in
      fmap (*2) :: (Num a, Functor f) => f a -> f a
    :t fmap (cycle 3) results in
      fmap (cycle 3) :: (Functor f) => f a -> f [a]
●   → this is called lifting a function
●   → we can predefine a function which gets a Functor and
      returns a functor
●   → that means, we can bring normal functions inside the
      Wrapper (Context)
●   → we lift the function up into the Context
Lifting a Function (Applicative)
●   liftA :: Applicative f => (a -> b) -> f a -> f b
        –   same as fmap
        –   fmap :: Functor f => (a -> b) -> f a -> f b
●   liftA2 :: (Applicative f) => (a -> b -> c) -> f a
      -> f b -> f c
    liftA2 f a b = f <$> a <*> b
        –   gets a function, with 2 parameters
        –   operates on 2 Applicatives
        –   result is also an Applicative
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

All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!John De Goes
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Useful JMeter functions for scripting
Useful JMeter functions for scriptingUseful JMeter functions for scripting
Useful JMeter functions for scriptingTharinda Liyanage
 
Monad Transformers In The Wild
Monad Transformers In The WildMonad Transformers In The Wild
Monad Transformers In The WildStackMob Inc
 
Array within a class
Array within a classArray within a class
Array within a classAAKASH KUMAR
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...John De Goes
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScriptJoseph Smith
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slidesOCaml
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in PythonColin Su
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming languageMegha V
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScripttmont
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 

What's hot (20)

All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Useful JMeter functions for scripting
Useful JMeter functions for scriptingUseful JMeter functions for scripting
Useful JMeter functions for scripting
 
Monad Transformers In The Wild
Monad Transformers In The WildMonad Transformers In The Wild
Monad Transformers In The Wild
 
Array within a class
Array within a classArray within a class
Array within a class
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
MTL Versus Free
MTL Versus FreeMTL Versus Free
MTL Versus Free
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
 
O caml2014 leroy-slides
O caml2014 leroy-slidesO caml2014 leroy-slides
O caml2014 leroy-slides
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
 
Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 

Viewers also liked

Mongo dbを知ろう
Mongo dbを知ろうMongo dbを知ろう
Mongo dbを知ろうCROOZ, inc.
 
はじめてのMongoDB
はじめてのMongoDBはじめてのMongoDB
はじめてのMongoDBTakahiro Inoue
 
がっつりMongoDB事例紹介
がっつりMongoDB事例紹介がっつりMongoDB事例紹介
がっつりMongoDB事例紹介Tetsutaro Watanabe
 
MongoDB〜その性質と利用場面〜
MongoDB〜その性質と利用場面〜MongoDB〜その性質と利用場面〜
MongoDB〜その性質と利用場面〜Naruhiko Ogasawara
 
MongoDB全機能解説1
MongoDB全機能解説1MongoDB全機能解説1
MongoDB全機能解説1Takahiro Inoue
 
初心者向けMongoDBのキホン!
初心者向けMongoDBのキホン!初心者向けMongoDBのキホン!
初心者向けMongoDBのキホン!Tetsutaro Watanabe
 

Viewers also liked (6)

Mongo dbを知ろう
Mongo dbを知ろうMongo dbを知ろう
Mongo dbを知ろう
 
はじめてのMongoDB
はじめてのMongoDBはじめてのMongoDB
はじめてのMongoDB
 
がっつりMongoDB事例紹介
がっつりMongoDB事例紹介がっつりMongoDB事例紹介
がっつりMongoDB事例紹介
 
MongoDB〜その性質と利用場面〜
MongoDB〜その性質と利用場面〜MongoDB〜その性質と利用場面〜
MongoDB〜その性質と利用場面〜
 
MongoDB全機能解説1
MongoDB全機能解説1MongoDB全機能解説1
MongoDB全機能解説1
 
初心者向けMongoDBのキホン!
初心者向けMongoDBのキホン!初心者向けMongoDBのキホン!
初心者向けMongoDBのキホン!
 

Similar to 10. haskell Modules

Similar to 10. haskell Modules (20)

08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
Functional programming with haskell
Functional programming with haskellFunctional programming with haskell
Functional programming with haskell
 
Functors, applicatives, monads
Functors, applicatives, monadsFunctors, applicatives, monads
Functors, applicatives, monads
 
Practical cats
Practical catsPractical cats
Practical cats
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
07. haskell Membership
07. haskell Membership07. haskell Membership
07. haskell Membership
 
Funkcija, objekt, python
Funkcija, objekt, pythonFunkcija, objekt, python
Funkcija, objekt, python
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
Advance python
Advance pythonAdvance python
Advance python
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Functions12
Functions12Functions12
Functions12
 
Functions123
Functions123 Functions123
Functions123
 
Functional python
Functional pythonFunctional python
Functional python
 
Scala qq
Scala qqScala qq
Scala qq
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
04. haskell handling
04. haskell handling04. haskell handling
04. haskell handling
 
functions
functionsfunctions
functions
 

Recently uploaded

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 

Recently uploaded (20)

"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 

10. haskell Modules

  • 1. Modules Sebastian Rettig A Haskell module is aa collection of related functions, A Haskell module is collection of related functions, types and typeclasses. types and typeclasses.
  • 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 ● Curried Functions
  • 4. Nice to remember (1) Applicative Context: – Maybe, Either for things which can fail – [] as non-deterministic result – IO as values send or get from outside ● Applicative functors allows us to operate in applicative types like normal types and provide the context! ● → We don't need to pattern match against the Context in every operation we use in our functions!
  • 5. Nice to remember (2) Typeclasses: ● define properties of the types ● an interface for types who have some behavior in common: – Eq can be compared – Ord can be ordered (>, <, >=, <=) (extending Eq) – Show can be shown as string – Read opposite of Show – Functor something that can be mapped over – Applicative handle functions wrapped in a Functor
  • 6. Nice to remember (3) 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]
  • 7. Nice to remember (4) Curried Function: ● every function in haskell consumes exactly one parameter and returns a value ● PARTIAL APPLICATION ● 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)
  • 8. Nice to remember (5) Pointless Style: ● based on partial Application → simpler code maxWithFour x = max 4 x is the same as maxWithFour = max 4 ● use Function Application ($) to avoid Parenthesis on function call with parameters sqrt $ 3 + 4 + 9 ● use Function Composition (.) to avoid Parenthesis on chaining functions fn = ceiling . negate . tan . cos . max 50
  • 9. Nice to remember (6) Kind: ● explains the steps which are necessary to evaluate the data from that type ● → evaluate = the type is fully applied ● can be used to find out the parameter-count of a type ● GHCi- Command :k ● :k Int returns Int :: * ● data MyVector4 a b c = Nirvana4 | Single4 {x'' :: a} | Tuple4 {x'' :: a, y :: b} | Triple4 {x'' :: a, y'' :: b, z'' :: c} :k MyVector4 returns MyVector4 :: * -> * -> * -> *
  • 10. Nice to remember (7) DO-Notation: main :: IO () main = do putStrLn “Say me your Name!” name <- getLine putStrLn $ “Hello” ++ name ● do syntax glues IO actions together ● bind operator <- get the data out of IO and bind result to a placeholder ● :t getLine returns getLine :: IO String – name has the type String ● ! The last action in a do-block can not be bound !
  • 11. Nice to remember (8) Fold & Scan: ● foldl :: (a -> b -> a) -> a -> [b] -> a ● foldr :: (a -> b -> b) -> b -> [a] -> b ● scanl :: (a -> b -> a) -> a -> [b] -> [a] ● scanr :: (a -> b -> b) -> b -> [a] -> [b] ● folding is a general approach for simple recursion ● scan is like fold, but returns the accumulator state of every recursion step instead of the accumulator
  • 12. Modules (1) ● types and functions are managed in modules ● main module can load other modules ● prelude.hs loads mostly used modules on startup ● import modules at the beginning of a File: import Data.List ● Selective Import of only some functions of module import Data.List (nub, sort) – import only functions nub and sort – import Data.List hiding (nub) – import all functions but not nub
  • 13. Modules (2) ● use qualified imports if you have name conflicts ● often occurs on import modules which are already selective imported by prelude.hs import Data.Map as M – use reference to call qualified imports, e.g. M.filter (>5) [3,6,2]
  • 14. Modules (3) ● create own modules, e.g. File Geometry.hs module Geometry ( sphereVolume , sphereArea ) where //Implementation ● modules in a namespace must be in same parent Folder, e.g. module Geometry.Sphere ( volume , area ) where – Sphere.hs in folder Geometry
  • 15. Functor Typeclass (1) class Functor f where fmap :: (a -> b) -> f a -> f b ● general Interface for things that can be mapped over ● !!! Functor needs Types with kind * -> * !!! ● fmap gets a function and a type and maps the function over the type variable ● Instance for List: instance Functor [] where fmap = map – Example: fmap (*2) [2,3,4] returns [4,6,8]
  • 16. 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)
  • 17. Functor Typeclass (3) 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 Just (4+) ● → we need an extension → Applicative Functors
  • 18. Applicative Functor (1) class (Functor f) => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b ● pure is a function who wraps a normal value into applicative – creates a minimal context ● (<*>) takes a functor with a function in it and another functor – extracts that function from the first functor – and then maps it over the second one ● pure f <*> x equals fmap f x → specific function exists: (<$>) :: (Functor f) => (a -> b) -> f a -> f b f <$> x = fmap f x
  • 19. Applicative Functor (2) ● Instance for Maybe instance Applicative Maybe where pure = Just Nothing <*> _ = Nothing (Just f) <*> something = fmap f something ● Instance for IO instance Applicative IO where pure = return a <*> b = do f <- a x <- b return (f x)
  • 20. Applicative Functor (3) Examples: ● Just (+3) <*> Just 9 returns Just 12 ● pure (+3) <*> Just 10 returns Just 13 ● Just (++"hah") <*> Nothing returns Nothing ● [(+100),(^2)] <*> [1,2,3] returns [101,102,103,1,4,9] ● pure "Hey" :: [String] returns ["Hey"] ● [(+),(*)] <*> [1,2] <*> [3,4] returns [4,5,5,6,3,4,6,8] ● (++) <$> Just "foo" <*> Just "bar" returns Just "foobar" ● main = do a <- (++) <$> getLine <*> getLine putStrLn $ "The two lines concatenated is: " ++ a
  • 21. Lifting a Function (Functor) ● if we partial apply fmap, the header has the following structure :t fmap (*2) results in fmap (*2) :: (Num a, Functor f) => f a -> f a :t fmap (cycle 3) results in fmap (cycle 3) :: (Functor f) => f a -> f [a] ● → this is called lifting a function ● → we can predefine a function which gets a Functor and returns a functor ● → that means, we can bring normal functions inside the Wrapper (Context) ● → we lift the function up into the Context
  • 22. Lifting a Function (Applicative) ● liftA :: Applicative f => (a -> b) -> f a -> f b – same as fmap – fmap :: Functor f => (a -> b) -> f a -> f b ● liftA2 :: (Applicative f) => (a -> b -> c) -> f a -> f b -> f c liftA2 f a b = f <$> a <*> b – gets a function, with 2 parameters – operates on 2 Applicatives – result is also an Applicative
  • 23. 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)