Basics
4 snippetsGetting started with Haskell
Hello World
main :: IO ()
main = putStrLn "Hello, World!" Let / Where
-- let expression
result = let x = 10
y = 20
in x + y
-- where clause
bmi weight height = category
where
category
| index < 18.5 = "underweight"
| index < 25.0 = "normal"
| otherwise = "overweight"
index = weight / height ^ 2 Comments
-- Single line comment
{- Multi-line
comment -} Type Annotations
add :: Int -> Int -> Int
add x y = x + y
greeting :: String -> String
greeting name = "Hello, " ++ name Types
4 snippetsType system fundamentals
Basic Types
x :: Int -- Fixed-precision integer
y :: Integer -- Arbitrary-precision
z :: Double -- Floating point
b :: Bool -- True / False
c :: Char -- Single character
s :: String -- [Char] Maybe & Either
safeDivide :: Int -> Int -> Maybe Int
safeDivide _ 0 = Nothing
safeDivide a b = Just (a `div` b)
validate :: String -> Either String Int
validate s = case reads s of
[(n, "")] -> Right n
_ -> Left "Invalid number" Data Types
data Color = Red | Green | Blue
data Shape = Circle Double | Rectangle Double Double
area :: Shape -> Double
area (Circle r) = pi * r * r
area (Rectangle w h) = w * h Records
data Person = Person
{ firstName :: String
, lastName :: String
, age :: Int
} deriving (Show, Eq) Functions
4 snippetsPattern matching and higher-order
Pattern Matching
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
head' :: [a] -> a
head' (x:_) = x
head' [] = error "empty list" Guards
grade :: Int -> String
grade score
| score >= 90 = "A"
| score >= 80 = "B"
| score >= 70 = "C"
| otherwise = "F" Composition
-- (.) composes functions
shout :: String -> String
shout = map toUpper . filter isAlpha
-- ($) avoids parentheses
result = sum $ map (*2) $ filter even [1..10] Lambda & Higher-Order
double = map (\x -> x * 2) [1..5]
filtered = filter (>3) [1,2,3,4,5]
result = foldr (+) 0 [1..100] -- sum Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Lists
3 snippetsList operations and comprehensions
Operations
head [1,2,3] -- 1
tail [1,2,3] -- [2,3]
length [1,2,3] -- 3
[1,2] ++ [3,4] -- [1,2,3,4]
1 : [2,3] -- [1,2,3]
reverse [1,2,3] -- [3,2,1] Comprehension
[x * 2 | x <- [1..10], even x]
-- [4,8,12,16,20]
pairs = [(x,y) | x <- [1..3], y <- [1..3], x /= y] Map / Filter / Fold
map (+1) [1,2,3] -- [2,3,4]
filter even [1..10] -- [2,4,6,8,10]
foldl (+) 0 [1..5] -- 15
zip [1,2] ["a","b"] -- [(1,"a"),(2,"b")]
take 3 [1..] -- [1,2,3] Monads & IO
3 snippetsdo notation and monadic operations
do Notation
main :: IO ()
main = do
putStrLn "What's your name?"
name <- getLine
putStrLn ("Hello, " ++ name) Maybe Monad
lookup' :: String -> [(String, Int)] -> Maybe Int
lookup' key pairs = do
value <- lookup key pairs
guard (value > 0)
return (value * 2) >>= (bind)
-- Without do notation
main = getLine >>= \name -> putStrLn ("Hello, " ++ name)
-- Chain operations
result = Just 5 >>= \x -> Just (x + 1) >>= \y -> Just (y * 2)