[
  {
    "path": ".eslintrc.yml",
    "content": "---\n  extends: \"standard\"\n  plugins: [markdown]\n  rules:\n    no-unused-vars: 0\n    no-undef: 0\n    no-extend-native: 0\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: hemanth\npatreon: fpjargon\ncustom: https://paypal.me/gnumanth\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2015 Hemanth.HM <hemanth.hm@gmail.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "contributing.md",
    "content": "# Contributing\n\nThis project is a work in progress. Contributions are very welcome.\n\n## Hard rules\nThere is a pre-commit hook that runs:  `npm run test && npm run roadmarks` for linting the readme and creating the TOC.\n\nThat said, we'd like to maintain some consistency across the document.\n\n## Style guide\n1. Every definition should include at least one JavaScript code example.\n1. Definitions should be written using the simplest language possible. Every word should tell.\n1. Target programmers that have no functional programming experience.\n1. We value understandability more than accuracy. e.g. It's okay to describe a functor as a container.\n1. Don't overuse jargon even if defined elsewhere in the document.\n1. Link to terms defined in the document when you use them in a definition.\n1. Avoid big walls of text\n\n## Code conventions\n[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\n* Be consistent with other examples\n* Prefer arrow functions\n* Parenthesis around function arguments\n* Put output values in comments\n* Keep it short and simple\n\nThis styleguide is a WIP too! Send PRs :)\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"functional-programming-jargons\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Jargon from the functional programming world in simple terms!\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"eslint readme.md\",\n    \"toc\": \"roadmarks\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/hemanth/functional-programming-jargon.git\"\n  },\n  \"author\": \"hemanth\",\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/hemanth/functional-programming-jargon/issues\"\n  },\n  \"homepage\": \"https://github.com/hemanth/functional-programming-jargon#readme\",\n  \"devDependencies\": {\n    \"eslint\": \"^3.4.0\",\n    \"eslint-config-standard\": \"^6.0.0\",\n    \"eslint-plugin-markdown\": \"^1.0.0-beta.6\",\n    \"eslint-plugin-standard\": \"^3.0.1\",\n    \"pre-commit\": \"^1.2.2\",\n    \"roadmarks\": \"^1.6.3\"\n  },\n  \"pre-commit\": [\n    \"test\",\n    \"toc\"\n  ]\n}\n"
  },
  {
    "path": "readme.md",
    "content": "# Functional Programming Jargon\n\nFunctional programming (FP) provides many advantages, and its popularity has been increasing as a result. However, each programming paradigm comes with its own unique jargon and FP is no exception. By providing a glossary, we hope to make learning FP easier.\n\nThis is a fork of [Functional Programming Jargon](https://github.com/jmesyou/functional-programming-jargon). Examples are presented in Python3.\n\nThis document attempts to adhere to [PEP8](https://www.python.org/dev/peps/pep-0008/) as best as possible.\n\nThis document is WIP and pull requests are welcome!\n\n__Translations__\n* [Portuguese](https://github.com/alexmoreno/jargoes-programacao-funcional)\n* [Spanish](https://github.com/idcmardelplata/functional-programming-jargon/tree/master)\n* [Chinese](https://github.com/shfshanyue/fp-jargon-zh)\n* [Bahasa Indonesia](https://github.com/wisn/jargon-pemrograman-fungsional)\n* [Scala World](https://github.com/ikhoon/functional-programming-jargon.scala)\n* [Korean](https://github.com/sphilee/functional-programming-jargon)\n\n__Table of Contents__\n<!-- RM(noparent,notop) -->\n\n* [Arity](#arity)\n* [Higher-Order Functions (HOF)](#higher-order-functions-hof)\n* [Closure](#closure)\n* [Partial Application](#partial-application)\n* [Currying](#currying)\n* [Auto Currying](#auto-currying)\n* [Function Composition](#function-composition)\n* [Continuation](#continuation)\n* [Purity](#purity)\n* [Side effects](#side-effects)\n* [Idempotent](#idempotent)\n* [Point-Free Style](#point-free-style)\n* [Predicate](#predicate)\n* [Contracts](#contracts)\n* [Category](#category)\n* [Value](#value)\n* [Constant](#constant)\n* [Functor](#functor)\n* [Pointed Functor](#pointed-functor)\n* [Lift](#lift)\n* [Referential Transparency](#referential-transparency)\n* [Equational Reasoning](#equational-reasoning)\n* [Lambda](#lambda)\n* [Lambda Calculus](#lambda-calculus)\n* [Lazy evaluation](#lazy-evaluation)\n* [Monoid](#monoid)\n* [Monad](#monad)\n* [Comonad](#comonad)\n* [Applicative Functor](#applicative-functor)\n* [Morphism](#morphism)\n  * [Endomorphism](#endomorphism)\n  * [Isomorphism](#isomorphism)\n  * [Homomorphism](#homomorphism)\n  * [Catamorphism](#catamorphism)\n  * [Anamorphism](#anamorphism)\n  * [Hylomorphism](#hylomorphism)\n  * [Paramorphism](#paramorphism)\n  * [Apomorphism](#apomorphism)\n* [Setoid](#setoid)\n* [Semigroup](#semigroup)\n* [Foldable](#foldable)\n* [Lens](#lens)\n* [Type Signatures](#type-signatures)\n* [Algebraic data type](#algebraic-data-type)\n  * [Sum type](#sum-type)\n  * [Product type](#product-type)\n* [Option](#option)\n* [Function](#function)\n* [Partial function](#partial-function)\n* [Functional Programming Libraries in Python](#functional-programming-libraries-in-javascript)\n\n\n<!-- /RM -->\n\n## Arity\n\nThe 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).\n\n```python\nfrom inspect import signature \n\nadd = lambda a, b: a + b\n\narity = len(signature(add).parameters)\nprint(arity) # 2\n\n# The arity of add is 2\n```\n\n## Higher-Order Functions (HOF)\n\nA function which takes a function as an argument and/or returns a function.\n\n```python\nfilter = lambda predicate, xs: [x for x in xs if predicate(xs)] \n```\n\n```python\nis_a = lambda T: lambda x: type(x) is T\n```\n\n```python\nfilter(is_a(int), [0, '1', 2, None]) # [0, 2]\n```\n\n## Closure\n\nA closure is a way of accessing a variable outside its scope.\nFormally, a closure is a technique for implementing lexically scoped named binding. It is a way of storing a function with an environment.\n\nA closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined.\nie. they allow referencing a scope after the block in which the variables were declared has finished executing.\n\n\n```python\nadd_to = lambda x: lambda y: x + y\nadd_to_five = add_to(5)\nadd_to_five(3) # returns 8\n```\nThe function ```add_to()``` returns a function(internally called ```add()```), lets store it in a variable called ```add_to_five``` with a curried call having parameter 5.\n\nIdeally, when the function ```add_to``` finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling ```add_to_five()```. This means that the state of the function ```add_to``` is saved even after the block of code has finished executing, otherwise there is no way of knowing that ```add_to``` was called as ```add_to(5)``` and the value of x was set to 5.\n\nLexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure.\n\nThe stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it).\n\nLambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.\n\nA closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.\n\n__Further reading/Sources__\n* [Lambda Vs Closure](http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda)\n* [JavaScript Closures highly voted discussion](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)\n\n## Partial Application\n\nPartially applying a function means creating a new function by pre-filling some of the arguments to the original function.\n\n\n```python\n# Helper to create partially applied functions\n# Takes a function and some arguments\npartial = lambda f, *args: \n  # returns a function that takes the rest of the arguments\n  lambda *more_args:\n    # and calls the original function with all of them\n    f(args, more_args)\n# Something to apply\nadd3 = lambda a, b, c: a + b + c\n# Partially applying `2` and `3` to `add3` gives you a one-argument function\nfive_plus = partial(add3, 2, 3) # (c) => 2 + 3 + c\n\nfive_plus(4) # 9\n```\n\nYou can also use `functools.partial` to partially apply a function in Python:\n\n```python\nfrom functools import partial \n\nadd_more = partial(add3, 2, 3) # (c) => 2 + 3 + c\n```\n\nPartial application helps create simpler functions from more complex ones by baking in data when you have it. [Curried](#currying) functions are automatically partially applied.\n\n\n## Currying\n\nThe process of converting a function that takes multiple arguments into a function that takes them one at a time.\n\nEach time the function is called it only accepts one argument and returns a function that takes one argument until all arguments are passed.\n\n```python\nsum = lambda a, b: a + b \n\ncurried_sum = lambda a: lambda b: a + b\n\ncurried_sum(40)(2) # 42.\n\nadd2 = curried_sum(2) # (b) => 2 + b\n\nadd2(10) # 12\n```\n\n## Auto Currying\nTransforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated.\n\nThe `toolz` module has an currying decorator which works this way\n\n```python\nfrom toolz import curry \n\n@curry\ndef add(x, y): return x + y \n\nadd(1, 2) # 3\nadd(1)    # (y) => 1 + y\nadd(1)(2) # 3\n```\n\n__Further reading__\n* [Favoring Curry](http://fr.umio.us/favoring-curry/)\n* [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA)\n\n## Function Composition\n\nThe act of putting two functions together to form a third function where the output of one function is the input of the other.\n\n```python\nimport math \n\ncompose = lambda f, g: lambda a: f(g(a)) # Definition\nfloor_and_str = compose(str, Math.floor) # Usage\nfloor_and_string(121.212121) # '121'\n```\n\n## Continuation\n\nAt any given point in a program, the part of the code that's yet to be executed is known as a continuation.\n\n```python\nprint_as_string = lambda num: print(num)\n\n# this was previously defined as multi-line function in Javascript\n# however, Python only supports single expression lambdas\nadd_one_and_continue = lambda num, cc: cc(num + 1) \n\nadd_one_and_continue(2, print_as_string) # 'Given 3'\n```\n\nContinuations are often seen in asynchronous programming when the program needs to wait to receive data before it can continue. The response is often passed off to the rest of the program, which is the continuation, once it's been received.\n\n```python\ncontinue_program_with = lambda data: ... # Continues program with data\n\nread_file_async('path/to/file', lambda err, response: raise err if err else continue_program_with(response))\n```\n\n## Purity\n\nA function is pure if the return value is only determined by its\ninput values, and does not produce side effects.\n\n```python\ngreet = lambda name: 'Hi, {}'.format(name)\n\ngreet('Brianne') # 'Hi, Brianne'\n```\n\nAs opposed to each of the following:\n\n```python\nname = 'Brianne'\n\ngreet = lambda: 'Hi, {}'.format(name)\n\ngreet() # \"Hi, Brianne\"\n```\n\nThe above example's output is based on data stored outside of the function...\n\n```python\ngreeting = None\n\ndef greet(name):\n  global greeting\n  greeting = 'Hi, {}'.format(name)\n\ngreet('Brianne')\ngreeting # \"Hi, Brianne\"\n```\n\n... and this one modifies state outside of the function.\n\n## Side effects\n\nA function or expression is said to have a side effect if apart from returning a value, it interacts with (reads from or writes to) external mutable state.\n\n```python\ndifferent_ever_time = list()\n```\n\n```python\nprint('IO is a side effect!')\n```\n\n## Idempotent\n\nA function is idempotent if reapplying it to its result does not produce a different result.\n\n```\nf(f(x)) ≍ f(x)\n```\n\n```python\nimport math\n\nmath.abs(math.abs(10))\n```\n\n```python\nsorted(sorted(sorted([2, 1])))\n```\n\n## Point-Free Style\n\nWriting functions where the definition does not explicitly identify the arguments used. This style usually requires [currying](#currying) or other [Higher-Order functions](#higher-order-functions-hof). A.K.A Tacit programming.\n\n```python\n# Given\nmap = lambda fn: lambda xs: [fn(x) for x in xs]\nadd = lambda a: lambda b: a + b\n\n# Then\n\n# Not points-free - `numbers` is an explicit argument\nincrement_all = lambda numbers: map(add(1))(numbers)\n\n# Points-free - The list is an implicit argument\nincrement_all2 = map(add(1))\n```\n\n`increment_all` identifies and uses the parameter `numbers`, so it is not points-free.  `increment_all2` is written just by combining functions and values, making no mention of its arguments.  It __is__ points-free.\n\nPoints-free function definitions look just like normal assignments without `def` or `lambda`.\n\n## Predicate\nA predicate is a function that returns true or false for a given value. A common use of a predicate is as the callback for array filter.\n\n```python\npredicate = lambda a: a > 2\n\nfilter(predicate, [1, 2, 3, 4]) # [3, 4]\n```\n\n## Contracts\n\nA contract specifies the obligations and guarantees of the behavior from a function or expression at runtime. This acts as a set of rules that are expected from the input and output of a function or expression, and errors are generally reported whenever a contract is violated.\n\n```python\ndef throw(ex):\n  raise ex\n\n# Define our contract : int -> boolean\ncontract = lambda value: True if type(value) is int else throw(Exception('Contract violated: expected int -> boolean'))\n\nadd1 = lambda num: contract(num) and num + 1\n\nadd1(2) # 3\nadd1('some string') # Contract violated: expected int -> boolean\n```\n\n## Category\n\nA category in category theory is a collection of objects and morphisms between them. In programming, typically types\nact as the objects and functions as morphisms.\n\nTo be a valid category 3 rules must be met:\n\n1. There must be an identity morphism that maps an object to itself.\n    Where `a` is an object in some category,\n    there must be a function from `a -> a`.\n2. Morphisms must compose.\n    Where `a`, `b`, and `c` are objects in some category,\n    and `f` is a morphism from `a -> b`, and `g` is a morphism from `b -> c`;\n    `g(f(x))` must be equivalent to `(g • f)(x)`.\n3. Composition must be associative\n    `f • (g • h)` is the same as `(f • g) • h`\n\nSince these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things.\n\n__Further reading__\n\n* [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)\n\n## Value\n\nAnything that can be assigned to a variable.\n\n```python\nfrom collections import namedtuple\nPerson = namedtuple('Person', 'name age')\n5\nPerson('John', 30)\nlambda a: a\n[1]\nNone\n```\n\n## Constant\n\nA variable that cannot be reassigned once defined.\n\n```python\n\nfive = 5\njohn = Person('John', 30)\n```\n\nConstants are [referentially transparent](#referential-transparency). That is, they can be replaced with the values that they represent without affecting the result.\n\nWith the above two constants the following expression will always return `true`.\n\n```python\njohn.age + five == Person('John' 30).age + 5\n```\n\n## Functor\n\nAn object that implements a `map` function which, while running over each value in the object to produce a new object, adheres to two rules:\n\n__Preserves identity__\n```\nobject.map(x => x) ≍ object\n```\n\n__Composable__\n\n```\nobject.map(compose(f, g)) ≍ object.map(g).map(f)\n```\n\n(`f`, `g` are arbitrary functions)\n\nIterables in Python are functors since they abide by the two functor rules:\n\n```python\n\nmap(lambda x: x, [1, 2, 3]) # = [1, 2, 3]\nmap(lambda x: x, (1, 2, 3)) # = (1, 2, 3)\n```\n\nand\n\n```python\nf = lambda x: x + 1\ng = lambda x: x * 2\n\nmap(lambda x: f(g(x)), [1, 2, 3]) # = [3, 5, 7]\nmap(f, map(g, [1, 2, 3]))         # = [3, 5, 7]\n```\n\n## Pointed Functor\nAn object with an `of` function that puts _any_ number of values into it. The following property\n`of(f(x)) == of(x).map(f)` must also hold for any pointed functor.\n\nWe create a custom class `Array` which mimics the original Javascript for a pointed functor.\n\n```python \n\nclass Array(list):\n\n  of = lambda *args: Array([a for a in args])\n\nArray.of(1) # [1]\n```\n\n## Lift\n\nLifting is when you take a value and put it into an object like a [functor](#pointed-functor). If you lift a function into an [Applicative Functor](#applicative-functor) then you can make it work on values that are also in that functor.\n\nSome implementations have a function called `lift`, or `liftA2` to make it easier to run functions on functors.\n\n```python\n# OSlash applicative library https://github.com/dbrattli/oslash\nfrom oslash import List, Applicative # we import the Applicative \n\nliftA2 = lambda f: lambda a, b:  a.map(f) * b # a, b is of type Applicative where (*) is the apply function.\n\nmult = lambda a: lambda b: a * b # (*) is just regular multiplication\n\nlifted_mult = liftA2(mult) # this function now works on functors like oslash.List\n\nlifted_mult(List([1, 2]), List([3])) # [3, 6]\nliftA2(lambda a: lambda b: a + b)(List([1, 2]), List([3, 4])) # [4, 5, 5, 6]\n\n# or using oslash, it can alternatively be written as\n\nList([1, 2]).lift_a2(mult, List([3]))\nList([1, 2]).lift_a2(lambda a: lambda b: a + b, List([3, 4]))\n```\n\nLifting a one-argument function and applying it does the same thing as `map`.\n\n```python\nincrement = lambda x: x + 1\n\nlift(increment)(List([2])) # [3]\nList([2]).map(increment)  # [3]\n```\n\n\n## Referential Transparency\n\nAn expression that can be replaced with its value without changing the\nbehavior of the program is said to be referentially transparent.\n\nSay we have function greet:\n\n```python\ngreet = lambda: 'Hello World!'\n```\n\nAny invocation of `greet()` can be replaced with `Hello World!` hence greet is\nreferentially transparent.\n\n##  Equational Reasoning\n\nWhen an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.\n\n## Lambda\n\nAn anonymous function that can be treated like a value.\n\n```python \ndef f(a):\n  return a + 1\n\nlambda a: a + 1\n```\nLambdas are often passed as arguments to Higher-Order functions.\n\n```python\nList([1, 2]).map(lambda x: x + 1) # [2, 3]\n```\n\nYou can assign a lambda to a variable.\n\n```python\nadd1 = lambda a: a + 1\n```\n\n## Lambda Calculus\nA branch of mathematics that uses functions to create a [universal model of computation](https://en.wikipedia.org/wiki/Lambda_calculus).\n\n## Lazy evaluation\n\nLazy 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.\n\n```python\nimport random\ndef rand(): \n  while True:\n    yield random.randint(1,101)\n```\n\n```python\nrandIter = rand()\nnext(randIter) # Each execution gives a random value, expression is evaluated on need.\n```\n\n## Monoid\n\nAn object with a function that \"combines\" that object with another of the same type.\n\nOne simple monoid is the addition of numbers:\n\n```python\n1 + 1 # 2\n```\nIn this case number is the object and `+` is the function.\n\nAn \"identity\" value must also exist that when combined with a value doesn't change it.\n\nThe identity value for addition is `0`.\n```python\n1 + 0 # 1\n```\n\nIt's also required that the grouping of operations will not affect the result (associativity):\n\n```python\n1 + (2 + 3) == (1 + 2) + 3 # true\n```\n\nList concatenation also forms a monoid:\n\n```python\n[1, 2] + [3, 4] # [1, 2, 3, 4]\n```\n\nThe identity value is empty array `[]`\n\n```python\n[1, 2] + [] # [1, 2]\n```\n\nIf identity and compose functions are provided, functions themselves form a monoid:\n\n```python\nidentity = lambda a: a\ncompose = lambda f, g: lambda x: f(g(x))\n```\n`foo` is any function that takes one argument.\n```\ncompose(foo, identity) ≍ compose(identity, foo) ≍ foo\n```\n\n## Monad\n\nA monad is an object with [`of`](#pointed-functor) and `chain` functions. `chain` is like [`map`](#functor) except it un-nests the resulting nested object.\n\n```python\n# pymonad Monad library https://bitbucket.org/jason_delaat/pymonad\nfrom pymonad.List import *\nfrom functools import reduce\n#implementation\nclass Array(list):\n\n  def of(*args): \n    return Array([a for a in args])\n\n  def chain(self, f):\n    return reduce(lambda acc, it: acc + f(it), self[:], [])\n\n  def map(self, f):\n    return [f(x) for x in self[:]]\n\n# Usage\nArray.of('cat,dog', 'fish,bird').chain(lambda a: a.split(',')) # ['cat', 'dog', 'fish', 'bird']\n\n# Contrast to map\nArray.of('cat,dog', 'fish,bird').map(lambda a: a.split(',')) # [['cat', 'dog'], ['fish', 'bird']]\n```\n\n`of` is also known as `return` in other functional languages.\n`chain` is also known as `flatmap` and `bind` in other languages.\n\n## Comonad\n\nAn object that has `extract` and `extend` functions.\n\n```python\nclass CoIdentity:\n\n  def __init__(self, v):\n    self.val = v\n\n  def extract(self):\n    return self.val\n\n  def extend(f):\n    return CoIdentity(f(self))\n```\n\nExtract takes a value out of a functor.\n\n```python\nCoIdentity(1).extract() # 1\n```\n\nExtend runs a function on the comonad. The function should return the same type as the comonad.\n\n```python\nCoIdentity(1).extend(lambda co: co.extract() + 1) # CoIdentity(2)\n```\n\n## Applicative Functor\n\nAn 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.\n\n```python\nfrom functools import reduce\n# Implementation\n\nclass Array(list):\n\n  def of(*args): \n    return Array([a for a in args])\n\n  def chain(self, f):\n    return reduce(lambda acc, it: acc + f(it), self[:], [])\n\n  def map(self, f):\n    return [f(x) for x in self[:]]\n\n  def ap(self, xs):\n    return reduce(lambda acc, f: acc + (xs.map(f)), self[:], [])\n\n# Example usage\nArray([lambda a: a + 1]).ap(Array([1])) # [2]\n```\n\nThis is useful if you have two objects and you want to apply a binary function to their contents.\n\n```python\n# Arrays that you want to combine\narg1 = [1, 3]\narg2 = [4, 5]\n\n# combining function - must be curried for this to work\nadd = lambda x: lambda y: x + y\n\npartially_applied_adds = [add].ap(arg1) # [(y) => 1 + y, (y) => 3 + y]\n```\n\nThis gives you an array of functions that you can call `ap` on to get the result:\n\n```python\npartially_applied_adds.ap(arg2) # [5, 6, 7, 8]\n```\n\n## Morphism\n\nA transformation function.\n\n### Endomorphism\n\nA function where the input type is the same as the output.\n\n```python\n# uppercase :: String -> String\nuppercase = lambda s: s.upper() \n\n# decrement :: Number -> Number\ndecrement = lambda x: x - 1\n```\n\n### Isomorphism\n\nA pair of transformations between 2 types of objects that is structural in nature and no data is lost.\n\nFor example, 2D coordinates could be stored as an array `[2,3]` or object `{x: 2, y: 3}`.\n\n```python\n# Providing functions to convert in both directions makes them isomorphic.\nfrom collections import namedtuple\n\nCoords = namedtuple('Coords', 'x y')\npair_to_coords = lambda pair: Coords(pair[0], pair[1])\n\ncoords_to_pair = lambda coords: [coords.x, coords.y]\n\ncoords_to_pair(pair_to_coords([1, 2])) # [1, 2]\n\npair_to_coords(coords_to_pair(Coords(1, 2))) # Coords(x=1, y=2)\n```\n\n### Homomorphism\n\nA homomorphism is just a structure preserving map. In fact, a functor is just a homomorphism between categories as it preserves the original category's structure under the mapping.\n\n```python\nfrom pymonad import *\nf * A.unit(x) == A.unit(f(x))\n\n(lambda x: x.upper()) * (Either.unit(\"oreos\")) == Either.unit(\"oreos\".upper())\n```\n\n### Catamorphism\n\nA `reduce_right` function that applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.\n\n```python\nfrom functools import reduce\nclass Array(list):\n\n  def reduce_right(self, f, init):\n    return reduce(f, self[::-1], init)\n\nsum = lambda xs: xs.reduce_right(lambda acc, x: acc + x, 0)\n\nsum(Array([1, 2, 3, 4, 5])) # 15\n```\n\n### Anamorphism\n\nAn `unfold` function. An `unfold` is the opposite of `fold` (`reduce`). It generates a list from a single value.\n\n```python\n\ndef unfold(f, seed):\n  def go(f, seed, acc):\n    res = f(seed)\n    return go(f, res[1], acc + [res[0]]) if res else acc\n\n  return go(f, seed, [])\n```\n\n```python\ncount_down = lambda n: unfold(lambda n: None if n <= 0 else (n, n - 1), n)\n\ncount_down(5) # [5, 4, 3, 2, 1]\n```\n\n### Hylomorphism\n\nThe combination of anamorphism and catamorphism.\n\n### Paramorphism\n\nA function just like `reduce_right`. However, there's a difference:\n\nIn paramorphism, your reducer's arguments are the current value, the reduction of all previous values, and the list of values that formed that reduction.\n\n```python\n\ndef para(reducer, accumulator, elements):\n  if not len(elements):\n    return accumulator\n\n  head = elements[0]\n  tail = elements[1:]\n\n  return reducer(head, tail, para(reducer, accumulator, tail))\n\nsuffixes = lambda lst: para(lambda x, xs, suffxs: [xs, *suffxs], [], lst)\n\nsuffixes([1, 2, 3, 4, 5]) # [[2, 3, 4, 5], [3, 4, 5], [4, 5], [5], []]\n```\n\nThe third parameter in the reducer (in the above example, `[x, *xs]`) is kind of like having a history of what got you to your current acc value.\n\n### Apomorphism\n\nit's the opposite of paramorphism, just as anamorphism is the opposite of catamorphism. Whereas with paramorphism, you combine with access to the accumulator and what has been accumulated, apomorphism lets you `unfold` with the potential to return early.\n\n## Setoid\n\nAn object that has an `equals` function which can be used to compare other objects of the same type.\n\nMake array a setoid:\n\n```python \n\nclass Array(list):\n\n  def equals(self, other):\n    if len(self) != len(other):\n      return False \n    else:\n      return reduce(lambda ident, pair: ident and (pair[0] == pair[1]), zip(self[:], other[:]), True)\n\nArray([1, 2]).equals(Array([1, 2])) # true\nArray([1, 2]).equals(Array([0])) # false\n```\n\n## Semigroup\n\nAn object that has a `concat` function that combines it with another object of the same type.\n\n```python\n[1] + [2] # [1, 2]\n```\n\n## Foldable\n\nAn object that has a `reduce` function that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.\n\n```python\nsum = lambda lst: reduce(lambda acc, x: acc + x, lst, 0)\nsum([1, 2, 3]) # 6\n```\n\n## Lens ##\nA lens is a structure (often an object or function) that pairs a getter and a non-mutating setter for some other data\nstructure.\n\n```python\nfrom lenses import lens\n# Using [python-lenses](https://python-lenses.readthedocs.io/en/latest/tutorial/methods.html)\n\nname_lens = lens['name'] # we create an unbound lens which accesses the value associate with the 'name' key of a dict\n```\n\nHaving the pair of get and set for a given data structure enables a few key features.\n\n```python\nperson = {'name': 'Gertrude Blanch'}\n\n# invoke the getter\nname_lens.get()(person) # 'Gertrude Blanch'\n\n# invoke the setter\nname_lens.set('Shafi Goldwasser')(person) # {'name': 'Shafi Goldwasser'}\n\n# run a function on the value in the structure\nname_lens.modify(lambda x: x.upper())(person) # {'name': 'GERTRUDE BLANCH'}\n```\n\nLenses are also composable. This allows easy immutable updates to deeply nested data.\n\n```python\n# This lens focuses on the first item in a non-empty array\nfirst_lens = lens[0]\n\npeople = [{'name': 'Gertrude Blanch'}, {'name': 'Shafi Goldwasser'}]\n\n# Despite what you may assume, lenses compose left-to-right.\n(first_lens & name_lens).modify(lambda x: x.upper())(people) # [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}]\n```\n\n## Type Signatures\n\nOften functions in JavaScript will include comments that indicate the types of their arguments and return values.\n\nThere's quite a bit of variance across the community but they often follow the following patterns:\n\n```python\n# function :: a -> b -> c\n\n# add :: int -> int -> int\n# alternatively could be float -> float -> float\nadd = lambda y: lambda x: x + y\n\n# increment :: int -> int\nincrement = lambda x: x + 1\n```\n\nIf a function accepts another function as an argument it is wrapped in parentheses.\n\n```python\n# call :: (a -> b) -> a -> b\ncall = lambda f: lambda x: f(x)\n```\n\nThe letters `a`, `b`, `c`, `d` are used to signify that the argument can be of any type. The following version of `map` 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`.\n\n```python\n# map :: (a -> b) -> [a] -> [b]\nmap(f, lst)\n```\n\n__Further reading__\n* [Ramda's type signatures](https://github.com/ramda/ramda/wiki/Type-Signatures)\n* [Mostly Adequate Guide](https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html#whats-your-type)\n* [What is Hindley-Milner?](http://stackoverflow.com/a/399392/22425) on Stack Overflow\n\n## Algebraic data type\nA composite type made from putting other types together. Two common classes of algebraic types are [sum](#sum-type) and [product](#product-type).\n\n### Sum type\nA Sum type is the combination of two types together into another one. It is called sum because the number of possible values in the result type is the sum of the input types.\n\nJavaScript doesn't have types like this (neither does python) but we can use `Set`s to pretend:\n```python\n# imagine that rather than sets here we have types that can only have these values\nbools = set([True, False])\nhalf_true = set(['half-true'])\n\n# The weakLogic type contains the sum of the values from bools and halfTrue\nweak_logic_values = bools.union(half_true)\n```\n\nSum types are sometimes called union types, discriminated unions, or tagged unions.\n\nThe [sumtypes](https://github.com/radix/sumtypes/) library in Python helps with defining and using union types.\n\n### Product type\n\nA **product** type combines types together in a way you're probably more familiar with:\n\n```python\nfrom collections import namedtuple\n\nPoint = namedtuple('Point', 'x y')\n# point :: (Number, Number) -> {x: Number, y: Number}\npoint = lambda pair: Point(x, y)\n```\nIt's called a product because the total possible values of the data structure is the product of the different values. Many languages have a tuple type which is the simplest formulation of a product type.\n\nSee also [Set theory](https://en.wikipedia.org/wiki/Set_theory).\n\n## Option\nOption is a [sum type](#sum-type) with two cases often called `Some` and `None`.\n\nOption is useful for composing functions that might not return a value.\n\n```python\n# Naive definition\n\nclass _Some:\n  \n  def __init__(self, v):\n    self.val = v\n\n  def map(self, f):\n    return _Some(f(self.val))\n\n  def chain(self, f):\n    return f(self.val)\n  \n# None is a keyword in python\nclass _None:\n\n  def map(self, f):\n    return self\n\n  def chain(self, f):\n    return self\n\n# maybe_prop :: String -> (String => a) -> Option a\nmaybe_prop = lambda key, obj: _None() if key not in obj else Some(obj[key])\n```\nUse `chain` to sequence functions that return `Option`s\n```python\n\n# get_item :: Cart -> Option CartItem\nget_item = lambda cart: maybe_prop('item', cart)\n\n# get_price :: Cart -> Option Float\nget_price = lambda item: maybe_prop('price', item)\n\n# get_nested_price :: Cart -> Option a\nget_nested_price = lambda cart: get_item(cart).chain(get_price)\n\nget_nested_price({}) # _None()\nget_nested_price({\"item\": {\"foo\": 1}}) # _None()\nget_nested_price({\"item\": {\"price\": 9.99}}) # _Some(9.99)\n```\n\n`Option` is also known as `Maybe`. `Some` is sometimes called `Just`. `None` is sometimes called `Nothing`.\n\n## Function\nA **function** `f :: A => B` is an expression - often called arrow or lambda expression - with **exactly one (immutable)** parameter of type `A` and **exactly one** return value of type `B`. That value depends entirely on the argument, making functions context-independant, or [referentially transparent](#referential-transparency). What is implied here is that a function must not produce any hidden [side effects](#side-effects) - a function is always [pure](#purity), by definition. These properties make functions pleasant to work with: they are entirely deterministic and therefore predictable. Functions enable working with code as data, abstracting over behaviour:\n\n```python\n# times2 :: Number -> Number\ntimes2 = lambda n: n * 2\n\nmap(times2, [1, 2, 3] # [2, 4, 6]\n```\n\n## Partial function\nA partial function is a [function](#function) which is not defined for all arguments - it might return an unexpected result or may never terminate. Partial functions add cognitive overhead, they are harder to reason about and can lead to runtime errors. Some examples:\n```python\nfrom functools import partial\n# example 1: sum of the list\n# sum :: [int] -> int\nsum = partial(reduce, lambda a, b: a + b, arr)\nsum([1, 2, 3]) # 6\nsum([])        # TypeError: reduce() of empty sequence with no initial value\n\n# example 2: get the first item in list\n# first :: [a] -> a\nfirst = lambda a: a[0]\nfirst([42]) # 42\nfirst([])   # IndexError\n# or even worse:\nfirst([[42]])[0] # 42\nfirst([])[0]     # Uncaught TypeError: an IndexError is throw instead\n\n# example 3: repeat function N times\n# times :: int -> (int -> int) -> int\ntimes = lambda n: lambda fn: n and (fn(n), times(n - 1)(fn))\ntimes(3)(print)\n# 3\n# 2\n# 1\n# out: (None, (None, (None, 0)))\ntimes(-1)(print)\n# RecursionError: maximum recursion depth exceeded while calling a Python object\n```\n\n### Dealing with partial functions\nPartial functions are dangerous as they need to be treated with great caution. You might get an unexpected (wrong) result or run into runtime errors. Sometimes a partial function might not return at all. Being aware of and treating all these edge cases accordingly can become very tedious.\nFortunately a partial function can be converted to a regular (or total) one. We can provide default values or use guards to deal with inputs for which the (previously) partial function is undefined. Utilizing the [`Option`](#Option) type, we can yield either `Some(value)` or `None` where we would otherwise have behaved unexpectedly:\n```python\n\n# re-order function arguments for easier partial function application\n_reduce = lambda fn, init, seq: reduce(fn, seq, init) \n# example 1: sum of the list\n# we can provide default value so it will always return result\n# sum :: [int] -> int\n\nsum = partial(_reduce, lambda a, b: a + b, 0)\nsum([1, 2, 3]) # 6\nsum([]) # 0\n\n# example 2: get the first item in list\n# change result to Option\n# first :: [A] -> Option A\nfirst = lambda a: _Some(a[0]) if len(a) else _None()\nfirst([42]).map(print) # 42\nfirst([]).map(print) # print won't execute at all\n# our previous worst case\nfirst([[42]]).map(lambda a: print(a[0])) # 42\nfirst([]).map(lambda a: print(a[0])) # won't execute, so we won't have error here\n# more of that, you will know by function return type (Option)\n# that you should use `.map` method to access the data and you will never forget\n# to check your input because such check become built-in into the function\n\n# example 3: repeat function N times\n# we should make function always terminate by changing conditions:\n# times :: int -> (int -> int) -> int\ntimes = lambda n: lambda fn: n > 0 and (fn(n), times(n - 1)(fn))\ntimes(3)(print)\n# 3\n# 2\n# 1\ntimes(-1)(print)\n# won't execute anything\n```\nMaking your partial functions total ones, these kinds of runtime errors can be prevented. Always returning a value will also make for code that is both easier to maintain as well as to reason about.\n\n## Functional Programming Libraries in Python\n\n### In This Doc\n  * [functools](https://docs.python.org/3/library/functools.html)\n  * [oslash](https://github.com/dbrattli/oslash)\n  * [python-lenses](https://github.com/ingolemo/python-lenses)\n  * [pymonad](https://bitbucket.org/jason_delaat/pymonad)\n  * [toolz](https://github.com/pytoolz/toolz)\n\nA comprehensive curated list of functional programming libraries for Python can be found [here](https://github.com/sfermigier/awesome-functional-python)\n\n---\n\n__P.S:__ This repo is successful due to the wonderful [contributions](https://github.com/hemanth/functional-programming-jargon/graphs/contributors)!\n"
  }
]