Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

haskell - Simulate global variable

I'm working on a project in Haskell and I need a global variable. Currently I'm doing this:

 funcs :: Map.Map String Double
 funcs = Map.empty

 eliminate :: Maybe a -> a
 eliminate (Just a) = a

 insert :: String -> Double -> Map.Map String Double -> Map.Map String Double
 insert key value cache = Map.insert key value cache

 f = do

                 let aux = insert "aaa" 1 funcs
                 let funcs = aux
                 .........


 g = do
        if (Map.lookup "aaa" funcs) == Nothing then error "not defined" else putStr "ok"

The problem is that always g function throw error. Do you know how can I simulate a global variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

With let funcs = aux you're only giving funcs a new binding in the scope of the f function, which means that the funcs you're referring to in g is the one in the global scope - the one that's defined as Map.empty. It is not possible to change pure values, global or otherwise, at runtime. It is, however, possible to use mutable references. Preferrably locally, but also globally with a bit of unsafe hackery.

Is it really necessary to use a global variable though? If you're not using your global throughout your entire program, you may want to wrap all the computations that use it in a State monad instead:

import Control.Monad.State
import qualified Data.Map as Map

funcs :: Map.Map String Double
funcs = Map.empty

f :: String -> Double -> State (Map.Map String Double) ()
f str d = do
  funcs <- get
  put (Map.insert str d funcs)

g :: State (Map.Map String Double) String
g = do
  funcs <- get
  if (Map.lookup "aaa" funcs) == Nothing then return "not defined" else return "ok"

main = putStrLn $ flip evalState funcs $ do {f "aaa" 1; g}

Keeping your state constrained in this way makes it easier to keep track of your program as it grows; you always know which computations may alter your state as it's clearly indicated by its type.

If, on the other hand, you for some reason absolutely need global variables, there is a well-known but fairly ugly trick using IORefs and unsafePerformIO:

import Data.IORef
import System.IO.Unsafe
import qualified Data.Map as Map

{-# NOINLINE funcs #-}
funcs :: IORef (Map.Map String Double)
funcs = unsafePerformIO $ newIORef Map.empty

f :: String -> Double -> IO ()
f str d = atomicModifyIORef funcs (m -> (Map.insert str d m, ()))

g :: IO ()
g = do
  fs <- readIORef funcs
  if (Map.lookup "aaa" fs) == Nothing then error "not defined" else putStrLn "ok"

main = do
  f "aaa" 1
  g

This trick creates a global IORef, which can be read and updated inside the IO monad. This means that any computation that performs IO may change the value of your global, which gives you all the wonderful headaches of global state. Aside from that, this trick is also extremely hacky and only works because of implementation details in GHC (see the {-# NOINLINE funcs #-} part, for instance).

If you decide to use this hack (which I really recommend against), keep in mind that you can absolutely not use it with polymorphic values. To illustrate why:

import Data.IORef
import System.IO.Unsafe

{-# NOINLINE danger #-}
danger :: IORef a
danger = unsafePerformIO $ newIORef undefined

coerce :: a -> IO b
coerce x = do
  writeIORef danger x
  readIORef danger

main = do
  x <- coerce (0 :: Integer) :: IO (Double, String) -- boom!
  print x

As you can see, this trick can be used together with polymorphism to write a function that reinterprets any type as any other type, which obviously breaks type safety and so may cause your programs to segfault (at best).

In summary, do consider using the State monad instead of global variables; do not turn to global variables lightly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...