Reading stdin in ghci on Linux is broken - linux

Comming from Windows, I have recently installed linux distribution named Peppermint and Haskell-Platform via bash (ghc 7.10) but there must be something wrong with ghci stdin in ghci because :
interact $ take 0
throws an error but
interact $ take 1
does not.
Furthermore, if I use backspace, arrows or any other control button when writing into stdin, it enters the char symbol. For example backspace enters ^? into ghci instead of deleting the last char typed...
...#... ~ $ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for help
Prelude> interact $ take 0
Prelude>
<stdin>: hGetChar: illegal operation (handle is closed)
...#... ~ $ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for help
Prelude> readLn :: IO String
euoe^?^?^[[1;5C^[[D^[[B -- here I tried to delete 'euoe'

Regarding the control code literals, this is because you've managed to escape all of the line editors (readline, Haskeline) that would usually interpret your key presses.
I don't know the particulars, but invoking GHCi is something like starting a subshell with bash --noediting. This allows GHCi to receive raw key presses without interference from the readline library. This is done because Haskeline—which GHCi uses in place of readline—can be configured with things like tab completion for available functions more easily (you knew GHCi provided tab completion, right?).
Calling getLine from GHCi then effectively drops through a trap door and dodges Haskeline completely by going straight to stdin. There is, after all, only one stdin. You're now typing directly into an unbuffered terminal.
Getting back to your first concern, there being only one stdin is also why GHCi immediately keels over after printing the Prelude> prompt. interact (which uses hGetContents behind the scenes) claims that it will address all of the input that will ever come through the handle (stdin) as one big lazy String. Effectively there can be no remaining input on the handle that interact hasn't already claimed to deal with, so the handle is immediately put into a “semi-closed” state. It's not closed (there could still be more input that will be read as part of that lazy String interact gets!) but it is closed to any newcomers, otherwise input would get duplicated (interact and new readers of the handle such as getLine would get the same line!).
Back to GHCi, after having used interact, stdout is still fine so the prompt gets printed as usual, then GHCi leans on Haskeline to return a line for processing. Haskeline (as a line editor) calls a blocking getChar (iirc) to either add a character to the line or perform some line editing command and dies because it's addressing a semi-closed handle. Thus a weaker creature does fall and the great wheel of life rolls on.

Related

Haskell does not return from getLine

For some reason, Haskell on my machine does never return from any getLine call. For instance, I tried to run the following code straight from Learn You a Haskell for Great Good:
main = do
putStrLn "Hello, what's your name?"
name <- getLine
putStrLn ("Hey " ++ name ++ ", you rock!")
When I run it, the first line is printed, and I see my input when I type a name, however when I press Enter the program just blocks there and never prints the final line.
How should I fix this?
edit: I am running it from the Sublime IDE, maybe that has something to do with it
After doing a quick search on how Sublime runs programs, I found a youtube video (edit: and this SO post) which says that Sublime's "run program" functionality can only show output and isn't capable of reading input.
So it looks like you'll have to run your program from the command line or from within GHCi using :main. The latter might be the most convenient as Sublime actually supports a GHCi tab, so you can still do everything from within Sublime.
This seems to be a limitation in Sublime's Build command (assuming that this is what you're using).
Sublime executes the script using runhaskell, but apparently, it doesn't capture STDIN (which makes kind of sense - build results are usually read-only and not an interactive session).
Workaround: run your script from the command line with
runhaskell script.hs
and everything works as expected

GHCi and compiled code seem to behave differently

I have a very strange problem. The following code gives different results when compiled as compared to running in ghci,
main = do
putStr "Please enter your name: "
name <- getLine
putStr ("Hello, " ++ name ++ ", how are you?")
When run it in ghci it does as one would expect,
Please enter your name: dglmoore
Hello, dglmoore, how are you?
However, when I compile the code to an executable it requires that I provide the input before any output is generated so I end up with this,
dglmoore
Please enter your name: Hello, dglmoore, how are you?
I've seen a similar problem before, but I cannot seem to find it again.
I am using ghc version 7.4.1 from the Haskell Platform version 2012.2.0.0.
Anyone have any idea why they give different results and how I can get both versions to do the "correct" thing?
It's a buffering issue. Usually IO is line buffered (i.e. the output doesn't actually show up on the screen until you print a new line or exceed the buffer size) unless you explicitly flush the buffer. In ghci it isn't, so the issue doesn't show up.
You can use hFlush stdout to flush stdout, causing the output to be printed to the screen, before you call getLine.
Alternatively you can use hSetBuffering NoBuffering to disable buffering altogether, removing the need for hFlush. That could have a negative impact on IO performance though.

How can I get input right when it is typed in Haskell?

I have written a Brainfuck interpreter in Haskell, but it only operates on the input once I hit Ctrl-D to signal EOF. How can I make the program act on each character when it is typed?
Here is the source. To use the program, give a file to interpret as an argument or type your program in the first line of stdin.
It sounds like your input is being buffered. You can modify the buffering mode of a file handle with System.IO.hSetBuffering. If you are reading from standard input, for instance, then you could disable buffering with:
import System.IO
hSetBuffering stdin NoBuffering
getLine waits for a newline character to be typed (\n), because what if the user typed a bunch of characters, but never pressed enter? Then it would be an error if some of the "line" had already be processed, if that "line" wasn't a line after all.
You should use getContents instead which will return everything that is typed at the terminal.
Also, you are using the following line:
then hGetContents =<< openFile (head args) ReadMode
This will open a file and never close it. This is fine for your short program, but it might be a better idea for the future to get used to doing this:
then readFile $ head args

Evaluate buffer in ghci or hugs via Emacs

Using sml-mode in Emacs I have been able to send my buffer contents directly to an inferior SML process using C-c C-b. Now I want to do the same thing only with Haskell. Haskell-mode does not seem to support this, so I'm wondering: What is the right way to go about this with Emacs and Haskell?
While learning SML I've been using C-c C-b almost non-stop to easily evaluate my program as I go, instantly seeing the results of assigning values etc. But if I use C-c C-l in haskell-mode on a saved file containing two lines, let foo = "foo" and let bar = "bar" - I get "parse error (possibly incorrect indentation)"
I think you are making a common rookie mistake, confusing what you can write inside the repl of ghci and what you write in a haskell source file.
All sml interpreters are made in such a way that you can write any top level declaration into the repl, or put in other words: anything you can write in an sml file, you can write into the sml interpreter. Thus you are allowed to write val foo = "bar" into a file and use C-c C-b to load the file and you are allowed to just put in val foo = "bar" into the interpreter.
On the other hand, because of how haskell work, you can write let foo = 42 into ghci, however it is not a valid top level declaration and thus this can't be in a haskell source file (by it self). On the other hand you can have id n = n in a haskell source file and use C-c C-l to load the file, however you can't write this directly into ghci (you will get an error: :1:6: parse error on input '='). The reason for this is that the repl in ghci runs in the IO monad, and thus what ever you write into ghci must be done using the do notation. I can only recommend that you read Interactive evaluation at the prompt from the Using GHCi user guide.
C-c C-b in sml-mode is the exact same thing as C-c C-l in haskell-mode, well atleast conceptually. I don't know that much about the internals of haskell-mode, but in sml-mode C-c C-b executes some sml code in the interpreter, normally the use(...) function. In haskell-mode it seems to just excute the :load "..." ghci command
You can't do that with ghci (or hugs) for the simple reason that you can't write top-level definitions in ghci (or hugs). So even if you manually pasted your file's contents into ghci, all you'd get would be a syntax error.
So loading a file using C-c C-l is the best you can do.

Emacs hangs in haskell-mode with inferior-haskell-load-file call

When in a Haskell file, I use C-c C-l to run the command inferior-haskell-load-file which is intended to load the current file into the GHCI interpreter but Emacs just hangs until I hit C-g. Anyone know how I can get this to work?
GNU Emacs 23.3.1 (x86_64-pc-linux-gnu, GTK+ Version 2.24.5) of 2011-08-14 on allspice, modified by Debian
Using haskell-mode version v2.7.0
inferior-haskell-mode does some parsing based upon the expected ghci prompt. As such, if you change the prompt in a .ghci file, then it can't detect it.
For more information, see where haskell-ghci.el sets the comint-prompt-regexp value to determine what a prompt is.
;; GHCi prompt should be of the form `ModuleName> '.
(setq comint-prompt-regexp
"^\\*?[[:upper:]][\\._[:alnum:]]*\\( \\*?[[:upper:]][\\._[:alnum:]]*\\)*> ")
If you want to keep the setting in your .ghci file, then it may be possible to customise this settings.
Old question, but as I just ran into this today, I wanted to share how to actually customize comint-prompt-regexp since I had to figure it out.
This customization will recognize λ> prompts, or actually any single character before >), but it doesn't break the existing regex. In your .emacs:
(load-library "inf-haskell")
(defun my-inf-haskell-hook ()
(setq comint-prompt-regexp
(concat comint-prompt-regexp "\\|^.> ")))
(add-to-list 'inferior-haskell-mode-hook 'my-inf-haskell-hook)
You can add more dots to "\\|^.> " to recognize a longer prompt, but I wanted to keep it fixed-length for simplicity.
I had a similar problem caused by GHCi reporting some kind of error on startup, causing the Emacs haskell mode to wait for the GHCi prompt indefinitely (GHCi didn't show the standard prompt (Prelude>), but rather just showed >). You can try running GHCi externally and see if it reports any errors.
I got the same error message when I tried to use stack with emacs. For me, adding this line to my .emacs/init.el resolved the problem:
(setq haskell-program-name "stack ghci")

Resources