Introduction to Haskell
Haskell is a purely functional programming language known for its strong static typing, lazy evaluation, and elegant syntax. It's widely used in academia and industry for its expressive power and mathematical foundations.
What is Functional Programming?
Functional programming is a paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. Key characteristics include:
- Pure functions: Same input always produces same output with no side effects
- Immutable data: Data cannot be modified after creation
- First-class functions: Functions can be passed as arguments and returned as values
- Recursion: Used for looping/iteration instead of imperative loops
Installing Haskell
The easiest way to install Haskell is using GHCup, which manages Haskell toolchain installations:
# On Linux/macOS
curl --proto '=https' --tlsv1.2 -sSf https://get-ghcup.haskell.org | sh
# On Windows (Powershell)
Set-ExecutionPolicy Bypass -Scope Process -Force
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072
Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Invoke-WebRequest https://www.haskell.org/ghcup/sh/bootstrap-haskell.ps1 -UseBasicParsing))) -ArgumentList $true
Your First Haskell Program
Create a file named hello.hs
with the following content:
-- This is a comment
main :: IO ()
main = putStrLn "Hello, World!"
Compile and run it with:
ghc hello.hs
./hello
Or run it directly with the interpreter:
runhaskell hello.hs
Basic Haskell Syntax
Here are some fundamental Haskell constructs:
-- Function definition
double :: Int -> Int
double x = x * 2
-- Conditional expression
absolute :: Int -> Int
absolute x = if x >= 0 then x else -x
-- List operations
numbers = [1, 2, 3, 4, 5]
squared = map (\x -> x * x) numbers
-- Recursive function
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)
Key Features of Haskell
- Lazy Evaluation: Expressions are not evaluated until their results are needed
- Type Inference: The compiler can often deduce types without explicit annotations
- Pattern Matching: Powerful way to deconstruct data and define functions
- Type Classes: Similar to interfaces in other languages, enabling polymorphism
- Monads: A structure that represents computations as a sequence of steps
Haskell Ecosystem
Haskell has a rich ecosystem of tools and libraries:
- GHC: Glasgow Haskell Compiler (the main Haskell compiler)
- Cabal: Package and build system
- Stack: Project development tool
- Hackage: Central package archive with thousands of libraries
- Hoogle: Haskell API search engine