> main = putStr "Hello World\n"
x1
and x2
to be Int
).
> main = > hSetBuffering stdout NoBuffering >> > putStr "Enter an integer: " >> > readLine >>= \ x1 -> > putStr "Enter another integer: " >> > readLine >>= \ x2 -> > putStr ("Their sum is " ++ show (x1+x2) ++ "\n") > > where readLine = isEOF >>= \ eof -> > if eof then return [] > else getChar >>= \ c -> > if c `isIn` ['\n','\p'] then > return [] > else > readLine >>= \ cs -> > return (c:cs)
> main = getArgs >>= \ [f1,f2] -> > openFile f1 ReadMode >>= \ h1 -> > openFile f2 WriteMode >>= \ h2 -> > copyFile h1 h2 >> > hClose h1 >> > hClose h2
> copyFile h1 h2 = > hIsEOF h1 >>= \ eof -> > if eof > return () > else > hGetChar h1 >>= \ c -> > hPutChar h2 (toUpper c) >> > copyFile h1 h2
An equivalent but much shorter version, using string I/O is:
> main = getArgs >>= \ [f1,f2] -> > readFile f1 >>= \ s -> > writeFile f2 (map toUpper s)
Assume that opening the "file" "u@h"
will open a connection
to user u
at host h
(so
"kh@dcs.glasgow.ac.uk"
will open a connection to Kevin
Hammond at Glasgow), then the following is a simple communication
program that allows the user to communicate across the network.
> main = getArgs >>= \ [user,host] -> > let username = (user ++ "@" ++ host) in > openFile username ReadWriteMode >>= \ cd -> > hSetBuffering NoBuffering stdin >> > hSetBuffering NoBuffering stdout >> > hSetBuffering NoBuffering cd >> > hPutString speakString >> > speak cd > > speakString = "Someone wants to speak with you"
> speak cd = > hReady cd >>= \ ready -> > if ready then (hGetChar cd >>= putChar) > else return () >> > > hReady stdin >>= \ ready -> > if ready then (getChar >>= hPutChar cd) > else return () >> > > speak cd
Note the use of hReady
to allow interleaved
communication, and hSetBuffering
to disable buffered
input and output.
[Up]