So I'm trying to print out a line of text to the terminal window using a returned value in a compiled code. The program looks like this:
module Main
where
import System.IO
main = do
askForWords
askForWords = do
putStrLn "Pleas enter a word:"
word <- getLine
if word == ""
then return []
else do
rest <- askForWords
return (word ++ " " ++ rest)
When I run it in the GHCi it works fine
*Main> main
Pleas enter a word:
Hello
Pleas enter a word:
World
Pleas enter a word:
"Hello World "
*Main>
When I try to run the Unix executable file the program don't print the last string
% /Users/tobyone/Workspace/Haskell/yaht/Yaht ; exit;
Pleas enter a word:
Hello
Pleas enter a word:
World
Pleas enter a word:
[Process completed]
I have tried printing out askForWords
in main with putStrLn
but get the error
<interactive>:2:10: error:
Couldn't match type ‘IO [Char]’ with ‘[Char]’
...
...
You aren't printing the output, you are only returning it. Your executable effectively ignores the return value of the main
, which conventionally has type IO ()
to emphasize this.
module Main
where
import System.IO
main = do
result <- askForWords
putStrLn result
askForWords = do
putStrLn "Pleas enter a word:"
word <- getLine
if word == ""
then return []
else do
rest <- askForWords
return (word ++ " " ++ rest)
In GHCi (like REPLs in most languages), the value of an expression is printed to the terminal.
main
could also be defined more simply as
main = askForWords >>= putStrLn