SlideShare a Scribd company logo
1 of 21
1
PROGRAMMING IN HASKELL
Chapter 9 - Interactive Programs
2
Introduction
To date, we have seen how Haskell can be used to
write batch programs that take all their inputs at the
start and give all their outputs at the end.
batch
program
inputs outputs
3
However, we would also like to use Haskell to write
interactive programs that read from the keyboard and
write to the screen, as they are running.
interactive
program
inputs outputs
keyboard
screen
4
The Problem
Haskell programs are pure mathematical functions:
However, reading from the keyboard and writing to
the screen are side effects:
Haskell programs have no side
effects.
Interactive programs have side effects.
5
The Solution
Interactive programs can be written in Haskell by
using types to distinguish pure expressions from
impure actions that may involve side effects.
IO a
The type of actions that
return a value of type a.
6
For example:
IO Char
IO ()
The type of actions
that return a character.
The type of purely side
effecting actions that
return no result value.
() is the type of tuples with no components.
Note:
7
Basic Actions
The standard library provides a number of actions,
including the following three primitives:
getChar :: IO Char
The action getChar reads a character from the
keyboard, echoes it to the screen, and returns
the character as its result value:
8
The action putChar c writes the character c to
the screen, and returns no result value:
putChar :: Char → IO ()
The action return v simply returns the value v,
without performing any interaction:
return :: a → IO a
9
A sequence of actions can be combined as a single
composite action using the keyword do.
For example:
Sequencing
a :: IO (Char,Char)
a = do x ← getChar
getChar
y ← getChar
return (x,y)
10
Derived Primitives
getLine :: IO String
getLine = do x ← getChar
if x == 'n' then
return []
else
do xs ← getLine
return (x:xs)
Reading a string from the keyboard:
11
putStr :: String → IO ()
putStr [] = return ()
putStr (x:xs) = do putChar x
putStr xs
Writing a string to the screen:
Writing a string and moving to a new line:
putStrLn :: String → IO ()
putStrLn xs = do putStr xs
putChar 'n'
12
Example
We can now define an action that prompts for a
string to be entered and displays its length:
strlen :: IO ()
strlen = do putStr "Enter a string: "
xs ← getLine
putStr "The string has "
putStr (show (length xs))
putStrLn " characters"
13
For example:
> strlen
Enter a string: abcde
The string has 5 characters
Evaluating an action executes its side effects,
with the final result value being discarded.
Note:
14
Hangman
Consider the following version of hangman:
One player secretly types in a word.
The other player tries to deduce the word, by
entering a sequence of guesses.
For each guess, the computer indicates which
letters in the secret word occur in the guess.
15
The game ends when the guess is correct.
hangman :: IO ()
hangman =
do putStrLn "Think of a word: "
word ← sgetLine
putStrLn "Try to guess it:"
guess word
We adopt a top down approach to implementing
hangman in Haskell, starting as follows:
16
The action sgetLine reads a line of text from the
keyboard, echoing each character as a dash:
sgetLine :: IO String
sgetLine = do x ← getCh
if x == 'n' then
do putChar x
return []
else
do putChar '-'
xs ← sgetLine
return (x:xs)
17
import System.IO
getCh :: IO Char
getCh = do hSetEcho stdin False
c ← getChar
hSetEcho stdin True
return c
The action getCh reads a single character from the
keyboard, without echoing it to the screen:
18
The function guess is the main loop, which requests
and processes guesses until the game ends.
guess :: String → IO ()
guess word =
do putStr "> "
xs ← getLine
if xs == word then
putStrLn "You got it!"
else
do putStrLn (diff word xs)
guess word
19
The function diff indicates which characters in one
string occur in a second string:
For example:
> diff "haskell" "pascal"
"-as--ll"
diff :: String → String → String
diff xs ys =
[if elem x ys then x else '-' | x ← xs]
20
Exercise
Implement the game of nim in Haskell, where the
rules of the game are as follows:
The board comprises five rows of stars:
1: * * * * *
2: * * * *
3: * * *
4: * *
5: *
21
Two players take it turn about to remove one
or more stars from the end of a single row.
The winner is the player who removes the last
star or stars from the board.
Hint:
Represent the board as a list of five integers that
give the number of stars remaining on each row.
For example, the initial board is [5,4,3,2,1].

More Related Content

What's hot

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class PatternsJohn De Goes
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQKnoldus Inc.
 
Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In SwiftVadym Markov
 
