Reputation: 1
In a project, I use a module containing global (constant once initialized) stuffs that I use in the rest of the project. I choose to put them into a module to avoid a lot of arguments passing. The problem is that this module have to be initialized at run-time with the argument of the program execution.
How could this be done in a functional paradigm, in a langage like Haskell for example ?
Edit:
To be more precise, I code my project in an imperative language (Ada), that's why I can use a module containing variables initialized at run-time, and then used as global constants (with inlined getter). However, being interested in functional programming, I wonder how to obtain the same result in this paradigm; I mean to have light signatures all over the rest of the code (using global constant), module data localized in the data section of memory, even be able to initialize different "constants" of the module separately, etc.
Upvotes: 0
Views: 212
Reputation: 61
Strictly speaking, it's not impossible so much as probably shouldn't be done.
import System.Environment
import System.IO.Unsafe
firstArg :: String
firstArg = head $ unsafePerformIO getArgs
{-# NOINLINE firstArg #-}
main = putStrLn firstArg
Please note how many times the word "unsafe" appears in that six line snippet.
It's dirty and gross, but IMO, there are a few valid uses cases of this paradigm, and global constant initialization is one of them. I use it to load level files in my games, for example.
Upvotes: 0
Reputation: 152707
If the behavior of your program depends on the arguments used on the command line, there is simply no way to hide that fact -- it will have to appear in the types of your program's components. The simplest way is to write
data Options = {- ... -}
doMyProgram :: Options -> IO ()
myModule'sConstantA :: Options -> A
myModule'sConstantB :: Options -> B
giving Options
as an argument to any operation or value which depends on it. Fancy designs often also define a custom monad M
for the program that includes a MonadReader Options M
instance to reduce the size of type signatures.
Upvotes: 4