{
"cells": [
{
"cell_type": "markdown",
"id": "904fb311",
"metadata": {},
"source": [
"# Functional Programming for Pythonistas\n",
"\n",
"There are never-ending arguments in tech communities about things like RDBMS versus no-SQL, or functional programming (FP) versus object-oriented-programming (OOP).\n",
"My goal here isn't to weigh in on that debate; those dead horses have been beaten by people far smarter than myself.\n",
"These are all tools.\n",
"My favorite analogy is this:\n",
"If you have a giant mechanic's toolbox in front of you and you keep reaching for the crescent wrench, \"you're doing it wrong.\"\n",
"Let's open up some drawers in that toolbox and play with some different tools to see where they might be useful.\n",
"\n",
"## Why learn FP\n",
"\n",
"This point is important, and it is difficult for me to quantify.\n",
"There are lots of articles if you search \"Why learn Haskell?\" or \"Why learn functional programming?\".\n",
"I believe the main benefit is that it changes how you view and approach some problems.\n",
"When you encounter functional code in the wild, you will see a useful abstraction instead of a chunk of \"code golf\".\n",
"Functional-style programming gets you to focus on the data and less about the cruft around it.\n",
"It teaches you to break problems down into really small components, then glue them together to build a solution.\n",
"Functional programming is heavily inspired by mathematics.\n",
"Category theory has an important relationship to FP, and it seeks to abstract common patterns across \"families\" of objects.\n",
"Don't worry, I am not going to get into those weeds in this post.\n",
"\n",
"One of my favorite quotes is from the well-known network architect Russ White.\n",
"[He says](https://www.circleid.com/posts/20171019_network_design_if_you_havent_found_the_tradeoff/), \"If you think you've found a design with no tradeoffs, wellâ€¦ Guess what? **You've not looked hard enough.**\"\n",
"I believe this is as applicable to network design as it is software development.\n",
"When discussing programming languages and software design, time is often the tradeoff.\n",
"Some of the items below can ease your cognitive burden (immutable data structures), and others require some up-front head scratching; things like thinking with types and dealing with side effects.\n",
"\n",
"## Why OCaml\n",
"\n",
"If you are going to burn time learning something, it's best if it is useful in some capacity.\n",
"When I started sipping the FP Kool-Aid, I chose to learn Haskell.\n",
"All the cool kids \\[PhD's\\] are doing it!\n",
"I would like to think that there is room in the automation world for a functional language.\n",
"Unfortunately, I don't think Haskell is the best choice.\n",
"Haskell has a steep learning curve, and it complicates common operations in a pursuit of \"purity\".\n",
"The next contender I looked at is OCaml.\n",
"It is very similar to Haskell, but it trades purity for pragmatism.\n",
"Unfortunately, this is my main gripe with the language and one of Python's major shortcomings.\n",
"Neither language has en explicit mechanism to signal the developer that a side-effect is occurring or that a function call might raise an exception.\n",
"Despite that, there are many benefits:\n",
"\n",
"- Compiled: It's straightforward to build tiny containers from binaries.\n",
"- REPL: `utop`, a great debugging tool.\n",
"- Impure: This is a double-edged sword as mentioned previously.\n",
" - Functions can perform side-effects (print debugging is dead simple unlike Haskell).\n",
" - Side effects aren't forcibly bound to monads (don't worry if you don't know what that means).\n",
"- Strongly typed\n",
"- Good parsing libraries. [Menhir](http://gallium.inria.fr/~fpottier/menhir/), [Angstrom](https://github.com/inhabitedtype/angstrom), others.\n",
"\n",
"Some other drawbacks:\n",
"\n",
"- Small community\n",
"- Tiny library pool\n",
"\n",
"## Whirlwind tour\n",
"\n",
"These concepts are generic to functional programming, and I will show code examples where appropriate."
]
},
{
"cell_type": "markdown",
"id": "8bc6bfe5",
"metadata": {},
"source": [
"### Function application\n",
"\n",
"In Python:\n",
"\n",
"```python\n",
"def add(a, b):\n",
" return a + b\n",
"\n",
"n = add(2, 4) # n = 6\n",
"```\n",
"\n",
"OCaml doesn't use parenthesis for function application, although they are used to group ambiguous terms together.\n",
"\n",
"```ocaml\n",
"let add a b = a + b\n",
"\n",
"let n = add 2 4 (* val n : int = 6 *)\n",
"```"
]
},