2 ms·
As a concrete example, there's a nice function in Haskell's standard library called `interact :: (String -> String) -> IO ()`: https://hackage.haskell.org/packa
by chriswarbo 6y ago
As a concrete example, there's a nice function in Haskell's standard library called `interact :: (String -> String) -> IO ()`:
https://hackage.haskell.org/package/base-4.14.1.0/docs/Prelude.html#v:interact https://hackage.haskell.org/package/base-4.14.1.0/docs/Prelu...
Its argument is a function of type `String -> String` and it returns an `IO ()`, i.e. an i/o action with a trivial result. That action will call the given function on contents of stdin, and writes its result to stdout. Or, equivalently, we can think of `interact f` as transforming a pure string-processing function `f` into a stdio CLI.
Note that laziness (specifically "lazy IO") causes stdin to be read 'on demand', giving us a streaming computation without any extra work. Here's an example implementation of 'wc':
module Main where
import System.IO
main :: IO ()
main = interact count
count :: String -> String
count input = show (length (unwords input))
Bonus: if we want to show off, we could implement 'count' using function composition like this:
count = show . length . unwords