Search code examples
listhaskelluser-inputio-monaddo-notation

Ask user for list input in Haskell


I found this code online, but it's not running.

main = do
 xs <- getLine []
print xs

So how do I ask the user for list input in Haskell? I am new to Haskell, please explain when you answer. Thanks.


Solution

  • You do it e.g. like this:

    main :: IO ()
    main = do
      xs <- getLine
      let { ints :: [Int] 
          ; ints = read xs 
          }
      print $ take 2 ints
      
    

    and you must type in the input in a valid list syntax, e.g.

    [1,2,3]
    

    Do take note, each line in a do-block must start at the same indentation level (unless explicit separators { ; } are used).