
{
"cell_type": "markdown",
"id": "1f038174",
"metadata": {},
"source": [
"### Immutability\n",
"\n",
"In functional languages, variables are immutable by default (Rust, too!).\n",
"The following code tries to create a function that takes a variable `x` and assign it a new value.\n",
"\n",
"```ocaml\n",
"utop # let f x = x := x + 1;;\n",
"Line 1, characters 15-16:\n",
"Error: This expression has type 'a ref but an expression was expected of type\n",
" int\n",
"```\n",
"\n",
"Python lambdas have better guards (expressions only, no assignment), but \"regular\" functions do not.\n",
"Notice that the dictionary `vals` is mutated by a function that doesn't return a value.\n",
"\n",
"```python\n",
">>> vals = {\"42\": 42}\n",
">>> def f(x):\n",
"... x[\"42\"] = 24\n",
"...\n",
">>> f(vals)\n",
">>> vals\n",
"{'42': 24}\n",
">>>\n",
"```\n",
"\n",
"Golang is just as guilty.\n",
"Pointers are often used to reduce memory use, but they allow the developer to mutate values in ways that may have unexpected results.\n",
"\n",
"```go\n",
"package main\n",
"\n",
"import (\n",
" \"fmt\"\n",
")\n",
"\n",
"func doit(val *string) {\n",
" *val = *val + \" world!\"\n",
"}\n",
"\n",
"func main() {\n",
" hello := \"hello\"\n",
" doit(&hello)\n",
" fmt.Printf(\"%s\\n\", hello)\n",
"}\n",
"```\n",
"\n",
"```shell\n",
"hello world!\n",
"\n",
"Program exited.\n",
"```\n",
"\n",
"These are trivial pet examples, but the problem becomes clear when you look at much larger projects.\n",
"It is extremely difficult to reason about the state of a program if everything is mutable and functions are allowed to create arbirary side effects.\n"
]
},
{
"cell_type": "markdown",
"id": "8b9b2a4f",
"metadata": {},
"source": [
"### Purity\n",
"\n",
"\"Pure\" functions are simply those that always produce the same result given the same input.\n",
"Pure functions can be written in nearly every language.\n",
"\n",
"```python\n",
"f = lambda x: x + 1\n",
"```\n",
"\n",
"```python\n",
"def f(x):\n",
" return x + 1\n",
"```\n",
"\n",
"```ocaml\n",
"let f x = x + 1\n",
"```\n",
"\n",
"Think of pure functions in the same way as mathematical functions (that's where the idea originates).\n",
"Addition takes two arguments and produces a result.\n",
"The same result given the same input!\n",
"One benefit of pure functions is that they tend to be very straightforward to test.\n",
"\n",
"These are impure functions.\n",
"`doit` above in the golang example (Play with it to see why. Hint, print the pointer address).\n",
"\n",
"This function will return different values depending on what is input.\n",
"\n",
"```python\n",
"def get_input():\n",
" return input(\"Type something: \")\n",
"```\n",
"\n",
"This function might raise an exception.\n",
"\n",
"```python\n",
"def get_val(d):\n",
" return d[42]\n",
"```\n",
"\n",
"You may be thinking that this is a nice idea, but it's entirely useless!\n",
"Exceptions happen; we need to validate inputs!\n",
"This argument is correct, but few people are taught a different way to deal with the ugly \"real world\".\n"
]
},
{
"cell_type": "markdown",
"id": "625394be",
"metadata": {},
"source": [
"### Referential transparency\n",
"\n",
"This is closely related to purity.\n",
"Referential transparency means that you can replace a funciton call with its return value.\n",
"I'll leave this as an exercise for the reader to see why this only works with pure functions.\n"
]
},
{
"cell_type": "markdown",
"id": "6b6babcd",
"metadata": {},
"source": [
"### Higer-order functions\n",
"\n",
"Thanfully, Python treats functions as first-class citizens (so does golang).\n",
"This means that functions can be passed as values to other functions.\n",
"Functions can also return functions (think `functools.wraps`).\n",
"The most common example in Python is the `key` argument to the `sorted` function.\n",
"\n",
"```python\n",
">>> l = [42, 21, 17, 19, -3]\n",
">>> sorted(l)\n",
"[-3, 17, 19, 21, 42]\n",
">>> sorted(l, key=lambda x: x * -1)\n",
"[42, 21, 19, 17, -3]\n",
">>>\n",
"```\n",
"\n",
"`sorted` is a function that accepts a `key` which is simply another function.\n",
"Less common, but fairly regular examples in Python are `map` and `filter`.\n",
"Both of these functions accept a function that is applied to the values of an interable.\n"
]
},