0

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]’
    ...
    ...
2
  • 1
    How did you try to use putStrLn? It seems you did that wrong, but if you don't show your mistake we can't tell how to correct it. Commented Jul 7, 2020 at 0:21
  • 2
    GHCi performs some magic. When you write 1+2, it actualy runs print (1+2). When you write return (1+2) it actually runs do it <- return (1+2) ; print it. In your code, you run askForWords in your main, but silently discard its result. GHCi would have converted that to do it <- askForWords ; print it, but in a program you have to be explicit about that (and possibly use putStrLn instead of print). Commented Jul 7, 2020 at 8:51

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.