I want to be able to read numbers from console input, and store them into a list until the user types end, like this:
readN = readNumbers []
readNumbers nums = do
n <- readFloatOrString
case n of
<<number>> -> return readNumbers (nums ++ [n])
"end" -> return nums
Is this doable without importing a library?
To check if the input string is an integer number, convert the user input to the integer type using the int() constructor. To check if the input is a float number, convert the user input to the float type using the float() constructor.
You can use the float() function to convert any data type into a floating-point number. This method only accepts one parameter. If you do not pass any argument, then the method returns 0.0. If the input string contains an argument outside the range of floating-point value, OverflowError will be generated.
C – Read Float using Scanf() So, to read a float number from console, give the format and argument to scanf() function as shown in the following code snippet. float n; scanf("%f", n); Here, %f is the format to read a float value and this float value is stored in variable n .
You should not read the value, or at least not immediately. You can first check if the line is "end"
, if so return the numbers, and otherwise continue reading:
import Text.Read(readMaybe)
readNumbers :: IO [Float]
readNumbers = do
n <- getLine
case (n, readMaybe n :: Maybe Float) of
("end", _) -> pure []
(_, Just n) -> (n:) <$> readNumbers
(_, Nothing) -> …
The …
is the part that should handle the case if you did not pass a valid float number.
We thus can process a list with:
Prelude Text.Read> readNumbers
1
4
end
[1.0,4.0]
(here the boldface part is user input).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With