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