CodeToLive

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:

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

Haskell Ecosystem

Haskell has a rich ecosystem of tools and libraries:

Next: Functions & Recursion →