SlideShare uma empresa Scribd logo
1 de 20
Baixar para ler offline
Streaming, IO

                Sebastian Rettig


“I/O actions are like boxes with little feet that go out and
  “I/O actions are like boxes with little feet that go out and
fetch some value from the outside world for us.” ([1])
  fetch some value from the outside world for us.” ([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
Functional vs. Imperative (1)
●   Imperative Program:
       –   give the computer a series of steps to
             execute
       –   → say the computer how to do something
            to achieve the goal
●   Functional Program:
       –   define what something is
       –   → don't care about the steps
Functional vs. Imperative (2)
●   Pure function (functional):
       –   can not change a state (because we have
            no variables → no state to change)
       –   can only return some result
       –   → call 2 times with same parameters has
            always to return the same result!
       –   e.g.: add:: Tree a -> a -> Tree a
               ●   returns a complete new tree, because
                     function can not change the state
Functional vs. Imperative (3)
●   Imperative function:
       –   can change a state
                   → has side-effects
       –   no guarantee, that function can crash the
            whole program
       –   → take care of all possible side-effects:
               ●   validate input
               ●   test, test, test!
Nice to remember (1)
●   Lambda-Functions:
      –   <param> <param> → <operation>
      –   e.g.:
                  ●   a b -> a+b
                  ●   map (x -> x+3) [2,3,4]
                          returns [5,6,7]
Nice to remember (2)
●   where & let .. in:
       –   additional definitions
       –   let .. in: defines scope of usage
               ●   let = definition
               ●   in = scope of definition (optional)
               ●   e.g.: add x = let a=9 in a + x
       –   where: has scope in whole function
               ●   e.g.: add x = a + x
                            where   a=9
Nice to remember (3)
●   GHCi Commands (Interpreter):
       –   :t
                ●   returns the function header (type)
                ●   e.g.: :t tail
                         tail :: [a] -> [a]
       –   :i
                ●   returns the function definition (interface)
                ●   e.g.: :i tail
                        tail :: [a] -> [a]        -- Defined in
                     GHC.List
Pure vs. Impure Functions
●   haskell use pure functions
●   a pure function can not change a state
●   but how can we communicate with that
     function?
●   → we have to use impure functions
●   → impure functions are for communicating
     with the outside world*
    (*) just a placeholder, real description in next session
The one and only program (1)
●   let's write the first IO program:
         main = putStrLn “Hello World!”
●   store it in helloworld.hs
●   compile instructions:
         ghc --make helloworld.hs
●   and execute:
         ./helloworld
The one and only program (2)
    main = putStrLn “Hello World!”
●   main = main entry point for IO actions
●   :i main
         main :: IO ()    -- Defined in Main
●   :i putStrLn
         putStrLn :: String -> IO () -- Defined
           in System.IO
What if we want more IO
              actions?
    main = do
     putStrLn “Say me your Name!”
     name <- getLine
     putStrLn $ “Hello” ++ name
●   do syntax glues IO actions together
●   bind operator <- binds some result to a
      placeholder
●   $ operator switches to right associative
IO Actions
●   an I/O action is like a box with little feet that will go
      out into the real world and do something there [1]
●   the only way to open the box and get the data inside
      it is to use the <- operator [1]
●   IO-Functions are impure functions
        –   called 2 times with same parameters do not
              always return the same result
●   you can only handle impure data in an impure
      environment
Bind Operator
●   so what type is bind to name?
      name <- getLine

        –   :t getLine
               getLine :: IO String
        –   name has the type String
●   ! The last action in a do-block can not be bound !
●   Quiz: Is this valid?
      name = “Hello” ++ getLine
●   Quiz: What is test?
      test <- putStrLn “Hello”
Include Pure Functions
●   easy by using let:
      main = do
         putStrLn “Your First Name:”
         fname <- getLine
         putStrLn “Your Last Name:”
         lname <- getLine
         putStrLn “Your Age:”
         age <- getLine
         let name = fname ++ lname
              daysOld = yearsToDays
         putStrLn $ “You are ” ++ name ++
           “ and ” ++ daysOld ++ “ Days old.”
Program Loop
●   use return to stop:
      main = do
         putStrLn “Your Name:”
         name <- getLine
         if null name
         then return ()
         else do
            putStrLn $ “Hello ” ++ name
            main
File Streaming
●   readFile: reads contents of a file lazy
●   :t readFile
        readFile :: FilePath -> IO String

●   What is FilePath?
        –   :i FilePath
            type FilePath = String -- Defined in
              GHC.IO
        –   → FilePath is synonym for String
File Streaming
●   e.g.:
      main = do
          contents <- readFile filename
          putStr contents

●   of course IO functions are also lazy:
       main = do
         contents <- readFile filename
         putStr $ take 5 contents

       –   no matter how long the file is
Sources
[1] Haskell-Tutorial: Learn you a Haskell (http://learnyouahaskell.com/,
    2012/03/15)
[2] The Hugs User-Manual (
    http://cvs.haskell.org/Hugs/pages/hugsman/index.html, 2012/03/15)
[3] The Haskellwiki (http://www.haskell.org/haskellwiki, 2012/03/15)

Mais conteúdo relacionado

Mais procurados

Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summary
lunfu zhong
 
CoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple wayCoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple way
Lim Chanmann
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
Kaunas Java User Group
 

Mais procurados (20)

Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Haskell
HaskellHaskell
Haskell
 
Hello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC UnidebHello kotlin | An Event by DSC Unideb
Hello kotlin | An Event by DSC Unideb
 
Reactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScriptReactive Programming in the Browser feat. Scala.js and PureScript
Reactive Programming in the Browser feat. Scala.js and PureScript
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
 
Building a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGLBuilding a Tagless Final DSL for WebGL
Building a Tagless Final DSL for WebGL
 
Groovy
GroovyGroovy
Groovy
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional Programming
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summary
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
 
CoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple wayCoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple way
 
Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)Intro to Java 8 Closures (Dainius Mezanskas)
Intro to Java 8 Closures (Dainius Mezanskas)
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modules
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
Java 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava ComparisonJava 8 Stream API and RxJava Comparison
Java 8 Stream API and RxJava Comparison
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 

Destaque (6)

08. haskell Functions
08. haskell Functions08. haskell Functions
08. haskell Functions
 
04. haskell handling
04. haskell handling04. haskell handling
04. haskell handling
 
01. haskell introduction
01. haskell introduction01. haskell introduction
01. haskell introduction
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
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
 

Semelhante a 05. haskell streaming io

Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
krmboya
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 

Semelhante a 05. haskell streaming io (20)

10. haskell Modules
10. haskell Modules10. haskell Modules
10. haskell Modules
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Kotlin
KotlinKotlin
Kotlin
 
Functional Go
Functional GoFunctional Go
Functional Go
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
 
Luigi presentation NYC Data Science
Luigi presentation NYC Data ScienceLuigi presentation NYC Data Science
Luigi presentation NYC Data Science
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional features
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 

Último

Último (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 

05. haskell streaming io

  • 1. Streaming, IO Sebastian Rettig “I/O actions are like boxes with little feet that go out and “I/O actions are like boxes with little feet that go out and fetch some value from the outside world for us.” ([1]) fetch some value from the outside world for us.” ([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. Functional vs. Imperative (1) ● Imperative Program: – give the computer a series of steps to execute – → say the computer how to do something to achieve the goal ● Functional Program: – define what something is – → don't care about the steps
  • 5. Functional vs. Imperative (2) ● Pure function (functional): – can not change a state (because we have no variables → no state to change) – can only return some result – → call 2 times with same parameters has always to return the same result! – e.g.: add:: Tree a -> a -> Tree a ● returns a complete new tree, because function can not change the state
  • 6. Functional vs. Imperative (3) ● Imperative function: – can change a state → has side-effects – no guarantee, that function can crash the whole program – → take care of all possible side-effects: ● validate input ● test, test, test!
  • 7. Nice to remember (1) ● Lambda-Functions: – <param> <param> → <operation> – e.g.: ● a b -> a+b ● map (x -> x+3) [2,3,4] returns [5,6,7]
  • 8. Nice to remember (2) ● where & let .. in: – additional definitions – let .. in: defines scope of usage ● let = definition ● in = scope of definition (optional) ● e.g.: add x = let a=9 in a + x – where: has scope in whole function ● e.g.: add x = a + x where a=9
  • 9. Nice to remember (3) ● GHCi Commands (Interpreter): – :t ● returns the function header (type) ● e.g.: :t tail tail :: [a] -> [a] – :i ● returns the function definition (interface) ● e.g.: :i tail tail :: [a] -> [a] -- Defined in GHC.List
  • 10. Pure vs. Impure Functions ● haskell use pure functions ● a pure function can not change a state ● but how can we communicate with that function? ● → we have to use impure functions ● → impure functions are for communicating with the outside world* (*) just a placeholder, real description in next session
  • 11. The one and only program (1) ● let's write the first IO program: main = putStrLn “Hello World!” ● store it in helloworld.hs ● compile instructions: ghc --make helloworld.hs ● and execute: ./helloworld
  • 12. The one and only program (2) main = putStrLn “Hello World!” ● main = main entry point for IO actions ● :i main main :: IO () -- Defined in Main ● :i putStrLn putStrLn :: String -> IO () -- Defined in System.IO
  • 13. What if we want more IO actions? main = do putStrLn “Say me your Name!” name <- getLine putStrLn $ “Hello” ++ name ● do syntax glues IO actions together ● bind operator <- binds some result to a placeholder ● $ operator switches to right associative
  • 14. IO Actions ● an I/O action is like a box with little feet that will go out into the real world and do something there [1] ● the only way to open the box and get the data inside it is to use the <- operator [1] ● IO-Functions are impure functions – called 2 times with same parameters do not always return the same result ● you can only handle impure data in an impure environment
  • 15. Bind Operator ● so what type is bind to name? name <- getLine – :t getLine getLine :: IO String – name has the type String ● ! The last action in a do-block can not be bound ! ● Quiz: Is this valid? name = “Hello” ++ getLine ● Quiz: What is test? test <- putStrLn “Hello”
  • 16. Include Pure Functions ● easy by using let: main = do putStrLn “Your First Name:” fname <- getLine putStrLn “Your Last Name:” lname <- getLine putStrLn “Your Age:” age <- getLine let name = fname ++ lname daysOld = yearsToDays putStrLn $ “You are ” ++ name ++ “ and ” ++ daysOld ++ “ Days old.”
  • 17. Program Loop ● use return to stop: main = do putStrLn “Your Name:” name <- getLine if null name then return () else do putStrLn $ “Hello ” ++ name main
  • 18. File Streaming ● readFile: reads contents of a file lazy ● :t readFile readFile :: FilePath -> IO String ● What is FilePath? – :i FilePath type FilePath = String -- Defined in GHC.IO – → FilePath is synonym for String
  • 19. File Streaming ● e.g.: main = do contents <- readFile filename putStr contents ● of course IO functions are also lazy: main = do contents <- readFile filename putStr $ take 5 contents – no matter how long the file is
  • 20. 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)