Main Points of Haskell Functional programming Laziness Purity (i.e. no side effects)
Main Points of Haskell Functional programming No states. Just values. No commands. Just math functions and declarations. x = 1 Imperative: assignment Functional: declaration
Main Points of Haskell Functional programming if … then … else Imperative: if <Bool> then <Commands> else <Commands> Functional: if <Bool> then <Value> else <Value> “if” can be viewed as a function: if :: Bool -> a -> a -> a if-then-else is just a syntactic sugar.
Main Points of Haskell Functional programming “Pure” math functions. Not procedures. Transform inputs to outputs. No side effects.
Main Points of Haskell Functional programming No loops. Use recursion instead. Why? Recursion: define sth using itself To solve a problem on recursively-defined data (e.g. a list, a tree), think of a recursive solution
Main Points of Haskell Functional programming No states. Just values. No commands. Just “pure” math functions and declarations. Not procedures. Laziness (i.e. call-by-need) Purity (i.e. no side effects)
Main Points of Haskell Laziness: Evaluation of function arguments is delayed as long as possible f x y = x + 2 f 5 (22^3579): 22^3579 will not be evaluated When to evaluate an argument expression?
Main Points of Haskell Laziness: Argument expressions are only evaluated when pattern-matched data Maybe = Nothing | Just Int f1 :: Maybe -> [Maybe] f1 m = [m, m] f2 :: Maybe -> [Int] f2 Nothing = [] f2 (Just x) = [x] Both f1 and f2 “uses” the argument. But for f1 m, m can remain unevaluated.
Main Points of Haskell Laziness: Argument expressions are only evaluated when pattern-matched Only as far as necessary for the match to proceed, and no farther! f2 Nothing = [] f2 (Just x) = [x] f2 (safeHead [3^500, 2]): f2 will force the evaluation of the call to (safeHead [3^500, 2]), which’ll evaluate to (Just 3^500) Whether the 3^500 gets evaluated later depends on how the result of f2 is used.
Main Points of Haskell Purity (no side effects) Side effects: anything that causes evaluation of an expression to interact with something outside itself. The issue: those effects are time-sensitive. E.g. Modifying a global variable Printing to the screen Reading from a file
Main Points of Haskell Laziness forces purity Lazy evaluation makes it hard to reason about when things will be evaluated But sides effects are time-sensitive Hence including side effects in a lazy language would be extremely unintuitive f (print(“hello”), print(“bye”)) Eager languages should specify the evaluation order, otherwise it will be confusing
Main Points of Haskell Functional programming Laziness Purity (i.e. no side effects)