
{
"cell_type": "markdown",
"id": "bca66d2c",
"metadata": {},
"source": [
"### Currying\n",
"\n",
"Most developers will argue that addition is a function of two arguments that returns a numeric value.\n",
"e.g. 2 + 2 = 4\n",
"Can we look at this a different way?\n",
"What if we considered the function `lambda x: x + 2`?\n",
"It adds two to whatever argument is passed to it.\n",
"That means that we can think of addition as a function that takes a single argument, and *returns a function that adds that argument to another value.*\n",
"\n",
"In OCaml, infix operators can be rewritten as binary operators by surrounding them with parenthesis.\n",
"e.g. `2 + 2` is equivalent to `(+) 2 2`\n",
"\n",
"```ocaml\n",
"utop # let f = (+);;\n",
"val f : int -> int -> int = \n",
"```\n",
"\n",
"The second line should look sort of familiar if you have used Python's type annotations.\n",
"The difference with ML family languages is that they don't differentiate between arguments and return values because all functions are \"curried\" by default.\n",
"\n",
"```ocaml\n",
"utop # let f = (+) 2;;\n",
"val f : int -> int = \n",
"\n",
"utop # let f = (+) 2 4;;\n",
"val f : int = 6\n",
"```\n",
"\n",
"#### This is not the curry you are looking for\n",
"\n",
"You may be familiar with `functools.partial`.\n",
"This function is a curry in spirit, but with the complications that mutable-everything bring.\n",
"`partial` is an unfortunate name as we'll see next."
]
},
{
"cell_type": "markdown",
"id": "3bf8cb7e",
"metadata": {},
"source": [
"### Total and partial functions\n",
"\n",
"I am speaking of mathematical partial functions, not \"partially-applied\" functions.\n",
"I have to get into the weeds a little on this one, but it's an important concept.\n",
"The *domain* of a function is the set of values in the \"input space\".\n",
"The *range* or *co-domain* is the set of values in the output space.\n",
"Here's an example:\n",
"\n",
"```python\n",
"def int_to_str(i: int) -> str:\n",
" return str(i)\n",
"```\n",
"\n",
"The domain of this function is all integers and the range or co-domain is the subset of strings that can be translated from integers.\n",
"This can be a bit of a squishy subject because computers have finite resources.\n",
"We can say a function works on \"all strings\", but implicitly, we understand that \"all strings\" are those we can store and process on a given machine.\n",
"\n",
"Here is another example, Python's [`math.log`](https://docs.python.org/3/library/math.html#math.log):\n",
"\n",
"```python\n",
">>> from math import log\n",
">>> log(-2)\n",
"Traceback (most recent call last):\n",
" File \"\", line 1, in \n",
"ValueError: math domain error\n",
">>>\n",
"```\n",
"\n",
"We have to be careful about how we define the *domain* of a function.\n",
"In math class, you have probably heard, \"The domain of the natural logarithm is all positive real numbers\".\n",
"In this context, the natural logarithm is a *total function*.\n",
"It is defined (an output exists) for every value in the domain.\n",
"\n",
"Programmers tend not to think in those restrictive terms, and thankfully, mathematicians provide us with the terminology to handle these situations.\n",
"If we expand our definition of domain a bit, then we can consider *partial functions*.\n",
"What if I want to define the domain of the natural logarithm as all the reals, positive and negative?\n",
"In this context, the natural logarithm becomes a *partial function* because there are elements of the input set that do not map to the output set (range or co-domain).\n",
"In other words, there are some inputs that are invalid.\n",
"\n",
"The `add` function defined earlier is total.\n",
"This is because Python integers are only bound by system resources.\n",
"The `get_val` function defined earlier is a partial function.\n",
"In OCaml, `List.hd` returns the first element of a list.\n",
"This function is partial because it will fail on an empty list.\n",
"\n",
"This may sound like a silly mathematical exercise, but looking at your code in this light is an important skill.\n",
"Partial functions will fail under certain conditions.\n",
"We can make them total functions through a type system.\n",
"In a language like Python, we have to rely on data sanitation and validation.\n",
"\n",
"Before you run off and create custom types for all of your functions, consider the tradeoffs.\n",
"Why doesn't everyone program like this?\n",
"The reason is because this kind of type safety comes at the cost of complexity.\n",
"Maybe dealing with an exception is a simpler, more elegant solution to your problem than creating a `positive_reals` data structure.\n",
"And maybe the problem in question is a mission-critical piece of business logic, and some of us like to try to sleep soundly at night."
]
},