This presentation tries to give an understanding of a Functor, through the eyes of the Haskell programming language. We try to compare Javascript and Haskell, and try to understand Functors by understanding the power of types.
2. Imperative programming
• Serial execution of sequence of steps
• A global state of the program exists
• Each step may change the program state
3. // Javascript
1 function divBy(x) {
2 return 10 / x;
3 }
4
5 function triple(x) {
6 return x * 3;
7 }
8
9 function run(x) {
10 var a = divBy(x);
11 var b = triple(a);
12 return b;
13 }
4. Functional Programming
• Executed by evaluating expressions
• Typically Immutable
• Functions are first class
• Higher order functions
• FP focusses on the what rather than the how
5. -- Haskell
1
2 divBy x = 10 / x
3
4 triple x = x * 3
5
6 run x = triple (divBy x)
7. What is a type?
• A type is a property or a label
• Every expression has a type
• Types exist in a dynamic or static language
• Only understood by the compiler
8. var name = "Earnest";
console.log(typeof(name)); // => "string"
var age = 24;
console.log(typeof(age)); // "number"
Dynamic Typing
9. Types we use everyday
• Integer, Double
• Boolean
• Arrays
• Objects (dictionary or maps in some dynamic languages)
10. name :: String
name = "Earnest" -- :type name => String
age :: Integer
age = 42 -- :type age => Integer
Static Typing
13. // Javascript
1 function divBy(x) {
2 return 10 / x;
3 }
4
5 function triple(x) {
6 return x * 3;
7 }
8
9 function run(x) {
10 var a = divBy(x);
11 var b = triple(a);
12 return b;
13 }
Enforced by you
run(10)
=> 3
run(“10”)
=> 3
run(“hello”)
=> NaN
14. Enforced by the language
1 -- Haskell
2 divBy :: Double -> Double
3 divBy x = 10 / 2
4
5 triple :: Double -> Double
6 triple x = x * 3
7
8 run :: Double -> Double
9 run x = triple (divBy x)
run(10)
=> 3.0
=> <interactive>:8:5: error:
- Couldn't match expected type 'Double' with
actual type 'String'
- In the first argument of 'run', namely '("10"
)'
In the expression: run ("10")
In an equation for 'it': it = run ("10")
run("10")
15. Errors & Exceptions
"I call it my billion-dollar mistake. It was the invention
of the null reference in 1965."
– Tony Hoare, inventor of ALGOL W.
• Null pointer exception
• Divide by zero