SlideShare una empresa de Scribd logo
1 de 20
Descargar para leer sin conexión
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)

Más contenido relacionado

La actualidad más candente

Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScriptAung 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 UnidebMuhammad 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 PureScriptLuka Jacobowitz
 
GPars For Beginners
GPars For BeginnersGPars For Beginners
GPars For BeginnersMatt 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 WebGLLuka Jacobowitz
 
Groovy
GroovyGroovy
Groovyatonse
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Java8 and Functional Programming
Java8 and Functional ProgrammingJava8 and Functional Programming
Java8 and Functional ProgrammingYiguang Hu
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet KotlinJieyi Wu
 
Zhongl scala summary
Zhongl scala summaryZhongl scala summary
Zhongl scala summarylunfu zhong
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overviewSergey 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 modulesJohn Hunter
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic FunctionsWebStackAcademy
 
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 ComparisonJosé Paumard
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 

La actualidad más candente (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
 

Destacado

Destacado (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 a 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 ProgrammingRichardWarburton
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansibleGeorge Shuklin
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Functional Swift
Functional SwiftFunctional Swift
Functional SwiftGeison Goes
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional ProgrammingGeison 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 ScienceErik Bernhardsson
 
Programming picaresque
Programming picaresqueProgramming picaresque
Programming picaresqueBret 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 GoGeeks Anonymes
 
Java 8 - functional features
Java 8 - functional featuresJava 8 - functional features
Java 8 - functional featuresRafal Rybacki
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 

Similar 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

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 
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
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
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
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
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
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 
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
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
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
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

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)