
{
"cell_type": "markdown",
"id": "caf44478",
"metadata": {},
"source": [
"### Recursion\n",
"\n",
"Most developers are aware of recursion, and it is supported by most programming languages.\n",
"Recursion is another first-class feature of functional languages.\n",
"Haskell has no loops, relying exclusively on recursion.\n",
"Recursion is inefficient in some languages, and care should be taken when dealing with large data structures.\n",
"Read about tail recursion in [Haskell](https://wiki.haskell.org/Tail_recursion) and [OCaml](https://www.cs.cornell.edu/courses/cs3110/2020fa/textbook/data/tail_recursion.html).\n",
"\n",
"```python\n",
">>> l = []\n",
">>> for i in range(10):\n",
"... l.append(i)\n",
"...\n",
">>> l\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
">>>\n",
"```\n",
"\n",
"Don't let the syntax scare you too much.\n",
"There is a **lot** to unpack here.\n",
"This is simply to demonstrate that we don't _need_ loops.\n",
"One possible recursive solution in OCaml.\n",
"\n",
"```ocaml\n",
"utop # let rec f n acc = match n with \n",
"| 0 -> acc\n",
"| _ -> f (n - 1) ((n - 1) :: acc);;\n",
"val f : int -> int list -> int list = \n",
"\n",
"utop # let _ = f 10 [];;\n",
"- : int list = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]\n",
"```\n",
"\n",
"The `rec` keyword tells the compiler that this is a recursive function.\n",
"This defines a function named `f` that takes an integer `n` and a list of integers `acc`. Finally, a list of integers is the return type."
]
},
{
"cell_type": "markdown",
"id": "4eb03c6b",
"metadata": {},
"source": [
"### Pattern matching\n",
"\n",
"The `switch` statement of functional programming, but better and more powerful.\n",
"This was shown earlier, now I'll break it down a bit.\n",
"\n",
"```ocaml\n",
"let rec f n acc = match n with \n",
"| 0 -> acc\n",
"| _ -> f (n - 1) ((n - 1) :: acc)\n",
"```\n",
"\n",
"`match n with` says match this variable with a value (or even a type).\n",
"The first case is `0` and the underscore means we don't care (OCaml enforces unused variables just like golang).\n",
"This is useful in a recursive function becaus we can identify edge conditions that signal the termination of the loop.\n",
"It also saves us from `if` `then` Hades.\n",
"Also notice that there are no types in this function definition!\n",
"OCaml and Haskell have powerful type inferencing mechanisms, so annotations are rarely needed.\n",
"Speaking of types, OCaml is strongly-typed, right?\n",
"Why would we need to be able to match on a type?\n",
"Read on!"
]
},
{
"cell_type": "markdown",
"id": "6714d7c3",
"metadata": {},
"source": [
"### Sum types\n",
"\n",
"Algebraic data types are well-supported in FP languages.\n",
"An option is a sum type that acts as a container for possibly empty values (see Tony Hoare's talk on the [billion-dollar mistake](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/)).\n",
"This is a parameterized type because the inner value takes on the type of the parameter passed to the constructor (I'll explain below).\n",
"\n",
"```ocaml\n",
"utop # type 'a option =\n",
"| Some of 'a\n",
"| None;;\n",
"type 'a option = Some of 'a | None\n",
"```\n",
"\n",
"Going back to pattern-matching, we can match on types as well:\n",
"\n",
"```ocaml\n",
"let f = function\n",
"| Some v -> Some (v + 2)\n",
"| None -> None;;\n",
"val f : int option -> int option = \n",
"\n",
"utop # let _ = f v;;\n",
"- : int option = Some 44\n",
"```\n",
"\n",
"Notice here that the type isn't `'a option` which is our \"generic\" option.\n",
"This option has been paramaterized by the `int` type.\n",
"OCaml is able to determine this entirely through type-inferencing because we called the `+` function!\n",
"\n",
"On one hand neat, but on the other hand, am I saying that you have to write special functions just to deal with containers?\n",
"Don't worry!\n",
"This isn't golang!\n",
"The monadic interface is supported as well (monads will get covered in another article).\n",
"The following code leverages the built-in `Option` type.\n",
"\n",
"```ocaml\n",
"utop # let v = Some 42;;\n",
"val v : int Option = Some 42\n",
"\n",
"utop # Option.map ((+) 2) v;; \n",
"- : int Option = Some 44\n",
"\n",
"utop # let v = None;;\n",
"val v : 'a option = None\n",
"utop # Option.map ((+) 2) v;;\n",
"- : int option = None\n",
"utop #\n",
"```\n",
"\n",
"These are called sum types because the cardinality of the set is the sum of the cardinalities of the member types of the set.\n",
"Scott Wlashin has a [great video](https://vimeo.com/113707214) on how this concept is useful to programmers."
]
},