SlideShare a Scribd company logo
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)

More Related Content

What's hot

Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
Aung Baw
 
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
Muhammad Raza
 
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
Luka Jacobowitz
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For Beginners
Matt Passell
 
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
Luka Jacobowitz
 
Groovy
GroovyGroovy
Groovy
atonse
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional Programming
Yiguang Hu
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
Jieyi Wu
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
Andres Almiray
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summarylunfu zhong
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
Sergey Stupin
 
CoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple wayCoffeeScript - JavaScript in a simple way
CoffeeScript - JavaScript in a simple wayLim 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
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modules
John Hunter
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
WebStackAcademy
 
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
José Paumard
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
thnetos
 

What's hot (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
 

Viewers also liked

03. haskell refresher quiz
03. haskell refresher quiz03. haskell refresher quiz
03. haskell refresher quiz
Sebastian Rettig
 
02. haskell motivation
02. haskell motivation02. haskell motivation
02. haskell motivation
Sebastian Rettig
 

Viewers also liked (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
 

Similar to 05. haskell streaming io

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
RichardWarburton
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
George Shuklin
 
Functional programming
Functional programmingFunctional programming
Functional programming
S M Asaduzzaman
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
Functional Go
Functional GoFunctional Go
Functional Go
Geison Goes
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
Karin Lagesen
 
Functional Swift
Functional SwiftFunctional Swift
Functional Swift
Geison Goes
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
Codemotion
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
Jordan Open Source Association
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
Geison Goes
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobikrmboya
 
Luigi presentation NYC Data Science
Luigi presentation NYC Data ScienceLuigi presentation NYC Data Science
Luigi presentation NYC Data Science
Erik Bernhardsson
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresque
Bret McGuire
 
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
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional features
Rafal Rybacki
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
daewon jeong
 

Similar to 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()
 

Recently uploaded

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 

Recently uploaded (20)

Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 

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)