Title here
Summary here
In Haskell, variables are introduced using binding expressions. Unlike many imperative languages, Haskell variables are immutable by default.
import System.IO (print)
main :: IO ()
main = do
-- Binding a value to a variable
let a = "initial"
print a
-- Multiple bindings can be introduced in a single let expression
let b = 1
c = 2
print (b, c)
-- Haskell infers types, but we can also provide explicit type annotations
let d :: Bool
d = True
print d
-- Variables in Haskell don't have a "zero value" concept.
-- Instead, we can use Maybe to represent potentially missing values
let e :: Maybe Int
e = Nothing
print e
-- In Haskell, all bindings are immutable by default
-- To simulate mutable state, we often use monads like IO
f <- return "apple"
print f
To run this program, save it as Variables.hs
and use runhaskell
:
$ runhaskell Variables.hs
"initial"
(1,2)
True
Nothing
"apple"
In Haskell:
let
expressions or at the top level.let
expression.Maybe
to represent potentially missing values.IO
.:=
syntax doesn’t exist in Haskell. All variable introductions use let
or are at the top level.Haskell’s approach to variables emphasizes immutability and strong typing, which can lead to more predictable and easier to reason about code, especially in larger programs.