
{
"cell_type": "markdown",
"id": "8d39c2b9",
"metadata": {},
"source": [
"### Product types\n",
"\n",
"Does that mean there is such a thing as product types?\n",
"Of course!\n",
"These are hidden away in what Pythonistas know as tuples.\n",
"\n",
"```python\n",
">>> (42, \"abc\")\n",
"(42, 'abc')\n",
">>> type((42, \"abc\"))\n",
"\n",
">>>\n",
"```\n",
"\n",
"If we were to use a type annotation, it would be `Tuple[Int, String]`.\n",
"Looking back at cardinalilities, this is a product type because the cardinality of the combined type is the product of its members.\n",
"These don't have to be 2-tuples, either, any permutation is allowed.\n",
"\n",
"```ocaml\n",
"utop # let t = (42, \"forty-two\");;\n",
"val t : int * string = (42, \"forty-two\")\n",
"```\n",
"\n",
"Notice the `*` in the type anotation above.\n",
"You know, like multiplication!\n",
"Can we pattern match on product types?\n",
"Yes!\n",
"\n",
"```ocaml\n",
"utop # let f v = match v with\n",
"| (42, _) -> \"You really like Douglas Adams!\"\n",
"| _ -> \"What a boring tuple\";;\n",
"val f : int * 'a -> string = \n",
"\n",
"utop # let _ = f t;;\n",
"- : string = \"You really like Douglas Adams!\"\n",
"\n",
"utop # let _ = f (99, 22);;\n",
"- : string = \"What a boring tuple\"\n",
"\n",
"utop # \n",
"```\n",
"\n",
"You may notice that I didn't provide anything useful in the second argument of the pattern match.\n",
"This is why the REPL annotates it as `'a`.\n",
"That means that the function will accept any type in that position.\n",
"The typing system is incredibly powerful once you sort it out in your head.\n"
]
},
{
"cell_type": "markdown",
"id": "5ad47e41",
"metadata": {},
"source": [
"## Next steps\n",
"\n",
"All of these topics are covered in great detail by the smart people of the interwebs.\n",
"My goal was to introduce these ideas from a Pythonista's frame of mind since Python is still my \"daily driver\".\n",
"I didn't cover some important topics like composition and thinking with types.\n",
"They deserve more thorough coverage, and I hope to tackle each of them in the near future.\n",
"\n",
"Can you use these techniques in Python?\n",
"Yes, of course!\n",
"I do encourage you to learn a bit of Haskell or OCaml first.\n",
"For me, leaving the comfort of Python really made this material \"click\".\n",
"You also need to be acutely aware of the limitations of Python and where these constructs fall apart.\n",
"\n",
"### My favorite Python/FP libraries\n",
"\n",
"- [pyrsistent](https://github.com/tobgu/pyrsistent/)\n",
"- [returns](https://returns.readthedocs.io/en/latest/)\n",
"- [toolz](https://toolz.readthedocs.io/en/latest/)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.10"
},
"nikola": {
"category": "",
"date": "2021-06-01 00:05:51 UTC-05:00",
"description": "",
"link": "",
"slug": "intro-to-functional-programming-ideas",
"tags": "python,ocaml,functional-programming",
"title": "Introduction to Functional Programming Ideas",
"type": "text"
}
},
"nbformat": 4,
"nbformat_minor": 5
}