Javascript: repetita iuvant
Javascript: repetita iuvantJavascript: repetita iuvant
Javascript: repetita iuvantLuciano Mammino
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей КоваленкоFwdays
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in goYusuke Kita
 
API design: using type classes and dependent types
API design: using type classes and dependent typesAPI design: using type classes and dependent types
API design: using type classes and dependent typesbmlever
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCTomohiro Kumagai
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskellJongsoo Lee
 
Elm introduction
Elm   introductionElm   introduction
Elm introductionMix & Go
 
From OCaml To Javascript At Skydeck
From OCaml To Javascript At SkydeckFrom OCaml To Javascript At Skydeck
From OCaml To Javascript At SkydeckJake Donham
 

What's hot (19)

Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Real World Generics In Swift
Real World Generics In SwiftReal World Generics In Swift
Real World Generics In Swift
 
Javascript: repetita iuvant
Javascript: repetita iuvantJavascript: repetita iuvant
Javascript: repetita iuvant
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко"Немного о функциональном программирование в JavaScript" Алексей Коваленко
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
API design: using type classes and dependent types
API design: using type classes and dependent typesAPI design: using type classes and dependent types
API design: using type classes and dependent types
 
Introduction of ES2015
Introduction of ES2015Introduction of ES2015
Introduction of ES2015
 
Swift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDCSwift で JavaScript 始めませんか? #iOSDC
Swift で JavaScript 始めませんか? #iOSDC
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Talk Code
Talk CodeTalk Code
Talk Code
 
A taste of Functional Programming
A taste of Functional ProgrammingA taste of Functional Programming
A taste of Functional Programming
 
Elm introduction
Elm   introductionElm   introduction
Elm introduction
 
From OCaml To Javascript At Skydeck
From OCaml To Javascript At SkydeckFrom OCaml To Javascript At Skydeck
From OCaml To Javascript At Skydeck
 
Class ‘increment’
Class ‘increment’Class ‘increment’
Class ‘increment’
 

Viewers also liked

Learn Haskell The Easy Way
Learn Haskell The Easy WayLearn Haskell The Easy Way
Learn Haskell The Easy WayYC Ling
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in HaskellHiromi Ishii
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10Kousuke Ruichi
 
Sand casting of metals - Gating system for sand casting mould
Sand casting of metals - Gating system for sand casting mouldSand casting of metals - Gating system for sand casting mould
Sand casting of metals - Gating system for sand casting mouldAmruta Rane
 
GATING SYSTEM IN CASTING
GATING SYSTEM IN CASTINGGATING SYSTEM IN CASTING
GATING SYSTEM IN CASTINGVivek Tyagi
 

Viewers also liked (6)

Chapter7
Chapter7Chapter7
Chapter7
 
Learn Haskell The Easy Way
Learn Haskell The Easy WayLearn Haskell The Easy Way
Learn Haskell The Easy Way
 
Metaprogramming in Haskell
Metaprogramming in HaskellMetaprogramming in Haskell
Metaprogramming in Haskell
 
Programming haskell chapter10
Programming haskell chapter10Programming haskell chapter10
Programming haskell chapter10
 
Sand casting of metals - Gating system for sand casting mould
Sand casting of metals - Gating system for sand casting mouldSand casting of metals - Gating system for sand casting mould
Sand casting of metals - Gating system for sand casting mould
 
GATING SYSTEM IN CASTING
GATING SYSTEM IN CASTINGGATING SYSTEM IN CASTING
GATING SYSTEM IN CASTING
 

Similar to Chapter9

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance HaskellJohan Tibell
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)yap_raiza
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88Mahmoud Samir Fayed
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Mattersromanandreg
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181Mahmoud Samir Fayed
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdfsrxerox
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONvikram mahendra
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196Mahmoud Samir Fayed
 

Similar to Chapter9 (20)

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Mcq cpup
Mcq cpupMcq cpup
Mcq cpup
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
High-Performance Haskell
High-Performance HaskellHigh-Performance Haskell
High-Performance Haskell
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
dv-210220053508_removed.pdf
dv-210220053508_removed.pdfdv-210220053508_removed.pdf
dv-210220053508_removed.pdf
 
Programming ppt files (final)
Programming ppt files (final)Programming ppt files (final)
Programming ppt files (final)
 
Loop Statements [5] M
Loop Statements [5] MLoop Statements [5] M
Loop Statements [5] M
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 
The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88The Ring programming language version 1.3 book - Part 83 of 88
The Ring programming language version 1.3 book - Part 83 of 88
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181The Ring programming language version 1.5.2 book - Part 14 of 181
The Ring programming language version 1.5.2 book - Part 14 of 181
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdf
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196The Ring programming language version 1.7 book - Part 30 of 196
The Ring programming language version 1.7 book - Part 30 of 196
 

