Reputation: 49
I want to read a string from keyboard but i don't know why isn't working, I tried a lot of methods, but nothing worked! Can someone help me or give me an idea?
type Polinom = [Int]
scriePolinom :: Polinom -> String
....
main = do
a<-getLine
--let a=[2,-5,1]
scriePolinom a
Upvotes: 0
Views: 2408
Reputation: 120711
GHCi, version 7.10.2: http://www.haskell.org/ghc/ :? for help
Prelude> :type getLine -- you can also write :t getLine
getLine :: IO String
This tells you that getLine
always gives you (after doing some kind of impure I/O operations, in this case waiting for the user to enter some stuff on the keyboard, until pressing enter) a value of type String
. Which makes sense: a string, also called...
Prelude> :info String -- you can also write :i String
type String = [Char] -- Defined in ‘GHC.Base’
...list of characters. These are just the exact characters/keys the user typed in. In general, these characters may not properly describe a Polinom
– what, for example, if the user enters 34958oiyq4ulbwre
?
What you need to do is trying to parse the input string to a more meaningfully-typed value, like Polinom
. How to do that depends on what form you actually expect the input to be. If the user should use normal Haskell syntax for the coefficients, e.g. [2, -5, 1]
, you can use the standard read
parser:
Prelude> scriePolinom (read "[2, -5, 1]")
"[2,-5,1]"
Or if, as Daniel Sanchez assumes, you expect just a sequence of space-separated numbers in decimal notation, you can first split up these numbers as words, then read each one individually:
Prelude> scriePolinom . map read $ words "2 -5 1"
"[2,-5,1]"
To use this in an executable program, you can use the ready-build combination of getLine
and read
:
main :: IO ()
main = do
a <- readLn
putStrLn $ scriePolinom a
Note that read
/readLn
are not robust with respect to malformed input (they're not total functions) – this will just crash the program unless you wrap it in explicit exception handling. For serious applications I recommend using a full-featured parsing library, such as megaparsec.
Upvotes: 1
Reputation: 42678
Parse the line into the corresponding data:
import Data.List
parseIntList :: String -> [Int]
parseIntList s = [read x :: Int | x <- words s]
type Polinom = [Int]
scriePolinom :: Polinom -> String
....
main = do
a <- getLine
let intlist = parseIntList a
putStrLn $ scriePolinom intlist
Upvotes: 1