Haskell Cheat Sheet

Hello World:

        
main :: IO ()
main = do
    putStrLn "Hello, World!"
        
    

Variables and Functions:

        
-- Variables
x :: Int
x = 10

-- Functions
add :: Int -> Int -> Int
add a b = a + b

-- Function call
result :: Int
result = add 5 3
        
    

Lists:

        
-- List of Integers
numbers :: [Int]
numbers = [1, 2, 3, 4, 5]

-- List of Strings
names :: [String]
names = ["Alice", "Bob", "Charlie"]

-- List concatenation
combined :: [Int]
combined = numbers ++ [6, 7, 8]

-- Accessing elements
first :: Int
first = head numbers

-- List length
length :: Int
length = length numbers
        
    

Tuples:

        
-- Pair of Integers
pair :: (Int, Int)
pair = (10, 20)

-- Accessing elements
firstElement :: Int
firstElement = fst pair

secondElement :: Int
secondElement = snd pair
        
    

Pattern Matching:

        
-- Pattern matching in function definition
isZero :: Int -> Bool
isZero 0 = True
isZero _ = False

-- Pattern matching in case expression
getGrade :: Int -> String
getGrade grade =
    case grade of
        0 -> "F"
        1 -> "D"
        2 -> "C"
        3 -> "B"
        4 -> "A"
        _ -> "Invalid grade"
        
    

Recursion:

        
-- Factorial function
factorial :: Int -> Int
factorial 0 = 1
factorial n = n * factorial (n - 1)

-- Fibonacci function
fibonacci :: Int -> Int
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n - 1) + fibonacci (n - 2)
        
    

Type Declarations:

        
-- Custom data type
data Person = Person
    { name :: String
    , age :: Int
    }

-- Function using custom data type
greet :: Person -> String
greet person = "Hello, " ++ name person ++ "!"