Max K
Max K

Reputation: 171

"Constants " in Haskell after start of the program

I have a keyboard input like unsafePerformIO $ entryGetText myTextEntry. How can I save this value like a "constant" (in data Type like this:

data SimuInfo = Information {
                massSaved:: Double 
                } deriving Show

) after the program starts. The only method I know to "save variables" is:

valuea::Int
valuea = 120

But this method just works, when the value is not define by the user.

Thanks in advance

Upvotes: 1

Views: 313

Answers (2)

asm
asm

Reputation: 8898

Values that are input from the user are not really constants. I think the usual way to handle this kind of configuration input is with a reader Monad.

import Control.Monad.Reader

-- type of our context, one double value.
-- This is not really necessary, you could just use Double everywhere
-- I use C.
newtype C = C Double
  deriving (Show, Eq)

main :: IO ()
main = do
  -- Read a double from the user.
  c <- getLine >>= return . read :: IO Double
  -- Run the computation, given a context/configuration with
  -- the user input.
  print  $ runReader foo (C c)

-- Computation dependent on our context.
foo :: Reader C Double
foo = do
  C x <- ask -- Get the value of our context.
  return $ x + 10 --  and use it

Upvotes: 0

Chad Gilbert
Chad Gilbert

Reputation: 36375

unsafePerformIO should be avoided at all costs, as its execution is unpredictable.

Haskell is a pure language and values are immutable, so you won't be able to "save" a value that will show as mutated elsewhere.

Instead, you'll need to read the value in and pass it around as needed.

main = do  
    putStrLn "Enter the default massSaved value"  
    val <- getLine
    doThingsWithDefaultSimuInfo (Information (read val :: Double))

doThingsWithDefaultSimuInfo :: SimuInfo -> IO ()
doThingsWithDefaultSimuInfo si = do
    ...

(There are cleaner and more idiomatic ways to do this with Readers but I'm trying to keep this answer aimed at beginner-level)

Upvotes: 7

Related Questions