Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read float or string from user input

Tags:

haskell

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?

like image 845
tacofisher Avatar asked Jun 06 '20 17:06

tacofisher


People also ask

How do you check if input is float or string?

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.

How do you make a float input?

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.

How do you read float values?

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 .


1 Answers

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

like image 71
Willem Van Onsem Avatar answered Sep 20 '22 17:09

Willem Van Onsem