Haskell Overview
Haskell is a standardized, general-purpose purely functional programming language with non-strict semantics and strong static typing. It is named after logician Haskell Curry. Haskell features lazy evaluation, pattern matching, list comprehension, type classes and type polymorphism.
Key Features
- Pure Functional: No side effects, same input always gives same output.
- Lazy Evaluation: Expressions are evaluated only when needed. Strong Static Typing: Type errors caught at compile time.
- Type Inference: Compiler can deduce types automatically.
- Pattern Matching: Powerful way to destructure data.
- Higher-Order Functions: Functions can take functions as arguments.
- Monads: Elegant way to handle side effects.
Common Use Cases
Academic Research
Teaching functional programming concepts.
Compiler Design
Implementing programming languages.
Financial Modeling
Where correctness is critical.
Blockchain Development
Used in projects like Cardano.
Example Code
-- Haskell example demonstrating features
-- Data type declaration
data Person = Person { name :: String, age :: Int }
-- Type class instance
instance Show Person where
show p = name p ++ " is " ++ show (age p) ++ " years old"
-- Function with pattern matching
greet :: Person -> String
greet (Person n a) = "Hello, " ++ n ++ "!"
-- Higher-order function
map' :: (a -> b) -> [a] -> [b]
map' _ [] = []
map' f (x:xs) = f x : map' f xs
-- Using the examples
main :: IO ()
main = do
let alice = Person "Alice" 30
putStrLn (greet alice)
putStrLn (show alice)
-- List comprehension
let squares = [x^2 | x <- [1..5]]
putStrLn ("Squares: " ++ show squares)
-- Function composition
let shout = map toUpper . greet
putStrLn (shout alice)
-- Lazy infinite list
let fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
putStrLn ("First 10 Fibonacci numbers: " ++ show (take 10 fibs))
-- Maybe monad for error handling
safeDivide :: Float -> Float -> Maybe Float
safeDivide _ 0 = Nothing
safeDivide x y = Just (x / y)
divideExample :: Float -> Float -> String
divideExample x y = case safeDivide x y of
Nothing -> "Cannot divide by zero"
Just result -> "Result: " ++ show result