[Haskell-beginners] Use of interact
Francesco Ariis
fa-ml at ariis.it
Sun Feb 10 16:39:09 UTC 2019
Ciao Michele,
On Sun, Feb 10, 2019 at 05:10:13PM +0100, Michele Alzetta wrote:
> If I leave my hello_worlds function as is and change the main function as
> follows:
>
> main = interact $ show . hello_worlds . read::Int
>
> I get: [...]
>
> helloworlds.hs:14:8-44: error:
> • Couldn't match expected type ‘Int’ with actual type ‘IO ()’
> • In the expression: interact $ show . hello_worlds . read :: Int
> In an equation for ‘main’:
> main = interact $ show . hello_worlds . read :: Int
Two facts:
- (.) is an operator which concatenates function
- to concatenate functions, input/outputs must match
So let's analyse this:
1. `read` has type `Read a => String -> a`
2. `hello_worlds` has type `Int -> IO ()`
3. `show` has type `Show a => a -> String`
and there is no way to convert `IO ()` to `String`. Remember that
hello_worlds does *not* return a series of Strings, but an IO action
(in this case, "blit something to screen")
Your `interact` example would function if written like this:
main = interact $ unlines . map (hello_pure . read) . lines
-- with `hello_pure :: Int -> String`
`lines` and `unlines` are there to keep input lazy for each line.
Do you think you can you fill-in "hello_pure" yourself?
-F
More information about the Beginners
mailing list