1

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.

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • There should be a new line after `getLine`, and that `[]` shouldn't be there. And make sure you line up the `p` of `print` with the `x` in `xs` – Robin Zigmond Mar 26 '19 at 18:31

2 Answers2

2

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).

Will Ness
  • 70,110
  • 9
  • 98
  • 181
1

getLine is an IO action that produces a string, nothing else. You need to process that string once you receive it. As an example, here's an IO action that will parse an appropriate input into a list of Int values.

getIntList :: IO [Int]
getIntList = fmap read getLine

main = do
         ints <- getIntList
         print ints

There is a Read instance for lists, so the following works:

> read "[1,2,3]" :: [Int]
[1,2,3]

getIntList uses the Functor instance for IO to apply read to the string that getLine will produce; read's concrete type will be inferred from the type given to getIntList: since getIntList :: IO [Int], then fmap read :: IO String -> IO [Int], and so read :: String -> [Int] will be used.

chepner
  • 497,756
  • 71
  • 530
  • 681