Haskell
Online Haskell Compiler
main.hs is compiled with GHC 9.12 and runs from main. Output is line-buffered, so a putStrLn line shows before getLine waits for your input; text printed with putStr needs hFlush stdout first.
Try it aboveHow Haskell runs here
- Versions
- GHC 9.12
- Build
ghc -O0 main.hs- Run
./a.out- Limits per run
- 512 MB memory, 15 s of CPU time on half a core, 2 MB of output
- Time
- Up to 10 minutes a run (30 on a paid plan); waits 2 minutes for input (5 on a paid plan)
- Sandbox
- Each run gets its own Linux sandbox with no network access. Text files your program writes next to your code open as new tabs.
A Haskell program that reads input
This main.hs reads words with a small prompt helper and counts them with Data.Map:
import qualified Data.Map.Strict as Map import Data.List (sortOn) import System.IO (hFlush, stdout) prompt :: String -> IO String prompt text = putStr text >> hFlush stdout >> getLine main :: IO () main = do n <- read <$> prompt "How many words? " ws <- mapM (\i -> prompt ("Word " ++ show i ++ ": ")) [1 .. n :: Int] let counts = Map.fromListWith (+) [(w, 1 :: Int) | w <- ws] mapM_ (\(w, c) -> putStrLn (w ++ " " ++ show c)) (sortOn (negate . snd) (Map.toList counts))
$ ghc -O0 main.hs && ./a.out How many words? 4 Word 1: tea Word 2: milk Word 3: tea Word 4: coffee tea 2 coffee 1 milk 1
Reading input in Haskell
- getLine reads a line; read converts it, and readLn does both. For several numbers on one line: map read . words <$> getLine.
- interact and getContents read lazily until the end of input, which this terminal never sends, so a program built on them never finishes. Read a count first, or stop on an empty line.
- putStr "Name: " without hFlush stdout shows only after the input. putStrLn needs no flush.
What isn’t available here
- Hackage packages. There’s no cabal or stack and no network, so random, vector, split and aeson are out. The libraries that ship with GHC are there: base, containers, text, bytestring, array, mtl, transformers and directory.
- GHCi. The file is compiled (with -O0) and run; there’s no prompt to evaluate expressions.
Errors you’ll see
- Variable not in scope: a typo, or a function from a module you didn’t import.
- Could not find module ‘System.Random’: the random package isn’t installed. Write a small linear congruential generator, or use a fixed list.
- “Prelude.read: no parse” read got text that isn’t a value of the type you asked for, such as "3 4" read as an Int.
Questions
Which GHC version does this use?
GHC 9.12. Programs are compiled with -O0 and run as a native binary.
Is Data.Map available?
Yes. containers ships with GHC, so Data.Map, Data.Set and Data.IntMap import normally.
How do I read input in Haskell online?
n <- readLn :: IO Int for one number, or line <- getLine for text. Type the input in the terminal while the program runs.