Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: How to parse an IO input string into a Float (or Int or whatever)?

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
like image 657
Philip Eloy Avatar asked Jul 14 '12 05:07

Philip Eloy


People also ask

How do I convert a string to a float in Haskell?

The unary + operator converts its argument to a double precision floating point. String floatString = "14.5"; float x = Float. parseFloat(floatString); double y = Double. parseFloat(floatString);

How do I convert a string to an integer in Haskell?

int i = int. Parse(s);

What is io Haskell?

IO is the way how Haskell differentiates between code that is referentially transparent and code that is not. IO a is the type of an IO action that returns an a . You can think of an IO action as a piece of code with some effect on the real world that waits to get executed.


1 Answers

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#-}

like image 60
applicative Avatar answered Sep 30 '22 19:09

applicative