Variables in Haskell

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:

  1. Variables are introduced using let expressions or at the top level.
  2. Multiple bindings can be introduced in a single let expression.
  3. Haskell uses type inference, but explicit type annotations can be provided.
  4. There’s no direct equivalent to Go’s zero values. Instead, Haskell often uses Maybe to represent potentially missing values.
  5. All bindings are immutable by default. To simulate mutable state, Haskell often uses monadic structures like IO.
  6. The := 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.