Haskell: How to parse an IO input string into a Fl

2019-03-24 16:05发布

问题:

I am trying to make a program that takes a Float number inputted by the user via keyboard and does stuff with it.

However every time I try to parse the inputted String into a Float I keep getting errors. Every single method I've tried has failed to allow me to take user inputted data and turn it into a Float, which is what I need.

My practice program (not the actual problem I'm trying to solve) is:

main = do
    putStrLn "Please input a number."
    inputjar <- getLine
    read :: read a => String -> a
    putStrLn( read inputjar :: Int)

Edit

A further question.

How do I take the inputted string and turn it into something I can use in a calculation?

For example, how do I take the inputted string so that I can do something like:

(var + var) / 2

回答1:

main = do
   putStrLn "Please input a number."
   inputjar <- readLn
   print (inputjar :: Int)

This is in a way nicer since it immediately fixes what we're reading the string as:

main = do
   putStrLn "Please input a number."
   inputjar :: Int  <- readLn
   print inputjar

but it requires {-#LANGUAGE ScopedTypeVariables#-}



回答2:

You say (read inputjar :: Int) in your code, but you're telling us that you want to read a Float. You are not defining read, take that line out. You use putStrLn so that you can print out the float, but putStrLn takes a String, so you need to show the value.

main = do
    putStrLn "Please input a number."
    inputjar <- getLine
    putStrLn $ show (read inputjar :: Float)


回答3:

putStrLn prints out Strings, not Ints, so there are two solutions:

Use print, which prints anything that implements Show:

main = do
    putStrLn "Please input a number."
    inputjar <- getLine
    let n = read inputjar :: Int
    print n

.. or call putStrLn on the original String that you read in

main = do
    putStrLn "Please input a number."
    inputjar <- getLine
    let n = read inputjar :: Int
    putStrLn inputjar

In the latter example n is never used, but presumably you would write some code after that which would actually use it.



回答4:

Well I guess the

read :: read a => String -> a

is there just by mistake?

Anyway, under ghci, :t putStrLn shows:

putStrLn :: String -> IO ()

So putStrLn only accepts String as its first parameter, so if you really want to:

putStrLn( show (read inputjar :: Int))

BTW, read inputjar :: int is correct, only your ouput is wrong.



回答5:

This worked for me

import System.IO

getNum :: IO Integer 
getNum = readLn 

--call function like this
something <- getNum
--something is type Integer