└── readme.md /readme.md: -------------------------------------------------------------------------------- 1 | # Functional Programming Jargon 2 | 3 | > The whole idea of this repos is to try and define jargon from combinatorics and category theory jargon that are used in functional programming in a easier fashion. 4 | 5 | *Let's try and define these with examples, this is a WIP—please feel free to send PR ;)* 6 | 7 | 8 | ## Arity 9 | 10 | > The number of arguments a function takes. From words like unary, binary, ternary, etc. This word has the distinction of being composed of two suffixes, "-ary" and "-ity." Addition, for example, takes two arguments, and so it is defined as a binary function or a function with an arity of two. Such a function may sometimes be called "dyadic" by people who prefer Greek roots to Latin. Likewise, a function that takes a variable number of arguments is called "variadic," whereas a binary function must be given two and only two arguments, currying and partial application notwithstanding (see below). 11 | 12 | ```js 13 | const sum = (a, b) => a + b; 14 | 15 | const arity = sum.length; 16 | console.log(arity); 17 | // => 2 18 | // The arity of sum is 2 19 | ``` 20 | --- 21 | 22 | ## Higher-Order Functions (HOF) 23 | 24 | > A function which takes a function as an argument and/or returns a function. 25 | 26 | ```js 27 | const filter = (pred, xs) => { 28 | const result = []; 29 | for (var idx = 0; idx < xs.length; idx += 1) { 30 | if (pred(xs[idx])) { 31 | result.push(xs[idx]); 32 | } 33 | } 34 | return result; 35 | }; 36 | ``` 37 | 38 | ```js 39 | const is = type => x => Object(x) instanceof type; 40 | ``` 41 | 42 | ```js 43 | filter(is(Number), [0, '1', 2, null]); //=> [0, 2] 44 | ``` 45 | 46 | ## Partial Application 47 | 48 | > The process of getting a function with lesser arity compared to the original 49 | function by fixing the number of arguments is known as partial application. 50 | 51 | ```js 52 | let sum = (a, b) => a + b; 53 | 54 | // partially applying `a` to `40` 55 | let partial = sum.bind(null, 40); 56 | 57 | // Invoking it with `b` 58 | partial(2); //=> 42 59 | ``` 60 | 61 | --- 62 | 63 | ## Currying 64 | 65 | > The process of converting a function with multiple arity into the same function with an arity of one. Not to be confused with partial application, which can produce a function with an arity greater than one. 66 | 67 | ```js 68 | let sum = (a, b) => a + b; 69 | 70 | let curriedSum = (a) => (b) => a + b; 71 | 72 | curriedSum(40)(2) // 42. 73 | ``` 74 | --- 75 | 76 | ## Composition 77 | 78 | > A function which combines two values of a given type (usually also some kind of functions) into a third value of the same type. 79 | 80 | The most straightforward type of composition is called "normal function composition". 81 | It allows you to combines functions that accept and return a single value. 82 | 83 | ```js 84 | const compose = (f, g) => a => f(g(a)) // Definition 85 | const floorAndToString = compose((val)=> val.toString(), Math.floor) //Usage 86 | floorAndToString(121.212121) // "121" 87 | 88 | ``` 89 | 90 | --- 91 | 92 | ## Purity 93 | 94 | > A function is said to be pure if the return value is only determined by its 95 | input values, without any side effects. 96 | 97 | ```js 98 | let greet = "yo"; 99 | 100 | greet.toUpperCase(); // YO; 101 | 102 | greet // yo; 103 | ``` 104 | 105 | As opposed to: 106 | 107 | ```js 108 | let numbers = [1, 2, 3]; 109 | 110 | numbers.splice(0); // [1, 2, 3] 111 | 112 | numbers // [] 113 | ``` 114 | 115 | --- 116 | 117 | ## Side effects 118 | 119 | > A function or expression is said to have a side effect if apart from returning a value, it modifies some state or has an observable interaction with external functions. 120 | 121 | ```js 122 | console.log("IO is a side effect!"); 123 | ``` 124 | --- 125 | 126 | ## Idempotency 127 | 128 | > A function is said to be idempotent if it has no side-effects on multiple 129 | executions with the the same input parameters. 130 | 131 | `f(f(x)) = f(x)` 132 | 133 | `Math.abs(Math.abs(10))` 134 | 135 | --- 136 | 137 | ## Point-Free Style 138 | 139 | > Writing functions where the definition does not explicitly define arguments. This style usually requires [currying](#currying) or other [Higher-Order functions](#higher-order-functions-hof). A.K.A Tacit programming. 140 | 141 | ```js 142 | // Given 143 | let map = fn => list => list.map(fn); 144 | let add = (a, b) => a + b; 145 | 146 | // Then 147 | 148 | // Not points-free - `numbers` is an explicit parameter 149 | let incrementAll = (numbers) => map(add(1))(numbers); 150 | 151 | // Points-free - The list is an implicit parameter 152 | let incrementAll2 = map(add(1)); 153 | ``` 154 | 155 | `incrementAll` identifies and uses the parameter `numbers`, so it is not points-free. `incrementAll2` is written just by combining functions and values, making no mention of its arguments. It __is__ points-free. 156 | 157 | Points-free function definitions look just like normal assignments without `function` or `=>`. 158 | 159 | --- 160 | 161 | ## Contracts 162 | 163 | --- 164 | 165 | ## Guarded Functions 166 | 167 | --- 168 | 169 | ## Categories 170 | 171 | > Objects with associated functions that adhere certain rules. E.g. [monoid](#monoid) 172 | 173 | --- 174 | 175 | ## Value 176 | 177 | > Any complex or primitive value that is used in the computation, including functions. Values in functional programming are assumed to be immutable. 178 | 179 | ```js 180 | 5 181 | Object.freeze({name: 'John', age: 30}) // The `freeze` function enforces immutability. 182 | (a) => a 183 | ``` 184 | Note that value-containing structures such as [Functor](#functor), [Monad](#monad) etc. are themselves values. This means, among other things, that they can be nested within each other. 185 | 186 | --- 187 | 188 | ## Constant 189 | 190 | > An immutable reference to a value. Not to be confused with `Variable` - a reference to a value which can at any point be updated to point to a different value. 191 | ```js 192 | const five = 5 193 | const john = {name: 'John', age: 30} 194 | ``` 195 | Constants are referentially transparent. That is, they can be replaced with the values that they represent without affecting the result. 196 | In other words with the above two constants the expression: 197 | 198 | ```js 199 | john.age + five === ({name: 'John', age: 30}).age + (5) 200 | 201 | ``` 202 | Should always return `true`. 203 | 204 | --- 205 | 206 | ## Functor 207 | 208 | > An object with a `map` function that adhere to certains rules. `Map` runs a function on values in an object and returns a new object. 209 | 210 | Simplest functor in javascript is an `Array` 211 | 212 | ```js 213 | [2,3,4].map( n => n * 2 ); // [4,6,8] 214 | ``` 215 | 216 | Let `func` be an object implementing a `map` function, and `f`, `g` be arbitrary functions, then `func` is said to be a functor if the map function adheres to the following rules: 217 | 218 | ```js 219 | func.map(x => x) == func 220 | ``` 221 | 222 | and 223 | 224 | ```js 225 | func.map(x => f(g(x))) == func.map(g).map(f) 226 | ``` 227 | 228 | We can now see that `Array` is a functor because it adheres to the functor rules! 229 | ```js 230 | [1, 2, 3].map(x => x); // = [1, 2, 3] 231 | ``` 232 | 233 | and 234 | ```js 235 | let f = x => x + 1; 236 | let g = x => x * 2; 237 | 238 | [1, 2, 3].map(x => f(g(x))); // = [3, 5, 7] 239 | [1, 2, 3].map(g).map(f); // = [3, 5, 7] 240 | ``` 241 | --- 242 | 243 | ## Pointed Functor 244 | > A functor with an `of` method. `Of` puts _any_ single value into a functor. 245 | 246 | Array Implementation: 247 | ```js 248 | Array.prototype.of = (v) => [v]; 249 | 250 | [].of(1) // [1] 251 | ``` 252 | 253 | --- 254 | 255 | ## Lift 256 | 257 | > Lift is like `map` except it can be applied to multiple functors. 258 | 259 | Map is the same as a lift over a one-argument function: 260 | 261 | ```js 262 | lift(n => n * 2)([2,3,4]); // [4,6,8] 263 | ``` 264 | Unlike map lift can be used to combine values from multiple arrays: 265 | ``` 266 | lift((a, b) => a * b)([1, 2], [3]); // [3, 6] 267 | ``` 268 | 269 | --- 270 | 271 | ## Referential Transparency 272 | 273 | > An expression that can be replaced with its value without changing the 274 | behavior of the program is said to be referentially transparent. 275 | 276 | Say we have function greet: 277 | 278 | ```js 279 | let greet = () => "Hello World!"; 280 | ``` 281 | 282 | Any invocation of `greet()` can be replaced with `Hello World!` hence greet is 283 | referentially transparent. 284 | 285 | --- 286 | 287 | ## Equational Reasoning 288 | 289 | > When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts. 290 | 291 | --- 292 | 293 | ## Lazy evaluation 294 | 295 | > Lazy evaluation is a call-by-need evaluation mechanism that delays the evaluation of an expression until its value is needed. In functional languages, this allows for structures like infinite lists, which would not normally be available in an imperative language where the sequencing of commands is significant. 296 | 297 | ```js 298 | let rand = function*() { 299 | while(1<2) { 300 | yield Math.random(); 301 | } 302 | } 303 | ``` 304 | ```js 305 | let randIter = rand(); 306 | randIter.next(); // Each exectuion gives a random value, expression is evluated on need. 307 | ``` 308 | --- 309 | 310 | ## Monoid 311 | 312 | > A monoid is some data type and a two parameter function that "combines" two values of the type, where an identity value that does not affect the result of the function also exists. 313 | 314 | One very simple monoid is numbers and addition: 315 | 316 | ```js 317 | 1 + 1; // 2 318 | ``` 319 | 320 | The data type is number and the function is `+`, the addition of two numbers. 321 | 322 | ```js 323 | 1 + 0; // 1 324 | ``` 325 | 326 | The identity value is `0` - adding `0` to any number will not change it. 327 | 328 | For something to be a monoid, it's also required that the grouping of operations will not affect the result: 329 | 330 | ```js 331 | 1 + (2 + 3) == (1 + 2) + 3; // true 332 | ``` 333 | 334 | Array concatenation can also be said to be a monoid: 335 | 336 | ```js 337 | [1, 2].concat([3, 4]); // [1, 2, 3, 4] 338 | ``` 339 | 340 | The identity value is empty array `[]` 341 | 342 | ```js 343 | [1, 2].concat([]); // [1, 2] 344 | ``` 345 | Functions also form a monoid with the normal functional compositon as an operation and the function which returns its input `(a) => a` 346 | 347 | 348 | --- 349 | 350 | ## Monad 351 | 352 | > A monad is an object with [`of`](#pointed-functor) and `chain` functions. `Chain` is like [map](#functor) except it unnests the resulting nested object. 353 | 354 | ```js 355 | ['cat,dog','fish,bird'].chain(a => a.split(',')) // ['cat','dog','fish','bird'] 356 | 357 | //Contrast to map 358 | ['cat,dog','fish,bird'].map(a => a.split(',')) // [['cat','dog'], ['fish','bird']] 359 | ``` 360 | 361 | You may also see `of` and `chain` referred to as `return` and `bind` (not be confused with the JS keyword/function...) in languages which provide Monad-like constructs as part of their standard library (e.g. Haskell, F#), on [Wikipedia](https://en.wikipedia.org/wiki/Monad_%28functional_programming%29) and in other literature. It's also important to note that `return` and `bind` are not part of the [Fantasy Land spec](https://github.com/fantasyland/fantasy-land) and are mentioned here only for the sake of people interested in learning more about Monads. 362 | 363 | --- 364 | 365 | ## Comonad 366 | 367 | > An object that has `extract` and `extend` functions. 368 | 369 | ```js 370 | let CoIdentity = v => ({ 371 | val: v, 372 | extract: this.v, 373 | extend: f => CoIdentity(f(this)) 374 | }) 375 | ``` 376 | 377 | Extract takes a value out of a functor. 378 | ```js 379 | CoIdentity(1).extract() // 1 380 | ``` 381 | 382 | Extend runs a function on the comonad. The function should return the same type as the Comonad. 383 | ```js 384 | CoIdentity(1).extend(co => co.extract() + 1) // CoIdentity(2) 385 | ``` 386 | --- 387 | 388 | ## Applicative Functor 389 | 390 | > An applicative functor is an object with an `ap` function. `Ap` applies a function in the object to a value in another object of the same type. 391 | 392 | ```js 393 | [(a)=> a + 1].ap([1]) // [2] 394 | ``` 395 | 396 | --- 397 | 398 | ## Morphism 399 | 400 | > A transformation function. 401 | 402 | --- 403 | 404 | ## Isomorphism 405 | 406 | > A pair of transformations between 2 types of objects that is structural in nature and no data is lost. 407 | 408 | For example, 2D coordinates could be stored as an array `[2,3]` or object `{x: 2, y: 3}`. 409 | ```js 410 | // Providing functions to convert in both directions makes them isomorphic. 411 | const pairToCoords = (pair) => ({x: pair[0], y: pair[1]}) 412 | 413 | const coordsToPair = (coords) => [coords.x, coords.y] 414 | 415 | coordsToPair(pairToCoords([1, 2])) // [1, 2] 416 | 417 | pairToCoords(coordsToPair({x: 1, y: 2})) // {x: 1, y: 2} 418 | ``` 419 | 420 | --- 421 | 422 | ## Setoid 423 | 424 | > An object that has an `equals` function which can be used to compare other objects of the same type. 425 | 426 | Make array a setoid. 427 | ```js 428 | Array.prototype.equals = arr => { 429 | var len = this.length 430 | if (len != arr.length) { 431 | return false 432 | } 433 | for (var i = 0; i < len; i++) { 434 | if (this[i] !== arr[i]) { 435 | return false 436 | } 437 | } 438 | return true 439 | } 440 | 441 | [1, 2].equals([1, 2]) // true 442 | [1, 2].equals([0]) // false 443 | ``` 444 | 445 | --- 446 | 447 | ## Semigroup 448 | 449 | An object that has a `concat` function that combines it with another object of the same type. 450 | 451 | ```js 452 | [1].concat([2]) // [1, 2] 453 | ``` 454 | 455 | --- 456 | 457 | ## Foldable 458 | 459 | > An object that has a reduce function that can transform that object into some other type. 460 | 461 | ```js 462 | let sum = list => list.reduce((acc, val) => acc + val, 0); 463 | sum([1, 2, 3]) // 6 464 | ``` 465 | 466 | --- 467 | 468 | ## Traversable 469 | 470 | --- 471 | ## Type Signatures 472 | 473 | > Often functions will include comments that indicate the types of their arguments and return types. 474 | 475 | There's quite a bit variance across the community but they often follow the following patterns: 476 | ```js 477 | // functionName :: firstArgType -> secondArgType -> returnType 478 | 479 | // add :: Number -> Number -> Number 480 | let add = x => y => x + y 481 | 482 | // increment :: Number -> Number 483 | let increment = x => x + 1 484 | ``` 485 | 486 | If a function accepts another function as an argument it is wrapped in parenthesis. 487 | 488 | ```js 489 | // call :: (a -> b) -> a -> b 490 | let call = f => x => f(x) 491 | ``` 492 | The letters `a`, `b`, `c`, `d` are used to signify that the argument can be of any type. For this map it takes a function that transforms a value of some type `a` into another type `b`, an array of values of type `a`, and returns an array of values of type `b`. 493 | ```js 494 | // map :: (a -> b) -> [a] -> [b] 495 | let map = f => list => list.map(f) 496 | ``` 497 | --------------------------------------------------------------------------------