Difference between revisions of "Output/Input"

From HaskellWiki
Jump to navigation Jump to search
(All-new content and category!)
m
 
(60 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
 
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
 
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
  +
A purely functional program implements a <i>function</i>; it has no side effect. [...] if the side effect can’t be in the functional program, it will have to be outside it.
Still, today, over 25 years after the introduction of the concept of monads to the world of functional programming, beginning functional programmers struggle to grasp the concept of monads. This struggle is exemplified by the numerous blog posts about the effort of trying to learn about monads. From our own experience we notice that even at university level, bachelor level students often struggle to comprehend monads and consistently score poorly on monad-related exam questions.
 
   
  +
<small>[https://web.archive.org/web/20210415200634/https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.13.9123&rep=rep1&type=pdf Tackling the Awkward Squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell], Simon Peyton Jones (pages 3-4 of 60). </small>
Considering that the concept of monads is not likely to disappear from the functional programming landscape any time soon, it is vital that we, as the functional programming community, somehow overcome the problems novices encounter when first studying monads.
 
  +
</div>
   
  +
One technique has been used for similar tasks:
<tt>[https://pms.cs.ru.nl/iris-diglib/src/getContent.php?id=2017-Steenvoorden-SupportLearning Visual Support for Learning Monads], Tim Steenvoorden, Jurriën Stutterheim, Erik Barendsen and Rinus Plasmeijer.</tt>
 
  +
  +
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
  +
This is discussed by Burton[https://academic.oup.com/comjnl/article-pdf/31/3/243/1157325/310243.pdf <span></span>], and is built on by Harrison[https://core.ac.uk/download/9835633.pdf <span></span>]. The effect of this proposal is to place the non-determinism <i>entirely</i> outside the software [...]
  +
  +
<small>[https://academic.oup.com/comjnl/article-pdf/32/2/162/1445725/320162.pdf Functional Programming and Operating Systems], Simon B. Jones and A. F. Sinclair (page 10 of 13).</small>
 
</div>
 
</div>
   
  +
It can also be used to provide access to external resources:
...so where are students of Haskell most likely to have their first encounter with this irksome interface? Here's a hint:
 
   
 
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
 
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
  +
The approach generalizes so that a program can make use of other run-time information such as the current time or current amount of available storage.
<code>IO</code> is the monad you cannot avoid.
 
   
  +
<small>[https://academic.oup.com/comjnl/article-pdf/31/3/243/1157325/310243.pdf Nondeterminism with Referential Transparency in Functional Programming Languages], F. Warren Burton (front page).</small>
<tt>[https://image.slidesharecdn.com/functionalconf2019-whyishaskellsohard2-191116135003/95/why-is-haskell-so-hard-and-how-to-deal-with-it-53-638.jpg Why Haskell is so HARD? (And how to deal with it)]; Saurabh Nanda.</tt>
 
 
</div>
 
</div>
   
  +
Perhaps it can be used for I/O...
If bachelor-level students are often struggling to comprehend the monadic interface, then it has ''no place whatsoever'' in any introductory Haskell course! I/O in Haskell must therefore be totally independent of the monadic interface. The introduction of this interface, including its basic operations, should be deferred to an advanced course of study where it can join functors, applicatives, arrows and maybe even category theory itself: only then should students be introduced to monadic I/O.
 
  +
<br>
  +
  +
__TOC__
  +
<sup> <sup>
  +
  +
----
  +
=== <u>Details, details</u> ===
  +
  +
How does it work?
  +
  +
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
  +
[...] supply each program with an extra argument consisting of an infinite (lazy) binary tree of values. (We choose a tree [...] since any number of subtrees may be extracted from an infinite tree). In practice, these values will be determined at run time (when used as arguments to a special function [...]), but once fixed will never change.
  +
</div>
  +
  +
...<i>“a special function”</i>: only one? More will definitely be needed! To keep matters [https://www.interaction-design.org/literature/article/kiss-keep-it-simple-stupid-a-design-principle simple], each value shall only be used <b>once</b> (if at all) as an argument to any such function.
  +
  +
<haskell>
  +
main' :: Tree Exterior -> ...
  +
  +
-- section 2
  +
data Tree a = Node { contents :: a,
  +
left :: Tree a,
  +
right :: Tree a }
  +
  +
data Exterior -- the abstract value type
  +
getchar :: Exterior -> Char -- the special functions
  +
putchar :: Char -> Exterior -> () -- (add more as needed :-)
  +
</haskell>
  +
  +
Avoiding gratuitous repetition:
  +
  +
<haskell>
  +
type OI = Tree Exterior
  +
  +
getChar' :: OI -> Char
  +
getChar' = getchar . contents
  +
  +
putChar' :: Char -> OI -> ()
  +
putChar' c = putchar c . contents
  +
</haskell>
  +
<sup> </sup>
  +
  +
==== An alternative abstraction ====
  +
  +
About those trees: are they really necessary? If <code>OI</code> was an abstract data type, the use of trees could at least be confined to the implementation:
  +
  +
<haskell>
  +
data OI
  +
getChar' :: OI -> Char
  +
putChar' :: Char -> OI -> ()
  +
</haskell>
  +
  +
...provided that single-use property applies directly to <code>OI</code> values (thereby deeming <i>“special”</i> any function which uses an <code>OI</code> argument). That includes the initial <code>OI</code> value supplied to each program:
  +
  +
<haskell>
  +
main' :: OI -> ...
  +
</haskell>
  +
  +
But most Haskell programs will need more:
  +
  +
<haskell>
  +
part :: OI -> (OI, OI)
  +
part t = (left t, right t)
  +
</haskell>
  +
  +
...than two <code>OI</code> values:
  +
  +
<haskell>
  +
parts :: OI -> [OI]
  +
parts t = let (t1, t2) = part t in t1 : parts t2
  +
</haskell>
  +
  +
So <code>OI</code> can be a tree-free abstract data type after all:
  +
  +
<haskell>
  +
data OI
  +
partOI :: OI -> (OI, OI)
  +
getChar :: OI -> Char
  +
putChar :: Char -> OI -> ()
  +
</haskell>
  +
<sup> </sup>
  +
  +
----
  +
=== <u>Other interfaces</u> ===
  +
  +
* [[Monad|monad]]
  +
  +
:<haskell>
  +
type M a = OI -> a
  +
  +
unit :: a -> M a
  +
unit x = \ u -> let !_ = partOI u in x
  +
  +
bind :: M a -> (a -> M b) -> M b
  +
bind m k = \ u -> let !(u1, u2) = partOI u in
  +
let !x = m u1 in
  +
let !y = k x u2 in
  +
y
  +
  +
getcharM :: M Char
  +
getcharM = getChar
  +
  +
putcharM :: Char -> M ()
  +
putcharM = putChar
  +
</haskell>
  +
  +
* [[Comonad|comonad]]:
  +
  +
:<haskell>
  +
type C a = (OI, a)
  +
  +
extract :: C a -> a
  +
extract (u, x) = let !_ = partOI u in x
  +
  +
duplicate :: C a -> C (C a)
  +
duplicate (u, x) = let !(u1, u2) = partOI u in
  +
(u2, (u1, x))
  +
  +
extend :: (C a -> b) -> C a -> C b
  +
extend h (u, x) = let !(u1, u2) = partOI u in
  +
let !y = h (u1, x) in
  +
(u2, y)
  +
  +
getcharC :: C () -> Char
  +
getcharC (u, ()) = getChar u
  +
  +
putcharC :: C Char -> ()
  +
putcharC (u, c) = putChar c u
  +
  +
</haskell>
  +
  +
* [[Arrow|arrow]]:
  +
  +
:<haskell>
  +
type A b c = (OI -> b) -> (OI -> c)
  +
  +
arr :: (b -> c) -> A b c
  +
arr f = \ c' u -> let !x = c' u in f x
  +
  +
both :: A b c -> A b' c' -> A (b, b') (c, c')
  +
f' `both` g' = \ c' u -> let !(u1:u2:u3:_) = partsOI u in
  +
let !(x, x') = c' u1 in
  +
let !y = f' (unit x) u2 in
  +
let !y' = g' (unit x') u3 in
  +
(y, y')
  +
where
  +
unit x u = let !_ = partOI u in x
  +
  +
getcharA :: A () Char
  +
getcharA = \ c' u -> let !(u1, u2) = partOI u in
  +
let !_ = c' u1 in
  +
let !ch = getChar u2 in
  +
ch
  +
  +
putcharA :: A Char ()
  +
putcharA = \ c' u -> let !(u1, u2) = partOI u in
  +
let !ch = c' u1 in
  +
let !z = putChar ch u2 in
  +
z
  +
</haskell>
  +
  +
The <code>OI</code> interface can also be used to implement [https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.91.3579&rep=rep1&type=pdf I/O models used in earlier versions] of Haskell:
  +
  +
* dialogues:
  +
  +
:<haskell>
  +
runD :: ([Response] -> [Request]) -> OI -> ()
  +
runD d u = foldr (\ (!_) -> id) () $ yet $ \ l -> zipWith respond (d l) (partsOI u)
  +
  +
yet :: (a -> a) -> a
  +
yet f = f (yet f)
  +
  +
respond :: Request -> OI -> Response
  +
respond Getq u = let !c = getChar u in Getp c
  +
respond (Putq c) u = let !_ = putChar c u in Putp
  +
  +
data Request = Getq | Putq Char
  +
data Response = Getp Char | Putp
  +
</haskell>
  +
  +
* continuations:
  +
  +
:<haskell>
  +
type Answer = OI -> ()
  +
  +
runK :: Answer -> OI -> ()
  +
runK a u = a u
  +
  +
doneK :: Answer
  +
doneK = \ u -> let !_ = partOI u in ()
  +
  +
getcharK :: (Char -> Answer) -> Answer
  +
getcharK k = \ u -> let !(u1, u2) = partOI u in
  +
let !c = getChar u1 in
  +
let !a = k c in
  +
a u2
  +
  +
putcharK :: Char -> Answer -> Answer
  +
putcharK c a = \ u -> let !(u1, u2) = partOI u in
  +
let !_ = putChar c u1 in
  +
a u2
  +
</haskell>
  +
  +
...and even <i>that</i> <s><i>world</i></s> state-passing style used in GHC, which is also used by [https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.17.935&rep=rep1&type=pdf Clean], [https://staff.science.uva.nl/c.u.grelck/publications/HerhSchoGrelDAMP09.pdf Single-Assignment C] and as part of the I/O model used for the verification of interactive programs in [https://cakeml.org/vstte18.pdf CakeML], remembering that <code>OI</code> values can only be used once:
  +
  +
<haskell>
  +
newtype World = W OI
  +
  +
getcharL :: World -> (Char, World)
  +
getcharL (W u) = let !(u1, u2) = partOI u in
  +
let !c = getChar u1 in
  +
(c, W u2)
  +
  +
putcharL :: Char -> World -> World
  +
putcharL c (W u) = let !(u1, u2) = partOI u in
  +
let !_ = putChar c u1 in
  +
W u2
  +
</haskell>
  +
<sup> </sup>
  +
  +
----
  +
=== <u>See also</u> ===
   
  +
* [[Plainly partible]]
A [https://www.interaction-design.org/literature/article/kiss-keep-it-simple-stupid-a-design-principle simple] general-purpose model of I/O for non-strict functional languages remains an [[Open research problems|open research problem]]...
 
  +
* [[Disposing of dismissives]]
  +
* [[IO then abstraction]]
   
[[Category:Rants and comments]]
+
[[Category:Theoretical foundations]]

Latest revision as of 12:36, 1 January 2024

A purely functional program implements a function; it has no side effect. [...] if the side effect can’t be in the functional program, it will have to be outside it.

Tackling the Awkward Squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell, Simon Peyton Jones (pages 3-4 of 60).

One technique has been used for similar tasks:

This is discussed by Burton, and is built on by Harrison. The effect of this proposal is to place the non-determinism entirely outside the software [...]

Functional Programming and Operating Systems, Simon B. Jones and A. F. Sinclair (page 10 of 13).

It can also be used to provide access to external resources:

The approach generalizes so that a program can make use of other run-time information such as the current time or current amount of available storage.

Nondeterminism with Referential Transparency in Functional Programming Languages, F. Warren Burton (front page).

Perhaps it can be used for I/O...


Details, details

How does it work?

[...] supply each program with an extra argument consisting of an infinite (lazy) binary tree of values. (We choose a tree [...] since any number of subtrees may be extracted from an infinite tree). In practice, these values will be determined at run time (when used as arguments to a special function [...]), but once fixed will never change.

...“a special function”: only one? More will definitely be needed! To keep matters simple, each value shall only be used once (if at all) as an argument to any such function.

main' :: Tree Exterior -> ...

 -- section 2
data Tree a = Node { contents :: a,
                     left     :: Tree a,
                     right    :: Tree a }

data Exterior                      -- the abstract value type
getchar :: Exterior -> Char        -- the special functions
putchar :: Char -> Exterior -> ()  -- (add more as needed :-)

Avoiding gratuitous repetition:

type OI  =  Tree Exterior

getChar' :: OI -> Char
getChar' =  getchar . contents

putChar' :: Char -> OI -> ()
putChar' c = putchar c . contents

An alternative abstraction

About those trees: are they really necessary? If OI was an abstract data type, the use of trees could at least be confined to the implementation:

data OI
getChar' :: OI -> Char
putChar' :: Char -> OI -> ()

...provided that single-use property applies directly to OI values (thereby deeming “special” any function which uses an OI argument). That includes the initial OI value supplied to each program:

main' :: OI -> ...

But most Haskell programs will need more:

part    :: OI -> (OI, OI)
part t  =  (left t, right t)

...than two OI values:

parts   :: OI -> [OI]
parts t =  let (t1, t2) = part t in t1 : parts t2

So OI can be a tree-free abstract data type after all:

data OI
partOI  :: OI -> (OI, OI)
getChar :: OI -> Char
putChar :: Char -> OI -> ()


Other interfaces

type M a   =  OI -> a

unit       :: a -> M a
unit x     =  \ u -> let !_ = partOI u in x 

bind       :: M a -> (a -> M b) -> M b
bind m k   =  \ u -> let !(u1, u2) = partOI u in
                     let !x = m u1 in
                     let !y = k x u2 in
                     y

getcharM   :: M Char
getcharM   =  getChar

putcharM   :: Char -> M () 
putcharM   =  putChar
type C a         =  (OI, a)

extract          :: C a -> a
extract (u, x)   =  let !_ = partOI u in x

duplicate        :: C a -> C (C a)
duplicate (u, x) =  let !(u1, u2) = partOI u in
                    (u2, (u1, x))

extend           :: (C a -> b) -> C a -> C b
extend h (u, x)  =  let !(u1, u2) = partOI u in
                    let !y        = h (u1, x) in
                    (u2, y)

getcharC         :: C () -> Char
getcharC (u, ()) =  getChar u

putcharC         :: C Char -> ()
putcharC (u, c)  =  putChar c u
type A b c   =  (OI -> b) -> (OI -> c)

arr          :: (b -> c) -> A b c
arr f        =  \ c' u -> let !x = c' u in f x

both         :: A b c -> A b' c' -> A (b, b') (c, c')
f' `both` g' =  \ c' u -> let !(u1:u2:u3:_) = partsOI u in
                          let !(x, x')      = c' u1 in
                          let !y            = f' (unit x) u2 in
                          let !y'           = g' (unit x') u3 in
                          (y, y')
                where
                  unit x u = let !_ = partOI u in x

getcharA     :: A () Char
getcharA     =  \ c' u -> let !(u1, u2) = partOI u in
                          let !_        = c' u1 in
                          let !ch       = getChar u2 in
                          ch     

putcharA     :: A Char ()
putcharA     =  \ c' u -> let !(u1, u2) = partOI u in
                          let !ch       = c' u1 in
                          let !z        = putChar ch u2 in
                          z

The OI interface can also be used to implement I/O models used in earlier versions of Haskell:

  • dialogues:
runD :: ([Response] -> [Request]) -> OI -> ()
runD d u = foldr (\ (!_) -> id) () $ yet $ \ l -> zipWith respond (d l) (partsOI u)

yet :: (a -> a) -> a
yet f = f (yet f)

respond :: Request -> OI -> Response
respond Getq     u = let !c = getChar u in Getp c
respond (Putq c) u = let !_ = putChar c u in Putp

data Request  = Getq | Putq Char
data Response = Getp Char | Putp
  • continuations:
type Answer = OI -> ()

runK :: Answer -> OI -> ()
runK a u = a u

doneK :: Answer
doneK = \ u -> let !_ = partOI u in ()

getcharK :: (Char -> Answer) -> Answer
getcharK k   = \ u -> let !(u1, u2) = partOI u in
                      let !c        = getChar u1 in
                      let !a        = k c in
                      a u2

putcharK :: Char -> Answer -> Answer
putcharK c a = \ u -> let !(u1, u2) = partOI u in
                      let !_        = putChar c u1 in
                      a u2

...and even that world state-passing style used in GHC, which is also used by Clean, Single-Assignment C and as part of the I/O model used for the verification of interactive programs in CakeML, remembering that OI values can only be used once:

newtype World = W OI

getcharL :: World -> (Char, World)
getcharL (W u) = let !(u1, u2) = partOI u in
                 let !c = getChar u1 in
                 (c, W u2)

putcharL :: Char -> World -> World
putcharL c (W u) = let !(u1, u2) = partOI u in
                   let !_ = putChar c u1 in
                   W u2


See also