Recently uploaded

OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAbhinavSharma374939
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 

Recently uploaded (20)

OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Analog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog ConverterAnalog to Digital and Digital to Analog Converter
Analog to Digital and Digital to Analog Converter
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 

Chapter9

  • 1. 1 PROGRAMMING IN HASKELL Chapter 9 - Interactive Programs
  • 2. 2 Introduction To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start and give all their outputs at the end. batch program inputs outputs
  • 3. 3 However, we would also like to use Haskell to write interactive programs that read from the keyboard and write to the screen, as they are running. interactive program inputs outputs keyboard screen
  • 4. 4 The Problem Haskell programs are pure mathematical functions: However, reading from the keyboard and writing to the screen are side effects: Haskell programs have no side effects. Interactive programs have side effects.
  • 5. 5 The Solution Interactive programs can be written in Haskell by using types to distinguish pure expressions from impure actions that may involve side effects. IO a The type of actions that return a value of type a.
  • 6. 6 For example: IO Char IO () The type of actions that return a character. The type of purely side effecting actions that return no result value. () is the type of tuples with no components. Note:
  • 7. 7 Basic Actions The standard library provides a number of actions, including the following three primitives: getChar :: IO Char The action getChar reads a character from the keyboard, echoes it to the screen, and returns the character as its result value:
  • 8. 8 The action putChar c writes the character c to the screen, and returns no result value: putChar :: Char → IO () The action return v simply returns the value v, without performing any interaction: return :: a → IO a
  • 9. 9 A sequence of actions can be combined as a single composite action using the keyword do. For example: Sequencing a :: IO (Char,Char) a = do x ← getChar getChar y ← getChar return (x,y)
  • 10. 10 Derived Primitives getLine :: IO String getLine = do x ← getChar if x == 'n' then return [] else do xs ← getLine return (x:xs) Reading a string from the keyboard:
  • 11. 11 putStr :: String → IO () putStr [] = return () putStr (x:xs) = do putChar x putStr xs Writing a string to the screen: Writing a string and moving to a new line: putStrLn :: String → IO () putStrLn xs = do putStr xs putChar 'n'
  • 12. 12 Example We can now define an action that prompts for a string to be entered and displays its length: strlen :: IO () strlen = do putStr "Enter a string: " xs ← getLine putStr "The string has " putStr (show (length xs)) putStrLn " characters"
  • 13. 13 For example: > strlen Enter a string: abcde The string has 5 characters Evaluating an action executes its side effects, with the final result value being discarded. Note:
  • 14. 14 Hangman Consider the following version of hangman: One player secretly types in a word. The other player tries to deduce the word, by entering a sequence of guesses. For each guess, the computer indicates which letters in the secret word occur in the guess.
  • 15. 15 The game ends when the guess is correct. hangman :: IO () hangman = do putStrLn "Think of a word: " word ← sgetLine putStrLn "Try to guess it:" guess word We adopt a top down approach to implementing hangman in Haskell, starting as follows:
  • 16. 16 The action sgetLine reads a line of text from the keyboard, echoing each character as a dash: sgetLine :: IO String sgetLine = do x ← getCh if x == 'n' then do putChar x return [] else do putChar '-' xs ← sgetLine return (x:xs)
  • 17. 17 import System.IO getCh :: IO Char getCh = do hSetEcho stdin False c ← getChar hSetEcho stdin True return c The action getCh reads a single character from the keyboard, without echoing it to the screen:
  • 18. 18 The function guess is the main loop, which requests and processes guesses until the game ends. guess :: String → IO () guess word = do putStr "> " xs ← getLine if xs == word then putStrLn "You got it!" else do putStrLn (diff word xs) guess word
  • 19. 19 The function diff indicates which characters in one string occur in a second string: For example: > diff "haskell" "pascal" "-as--ll" diff :: String → String → String diff xs ys = [if elem x ys then x else '-' | x ← xs]
  • 20. 20 Exercise Implement the game of nim in Haskell, where the rules of the game are as follows: The board comprises five rows of stars: 1: * * * * * 2: * * * * 3: * * * 4: * * 5: *
  • 21. 21 Two players take it turn about to remove one or more stars from the end of a single row. The winner is the player who removes the last star or stars from the board. Hint: Represent the board as a list of five integers that give the number of stars remaining on each row. For example, the initial board is [5,4,3,2,1].