Basics:
- Function Definition:
add :: Int -> Int -> Int
add x y = x + y
- Type Declarations:
name :: String
name = "John"
age :: Int
age = 25
- Lists:
numbers :: [Int]
numbers = [1, 2, 3, 4, 5]
strings :: [String]
strings = ["apple", "banana", "cherry"]
Pattern Matching:
- Matching on Values:
isZero :: Int -> Bool
isZero 0 = True
isZero _ = False
- Matching on Lists:
head' :: [a] -> a
head' (x:_) = x
head' [] = error "Empty list"
Higher-Order Functions:
- Map Function:
square :: Int -> Int
square x = x * x
squares :: [Int] -> [Int]
squares = map square
- Filter Function:
isEven :: Int -> Bool
isEven x = x `mod` 2 == 0
evens :: [Int] -> [Int]
evens = filter isEven
Lambda Expressions:
- Anonymous Function:
double :: Int -> Int
double = \x -> x * 2
Typeclasses:
- Defining Typeclasses:
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
- Implementing Instances:
instance Eq Bool where
True == True = True
False == False = True
_ == _ = False
Monads:
- Maybe Monad:
divide :: Double -> Double -> Maybe Double
divide _ 0 = Nothing
divide x y = Just (x / y)
IO Operations:
- Printing to Console:
main :: IO ()
main = putStrLn "Hello, Haskell!"
- Reading from Console:
main :: IO ()
main = do
putStrLn "What's your name?"
name <- getLine
putStrLn $ "Hello, " ++ name ++ "!"
This Haskell cheat sheet covers basic syntax, common constructs, and functional programming concepts. Haskell’s expressive and concise syntax makes it a powerful language for various applications, including mathematical modeling, compiler