Constants in Haskell
Constants in Haskell
Haskell supports constants of character, string, boolean, and numeric values.
Defining Constants
In Haskell, constants can be defined using the let
or where
clauses, but for simplicity, constants are usually defined at the top level using pattern matching.
-- Defining a constant value
s :: String
s = "constant"
main :: IO ()
main = do
putStrLn s
Defining Numeric Constants
A constant statement can appear anywhere a variable assignment can.
-- Defining a numeric constant
n :: Integer
n = 500000000
Arithmetic with Constants
Constant expressions in Haskell perform arithmetic with arbitrary precision.
-- Defining a constant with an arithmetic expression
d :: Double
d = 3e20 / fromIntegral n
main :: IO ()
main = do
putStrLn s
print d
Type Conversion
A numeric constant has no type until it’s given one, such as by an explicit conversion.
main :: IO ()
main = do
putStrLn s
print d
print (round d :: Int)
Context-Based Typing
A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. For example, here sin
expects a Floating
type.
main :: IO ()
main = do
putStrLn s
print d
print (round d :: Int)
print (sin (fromIntegral n :: Double))
To run the program, save the code in a file named constants.hs
and use runhaskell
to execute it.
$ runhaskell constants.hs
constant
6.0e11
600000000000
-0.28470407323754404
Now that we can run and build basic Haskell programs, let’s learn more about the language.