{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "l15-c000",
   "metadata": {},
   "source": [
    "# Lecture 15 - A look at other programming languages\n",
    "\n",
    "<!-- <a rel=\"license\" href=\"https://creativecommons.org/licenses/by/4.0/\" target=\"_blank\"><img alt=\"Creative Commons Licence\" style=\"border-width:0\" src=\"https://licensebuttons.net/l/by/4.0/88x31.png\" title=\"This work is licensed under a Creative Commons Attribution 4.0 International License.\" align=\"right\"/></a> -->\n",
    "\n",
    "**Authors:** Fiona McNeill, Matteo Degiacomi, Rayo Verweij, and Nigel Topham\n",
    "\n",
    "## Introduction\n",
    "\n",
    "So far in this course, we have been writing Python. But Python is just one of *many* programming languages out there. Estimates of how many have ever been created run into the thousands, and perhaps a few dozen are in everyday professional use at any one time. What are they like? And what are the main differences between them?\n",
    "\n",
    "### Learning outcomes\n",
    "\n",
    "In this notebook, we'll discuss:\n",
    "\n",
    "- why there are so many programming languages, and what problems each was designed to solve;\n",
    "- the difference between a language, its implementation, and the machine that runs it;\n",
    "- compiled versus interpreted languages, and static versus dynamic typing;\n",
    "- imperative, functional, and declarative ways of solving the same problem;\n",
    "- why a task can be short in one language and long in another;\n",
    "- choosing a language for a problem, and justifying that choice; and\n",
    "- which of your skills will transfer to a language you have never seen before.\n",
    "\n",
    "### Using the notebook\n",
    "\n",
    "Remember, this notebook is _yours_! You can edit each cell, for example by adding new examples or changing values to see what happens. Feel free to experiment!\n",
    "\n",
    "Heads-up: many of the code blocks in this notebook are **not Python**, and are only there for you to read. Every code cell you can actually run is Python, and you will not need anything beyond the standard library and NumPy.\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "A common approach for learning how to read and write code in a structured way is called **PRIMM**:\n",
    "1. **Predict**: before running the code, look at it - do you understand each line? What do you think will happen?\n",
    "2. **Run**: now run the code and see what output you get.\n",
    "3. **Investigate**: did it go as you thought it would? If not, can you figure out why?\n",
    "4. **Modify**: now change the code and once again try to predict the output. If you got it wrong the first time, did you get it right now?\n",
    "5. **Make**: finally, try to write your own program from scratch using the skills you learned.\n",
    "\n",
    "You can apply steps 1-4 to each code cell in the notebook and many will have prediction prompts to help you get started. In addition, there will be challenges that ask you to put everything together yourself and execute step 5. There will often be multiple ways to solve these, but each challenge has a potential answer listed.\n",
    "\n",
    "</details>\n",
    "\n",
    "### Navigating the notebook\n",
    "\n",
    "A Jupyter notebook can be operated with your keyboard. Here is a **cheat sheet**:\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "- To run the selected cell and move to the next cell, press <kbd>&#x21E7; Shift</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To run the selected cell and keep focus there, press <kbd>⌃ Ctrl</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To create a cell under the one currently highlighted, press <kbd>B</kbd>;\n",
    "- To delete the currently highlighted cell, press <kbd>D</kbd> twice (be careful with this one!) or press <kbd>X</kbd> to cut it;\n",
    "- To get help for a specific function, place the cursor within the function's brackets, hold <kbd>&#x21E7; Shift</kbd>, and press <kbd>&#x21E5; Tab</kbd>.\n",
    "\n",
    "</details>\n",
    "\n",
    "Watch out: **code cells remember what happened in cells before**. So, especially in the more complicated notebooks later down the line, make sure to always run **every** cell from top to bottom, as one might rely on a piece of code that came before it! If your results become confusing, use **Kernel > Restart Kernel** and then rerun all the completed cells in order.\n",
    "\n",
    "### Further reading and practice\n",
    "\n",
    "- Official Python documentation: [Regular expressions](https://docs.python.org/3/library/re.html), if you would like to learn more about them.\n",
    "- Helsinki Python MOOC: [Regular expressions](https://programming-26.mooc.fi/part-12/4-regular-expressions), if you would like to learn more about them.\n",
    "- [NumPy: the absolute basics for beginners](https://numpy.org/doc/stable/user/absolute_beginners.html) - read the introduction to arrays if you want to explore the numerical comparison in Section 5.\n",
    "- [The Esoteric Languages Wiki](https://esolangs.org/) - choose a language and explain one trade-off in its design.\n",
    "- Alan J. Perlis, \"Special Feature: Epigrams on programming\", *ACM SIGPLAN Notices* 17(9), 1982, 7–13, [doi:10.1145/947955.1083808](https://doi.org/10.1145/947955.1083808).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c001",
   "metadata": {},
   "source": [
    "## 1. Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c002",
   "metadata": {},
   "source": [
    "Let's start by getting a sense of just how *different* programming languages can be.\n",
    "\n",
    "Below is a small weather file, in the same shape as the one from Assignment 2: comma-separated, with a header, and with `NA` marking missing readings. Our task is to calculate the mean temperature over all the usable readings, and count how many readings were usable. We're going to solve it four times, in four different languages.\n",
    "\n",
    "First off, our familiar Python:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c003",
   "metadata": {},
   "outputs": [],
   "source": [
    "DATA = \"\"\"date,temperature_c,rainfall_mm\n",
    "2025-11-01,8.1,0.0\n",
    "2025-11-02,7.4,2.6\n",
    "2025-11-03,NA,1.2\n",
    "2025-11-04,9.9,-1.0\n",
    "2025-11-05,6.2,0.4\n",
    "2025-11-06,10.3,5.1\n",
    "2025-11-07,5.8,NA\n",
    "\"\"\"\n",
    "\n",
    "lines = DATA.strip().split(\"\\n\")\n",
    "header = lines[0].split(\",\")\n",
    "rows = [line.split(\",\") for line in lines[1:]]\n",
    "\n",
    "print(header)\n",
    "print(rows[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c004",
   "metadata": {},
   "source": [
    "**Predict:** How many usable temperature readings are there? Roughly what do you expect the mean to be?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c005",
   "metadata": {},
   "outputs": [],
   "source": [
    "column = header.index(\"temperature_c\")\n",
    "\n",
    "total = 0.0\n",
    "count = 0\n",
    "for row in rows:\n",
    "    field = row[column]\n",
    "    if field != \"NA\":\n",
    "        total += float(field)\n",
    "        count += 1\n",
    "\n",
    "print(f\"mean {total / count:.2f} over {count} readings\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c006",
   "metadata": {},
   "source": [
    "### C\n",
    "\n",
    "Now let's look at the very same program written in **C**, the language that most modern languages are ultimately based on and in which the core of most operating systems is written.\n",
    "\n",
    "```c\n",
    "#include <stdio.h>\n",
    "#include <stdlib.h>\n",
    "#include <string.h>\n",
    "\n",
    "int main(void) {\n",
    "    FILE *file = fopen(\"weather.csv\", \"r\");\n",
    "    if (file == NULL) {\n",
    "        fprintf(stderr, \"cannot open file\\n\");\n",
    "        return 1;\n",
    "    }\n",
    "\n",
    "    char line[256];\n",
    "    double total = 0.0;\n",
    "    int count = 0;\n",
    "\n",
    "    fgets(line, sizeof line, file);              /* discard the header */\n",
    "\n",
    "    while (fgets(line, sizeof line, file) != NULL) {\n",
    "        strtok(line, \",\");                       /* the date, not needed */\n",
    "        char *temperature = strtok(NULL, \",\");\n",
    "        if (temperature != NULL && strcmp(temperature, \"NA\") != 0) {\n",
    "            total += atof(temperature);\n",
    "            count += 1;\n",
    "        }\n",
    "    }\n",
    "\n",
    "    fclose(file);\n",
    "\n",
    "    if (count == 0) {\n",
    "        fprintf(stderr, \"no usable values\\n\");\n",
    "        return 1;\n",
    "    }\n",
    "\n",
    "    printf(\"mean %.2f over %d readings\\n\", total / count, count);\n",
    "    return 0;\n",
    "}\n",
    "```\n",
    "\n",
    "Don't panic! Even if this course was your first ever foray into programming, you can probably read most of this. We import (include) libraries at the top, our code runs inside of a `main()` function, and just like in Python we accumulate a total using an `if` statement inside of a `while` loop.\n",
    "\n",
    "Of course, C sometimes uses different names and syntax for things, such as `void` instead of `None` and `strtok()` instead of `split()`. The main difference, though, is that C explicitly makes you define what types a variable has: `total` is a `double` (a floating-point number) and `count` is an `int`. In addition, C does not have Boolean types, so functions have to return `1` or `0` instead."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31171e9c-3a48-44b6-8210-5399b83f7dc5",
   "metadata": {},
   "source": [
    "### awk\n",
    "\n",
    "Not all languages follow these designs, however. In **awk**, this entire program could be written as just one line of code:\n",
    "\n",
    "```bash\n",
    "awk -F, 'NR>1 && $2!=\"NA\" {total+=$2; n++} END {print total/n, n}' weather.csv\n",
    "```\n",
    "\n",
    "This will be a lot more difficult to read! awk is a language from 1977 that was designed specifically for text processing and data extraction. So while it can solve this task in just one line, it does not have the full suite of functionality that more general-purpose languages like Python or C have."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "474268a7-5bd5-48b3-9842-6793d1089ab2",
   "metadata": {},
   "source": [
    "### SQL\n",
    "\n",
    "Python, C, and awk are all *scripting* languages, used to automate tasks, but that is not the only type of programming language. For example, **SQL** is a *query* language, used for retrieving information from databases.\n",
    "\n",
    "Python comes with a small database engine, called sqlite, built-in. In the snippet of code below, we use Python to set up the database and then supply strings with SQL arguments to Python functions - using one programming language inside of another one!\n",
    "\n",
    "`CREATE TABLE` creates the table `readings` with the columns from our data file. Then, `INSERT INTO` adds the data from our file into the table, and the `SELECT` query retrieves both the average of the temperature column as well as the count of instances where the temperature is not *NA*. Even if you are unlikely to know what all the Python commands or SQL syntax in this piece of code mean, careful reading of the strings will probably at least give you some idea of what the code does!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c007",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sqlite3\n",
    "\n",
    "connection = sqlite3.connect(\":memory:\")\n",
    "connection.execute(\"CREATE TABLE readings (date TEXT, temperature_c TEXT, rainfall_mm TEXT)\")\n",
    "connection.executemany(\"INSERT INTO readings VALUES (?, ?, ?)\", rows)\n",
    "\n",
    "query = \"SELECT AVG(temperature_c), COUNT(*) FROM readings WHERE temperature_c != 'NA'\"\n",
    "mean_temperature, usable = connection.execute(query).fetchone()\n",
    "\n",
    "print(f\"mean {mean_temperature:.2f} over {usable} readings\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c008",
   "metadata": {},
   "source": [
    "Each language accomplished the same task, just in a different way! In this lecture, we'll explore exactly where the differences in languages come from, and which types are better for certain tasks than others.\n",
    "\n",
    "<div class=\"alert alert-info\">\n",
    "<b>Note: the last decimal digit</b>\n",
    "\n",
    "If you print the Python and SQL results with all their decimals, you may spot that they are not identical: on our machine, Python gives `7.949999999999999` and SQL gives `7.95`. That's because adding up decimal numbers on a computer is not perfectly exact (remember Lecture 13), and different engines add them up in different ways!\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c009",
   "metadata": {},
   "source": [
    "### A brief history"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c010",
   "metadata": {},
   "source": [
    "The first computers were programmed by physically flipping switches, rewiring plugboards, or punching numbers onto cards. Back then, a program was literally a long list of numbers. Ever since, programs have increasingly become *more abstract*: becoming less computer-readable and more human-readable.\n",
    "\n",
    "The first iteration of this was [**assembly language**](https://en.wikipedia.org/wiki/Assembly_language), created by Kathleen Booth, with Andrew Booth, in 1947. Instead of numbers, assembly used short words to give instructions, such as `ADD EAX, EBX`. While this was a great improvement, each different type of computer still needed its own assembly language.\n",
    "\n",
    "This changed with the creation of the first **compilers**. A compiler is a program that translates source code into another representation, such as machine instructions. Having compilers handle the specificities of each type of computer architecture finally enabled programmers to write code that was *machine-agnostic*, that is, it works on any computer. This enabled several waves of new programming languages, now designed to solve specific problems rather than work on specific hardware.\n",
    "\n",
    "| Era | Computers of the time | Language(s) | Problems set out to solve |\n",
    "| --- | --- | --- | --- |\n",
    "| late 1950s | mainframes | Fortran | scientists wanted to write formulas instead of machine instructions |\n",
    "| late 1950s | mainframes | COBOL | businesses needed readable programs for records and reports |\n",
    "| late 1950s | mainframes | Lisp | symbolic work needed recursion and code that manipulates code |\n",
    "| late 1950s | mainframes | ALGOL | introduced code blocks to create cleaner syntax |\n",
    "| 1960s | time-sharing terminals | BASIC | students outside science needed to use a shared computer |\n",
    "| 1970s | minicomputers running Unix | C | having one portable language for writing operating systems |\n",
    "| late 1980s–1990s | personal computers and workstations | Perl, Python, Ruby | as computers improved, language usability became more important than speed |\n",
    "| 1990s | the internet | Java, JavaScript, PHP | the internet arrived, and code had to run in browsers and on web servers |\n",
    "| late 2000s–2010s | multicore processors and smartphones | Go, Rust, Swift, Julia | integrating the latest advances in processor design and safety |\n",
    "\n",
    "New languages rarely start from scratch: each borrows ideas from earlier ones. In the family tree below, the main languages of this course sit at the year they first appeared, and an arrow means that ideas passed from one language to the next (both languages' English Wikipedia articles list the influence).\n",
    "\n",
    "![Family tree of the main programming languages, from Fortran to Swift](l15_language_tree_course.png)\n",
    "\n",
    "That a language is old does not necessarily mean it has been superseded: for example, COBOL is still widely used in banking, and C remains to this day one of the most-used programming languages in the world."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c016",
   "metadata": {},
   "source": [
    "## 2. Compilation and type systems\n",
    "\n",
    "Strictly speaking, what we call Python is a **specification** of a language: a large document that describes what Python code should do. There are several different **implementations** of Python that make computers able to handle Python code. The most common one is called **CPython**, and is written in C. Other Python implementations include PyPy and MicroPython, which enable Python to run on different types of hardware from 'regular' computers.\n",
    "\n",
    "When you run Python code using CPython, then, the program that actually translates your Python into code your computer can read, is written in C. This is also what distinguishes syntax errors from runtime errors, as discussed in Lecture 13. Syntax errors are caught during compilation: CPython fails to translate your code because you did not adhere to its specification. Runtime errors, however, are only encountered *after* this step, when the code has been translated and is already running.\n",
    "\n",
    "We can actually demonstrate this because Python includes a neat `compile()` function that takes in a string and compiles it as a line of code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c017",
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    compile(\"total = 1 +\", \"<demo>\", \"exec\")\n",
    "except SyntaxError as error:\n",
    "    print(\"Found before execution:\", error)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c018",
   "metadata": {},
   "source": [
    "In the `compile()` function, the first parameter is the line to be compiled, the second parameter is what you call the 'file' you are pretending to work in (used to display any error messages), and the third parameter is the *mode* for the function. The `\"exec\"` means the source contains statements to execute."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c021",
   "metadata": {},
   "source": [
    "### Static vs dynamic typing"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c022",
   "metadata": {},
   "source": [
    "Every language has a **type system**: a set of rules that decides which operations you are allowed to perform on which values. We've already discussed Python's built-in types many types, as well as how you can create your own ones through building classes.\n",
    "\n",
    "A major differentiatior between languages is *when* they check a program's types:\n",
    "- In a **dynamically typed** language, like Python, the rules are checked while the program is running; but\n",
    "- In a **statically typed** language, like Java or C, they are checked before the program runs.\n",
    "\n",
    "In statically typed languages, you are required to specify in your code which type each value is, such as in the C snippet above. While Python provides type hints to simulate some of this behaviour, as discussed in the previous lecture, type hints are not actually checked during compilation.\n",
    "\n",
    "This means the following Python program is perfectly valid... right up until the moment it runs into trouble.\n",
    "\n",
    "**Predict:** Which of the two calls is going to fail, and when?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c023",
   "metadata": {},
   "outputs": [],
   "source": [
    "def risky(input):\n",
    "    return \"total: \" + input\n",
    "\n",
    "print(risky(\"ten\"))\n",
    "print(risky(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c024",
   "metadata": {},
   "source": [
    "Now compare the function with a **Java** definition, where the parameter type is written in the code:\n",
    "\n",
    "```java\n",
    "static String risky(String userInput) {\n",
    "    return \"total: \" + userInput;\n",
    "}\n",
    "\n",
    "risky(10);\n",
    "```\n",
    "\n",
    "Java's compiler would reject this particular call before it runs, similar to how it would catch syntax errors, whereas in Python it would be a runtime error.\n",
    "\n",
    "People disagree on whether dynamic typing or static typing is the 'best', and to some extent this is simply a matter of taste. Statically typed languages often allow for early catching of type-related bugs and many programmers enjoy the peace of mind that static typing gives them as it forces you to be precise. However, being forced to define types can sometimes get complex and does make programs a bit less flexible in some cases."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c026",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: add type hints</b>\n",
    "\n",
    "[UPDATE]\n",
    "\n",
    "Imagine a program that reads a setting from a file and multiplies it by 2. Unfortunately, the setting arrives as the string `\"5\"`.\n",
    "\n",
    "In one sentence each, write down what happens in Python, and whether Java would accept the expression `\"5\" * 2`. Then decide which behaviour you would prefer for (a) a script you will only run once, and (b) software controlling a hospital drug pump.\n",
    "\n",
    "If you are not sure what Python does, try it out in the cell below before writing your answer!\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c027",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# What happens in Python:\n",
    "\n",
    "# What would happen in a statically typed language:\n",
    "\n",
    "# Which I'd prefer for (a) and (b), and why:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c028",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "Python evaluates `\"5\" * 2` as `\"55\"`, because multiplying a string by an integer means repetition. The program runs, but its answer does not match the intended calculation. Java does not define this multiplication for strings and integers, so it rejects this expression during compilation. Another statically typed language could define string repetition; the result depends on its rules, not just when it checks types.\n",
    "\n",
    "For a small script, Python may be convenient, but we still need a test confirming that the input is converted to a number. For a drug pump, early type checks are useful though we would still need careful requirements, testing, and review. The choice of language alone does not establish that software is safe!\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c029",
   "metadata": {},
   "source": [
    "## 3. Programming paradigms"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c030",
   "metadata": {},
   "source": [
    "Programming languages differ not just on the level of hardcoded design decisions, such as their type systems, but also in the *style* of programming they prefer. Over the decades, several **paradigms** have emerged. Languages often don't enforce just one paradigm; Python, for example, supports several of them. However, languages are often *optimised* for one particular paradigm.\n",
    "\n",
    "Broadly speaking, there are two types of programming paradigms.\n",
    "\n",
    "**Imperative paradigms** focus on *how* a program runs, that is, describing step by step what a program needs to do. In this course so far, we have mostly programmed imperatively.\n",
    "\n",
    "**Declarative paradigms**, by contrast, focus on *what* needs to happen, that is, describing the result you want, often as some kind of mathematical function."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4ca2a62b",
   "metadata": {},
   "source": [
    "### Imperative paradigms\n",
    "\n",
    "**Procedural programming** is what we've seen most of so far: you describe the *steps* of your algorithm one-by-one, updating variables as you go."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c031",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Getting the average temperature in a procedural way\n",
    "# Run the cells in Section 1 before running this one!\n",
    "total = 0.0\n",
    "count = 0\n",
    "for row in rows:\n",
    "    if row[column] != \"NA\":\n",
    "        total += float(row[column])\n",
    "        count += 1\n",
    "\n",
    "print(\"imperative  :\", round(total / count, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c80cfbd5",
   "metadata": {},
   "source": [
    "**Object-oriented programming** is a related imperative paradigm in which code is structured as objects that are instances of classes. We have seen a glimpse of this already and will dive even deeper into this next week. Python supports both procedural and object-oriented programming and makes it easy to mix them."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "021cf6ed",
   "metadata": {},
   "source": [
    "### Declarative paradigms\n",
    "\n",
    "If you're used to programming imperatively, declarative writing may require you to switch perspectives a bit. What does it mean, programming by declaring results, rather than the steps the program needs to take?\n",
    "\n",
    "We've actually already seen an example above: **data-driven programming**, often employed by database query languages, work this way. When writing the SQL query below, you don't specify how the rows are visited, or in which order things are added up; you simply specify that it should happen, and the language takes care of it for you."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6c94fd53",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Getting the average temperature through a database query\n",
    "# Run the cells in Section 1 before running this one!\n",
    "declarative = connection.execute(\n",
    "    \"SELECT ROUND(AVG(temperature_c), 2) FROM readings WHERE temperature_c != 'NA'\"\n",
    ").fetchone()[0]\n",
    "\n",
    "print(\"declarative :\", declarative)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c032",
   "metadata": {},
   "source": [
    "In **functional programming**, you constantly create functions that constantly map new values to other values, rather than updating variables step by step. Python is not a functional programming language, however, has borrowed some styles from functional languages over time, such as list comprehensions. We'll look more at functional-style programming in Lecture 18."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c033",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Getting the average temperature in a functional way\n",
    "# Run the cells in Section 1 before running this one!\n",
    "usable = [float(row[column]) for row in rows if row[column] != \"NA\"]\n",
    "print(\"functional  :\", round(sum(usable) / len(usable), 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c034",
   "metadata": {},
   "source": [
    "In a 'pure' functional language like **Haskell**, created by University of Edinburgh researchers, you cannot even update a variable after you have assigned it! \n",
    "\n",
    "```haskell\n",
    "mean :: [Double] -> Double\n",
    "mean values = sum values / fromIntegral (length values)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c037",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: the same question, three ways</b>\n",
    "\n",
    "Calculate the total rainfall, treating both `NA` and any negative value as unusable, and also report how many values you had to reject.\n",
    "\n",
    "Write it once as a loop, and once as a comprehension. Feeling brave? Have a go at the SQL version too!\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c038",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "rain = header.index(\"rainfall_mm\")\n",
    "\n",
    "# Loop version\n",
    "\n",
    "# Comprehension version\n",
    "\n",
    "# SQL version (optional)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c039",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "rain = header.index(\"rainfall_mm\")\n",
    "\n",
    "# Loop version\n",
    "total_rain = 0.0\n",
    "rejected = 0\n",
    "for row in rows:\n",
    "    field = row[rain]\n",
    "    if field == \"NA\" or float(field) < 0:\n",
    "        rejected += 1\n",
    "    else:\n",
    "        total_rain += float(field)\n",
    "print(round(total_rain, 1), rejected)\n",
    "\n",
    "# Comprehension version\n",
    "values = [row[rain] for row in rows]\n",
    "usable_rain = [float(v) for v in values if v != \"NA\" and float(v) >= 0]\n",
    "print(round(sum(usable_rain), 1), len(values) - len(usable_rain))\n",
    "\n",
    "# SQL version\n",
    "rain_total, rain_count = connection.execute(\n",
    "    \"SELECT ROUND(SUM(CAST(rainfall_mm AS REAL)), 1), COUNT(*) FROM readings \"\n",
    "    \"WHERE rainfall_mm != 'NA' AND CAST(rainfall_mm AS REAL) >= 0\"\n",
    ").fetchone()\n",
    "print(rain_total, len(rows) - rain_count)\n",
    "```\n",
    "\n",
    "In the SQL query, `CAST(rainfall_mm AS REAL)` converts a stored text field to a number before comparison and addition. This sample contains only numeric text or `NA`; arbitrary bad text would need additional checks.\n",
    "\n",
    "All three should give you a total of 9.3 mm, with 2 values rejected: one `NA` and one negative reading.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c040",
   "metadata": {},
   "source": [
    "## 4. General-purpose versus domain-specific languages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c041",
   "metadata": {},
   "source": [
    "Some languages are designed for many kinds of program; others concentrate on a particular area. SQL, which we have already used, is an example of the latter.\n",
    "\n",
    "First, let's pin down what we actually mean by a programming language. For this notebook, a **programming language** is a notation with three properties:\n",
    "1. a defined syntax (the \"grammar\" or rules, that is, what you are allowed to write);\n",
    "2. a defined meaning for everything you can write (the *semantics*); and\n",
    "3. a machine that can carry that meaning out.\n",
    "\n",
    "A **domain-specific language** is designed around a particular area, such as database queries or text patterns. Some are computationally general despite that specialised purpose.\n",
    "\n",
    "You probably know a few of these already. SQL describes questions about tables. HTML describes the structure of web pages, and CSS describes how they look. LaTeX describes typeset documents. Spreadsheet formulas describe how cells depend on each other. And **regular expressions**, which we can run right here, describe patterns in text.\n",
    "\n",
    "Let's look at that one in a bit more detail by writing two functions to check valid postcodes, one in 'regular' Python and one using regular expressions. `re` is the built-in Python library for regular expressions. `re.compile(pattern)` prepares a pattern and `.match(text)` returns a match object, or `None` if the start of the text does not match. The `r` before the string marks a *raw string*, which preserves backslashes used by many regex patterns.\n",
    "\n",
    "For this pattern, `^` and `$` mark the start and end, `[A-Z]` means an uppercase letter, `[0-9]` a digit, `{1,2}` means one or two repetitions, and `?` makes the preceding part optional.\n",
    "\n",
    "The Python version of the function uses `.replace(\" \", \"\")` to remove spaces. `.isdigit()` and `.isalpha()` test whether text consists only of digits or only of letters, and `.isupper()` tests whether all the letters in the text are uppercase.\n",
    "\n",
    "**Predict:** The cell below checks whether a string looks like a UK postcode, in two different ways. Which one would you rather have to *modify*? And which one would you rather have to *explain* to someone else?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c042",
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "POSTCODE = re.compile(r\"^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$\")\n",
    "\n",
    "\n",
    "def looks_like_postcode(text):\n",
    "    return POSTCODE.match(text) is not None\n",
    "\n",
    "\n",
    "def looks_like_postcode_by_hand(text):\n",
    "    text = text.replace(\" \", \"\")\n",
    "    if len(text) < 5 or len(text) > 7:\n",
    "        return False\n",
    "    inward, outward = text[-3:], text[:-3]\n",
    "    if not inward[0].isdigit():\n",
    "        return False\n",
    "    if not (inward[1:].isalpha() and inward[1:].isupper()):\n",
    "        return False\n",
    "    if not (outward[0].isalpha() and outward[0].isupper()):\n",
    "        return False\n",
    "    for character in outward:\n",
    "        if character.isdigit():\n",
    "            return True\n",
    "    return False\n",
    "\n",
    "\n",
    "for candidate in [\"EH8 9AB\", \"EH89AB\", \"W1A 0AX\", \"eh8 9ab\", \"12345\", \"EH8 9A\", \"XYZ 1AB\", \"E!1 9AB\"]:\n",
    "    print(repr(candidate), \"regex:\", looks_like_postcode(candidate),\n",
    "          \"by hand:\", looks_like_postcode_by_hand(candidate))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c043",
   "metadata": {},
   "source": [
    "While both versions agree on the original examples, they disagree on `\"E!1 9AB\"`, as the hand-written checks overlook the punctuation in the outward part.\n",
    "\n",
    "Point being - while general-purpose languages can often do many different tasks, domain-specific languages might be more efficient at any one of them. While the regular expression version is a lot more compact, using it also requires you to learn another notation on top of Python. Whether that is worth it, depends on how well the people maintaining the program understand it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c044",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: is HTML a programming language?</b>\n",
    "\n",
    "Using the three-part definition above, decide whether each of the following is a programming language: HTML, SQL, Excel formulas, and the instructions on a shampoo bottle.\n",
    "\n",
    "Note that many people disagree on what exactly makes a programming language - for this exercise, it's not so much the answer that matters, and more so your reasoning *why*.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c045",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# HTML:\n",
    "\n",
    "# SQL:\n",
    "\n",
    "# Excel formulas:\n",
    "\n",
    "# The instructions on a shampoo bottle:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c046",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for possible answers</b></summary>\n",
    "\n",
    "There is not one right answer here, and even experienced programmers disagree. What matters is the reasoning you apply.\n",
    "\n",
    "- **HTML** meets our deliberately broad three-property definition: it has syntax, meaning, and a browser that interprets it. It is called a *markup language* because its purpose is to describe document structure - but whether that means it is or isn't a *programming* language is up to you.\n",
    "- **SQL** definitely calculates, although it deliberately limits what you can express. Modern SQL even supports recursive queries, so it is more powerful than it first looks.\n",
    "- **Excel formulas** calculate too, and since Excel added a function that lets a formula call itself, they can even do recursion. Lots of people have been programming for years without realising it.\n",
    "- **The shampoo bottle** has syntax and meaning, but no machine... so not a programming language by (almost) any definition.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c047",
   "metadata": {},
   "source": [
    "## 5. Speed"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c048",
   "metadata": {},
   "source": [
    "Some languages, and some ways of doing things *within* languages, are faster than others. Let's compare two implementations of a calculation: adding up squares of whole numbers. One uses our usual Python loop; the other uses **NumPy**, a Python library for numerical arrays.\n",
    "\n",
    "A NumPy array stores many values of the same numeric type, a bit like a specialised list. `np.arange(n, dtype=np.float64)` creates values from 0 to `n - 1`, stored as floating-point numbers. We can multiply two arrays to multiply matching entries, before `.sum()` adds the resulting entries.\n",
    "\n",
    "We can measure the speed of both operations by retrieving the time before and after they occur and looking at the difference. We use `time.perf_counter()` to return a clock reading. In the final output, `:.1e` displays a number in scientific notation with one decimal place.\n",
    "\n",
    "**Predict:** Which implementation do you expect to finish first? What might differ between the exact integer result and the floating-point result?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c049",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "import numpy as np\n",
    "\n",
    "n = 10 ** 7  # That is, 10,000,000. Go big or go home!\n",
    "\n",
    "\n",
    "def sum_of_squares(n):\n",
    "    total = 0\n",
    "    for i in range(n):\n",
    "        total += i * i\n",
    "    return total\n",
    "\n",
    "\n",
    "start = time.perf_counter()\n",
    "exact = sum_of_squares(n)\n",
    "python_seconds = time.perf_counter() - start\n",
    "\n",
    "values = np.arange(n, dtype=np.float64)\n",
    "start = time.perf_counter()\n",
    "fast = (values * values).sum()\n",
    "numpy_seconds = time.perf_counter() - start\n",
    "\n",
    "print(f\"plain Python : {python_seconds:.3f} s\")\n",
    "print(f\"NumPy        : {numpy_seconds:.4f} s\")\n",
    "print(f\"ratio        : {python_seconds / numpy_seconds:.0f} times faster\")\n",
    "print(f\"relative difference in the answer: {abs(int(fast) - exact) / exact:.1e}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c050",
   "metadata": {},
   "source": [
    "NumPy will usually finish this calculation much faster, though the exact ratio depends on your computer, library build, and measurements. This is because under-the-hood, NumPy stores numbers in one big block of memory and hands the actual maths over to compiled code. That compiled code is written in languages such as C and Fortran. \n",
    "\n",
    "Focussing on speed can have other trade-offs, however."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55ebc4cc-eb50-4b2f-9251-6e5f2211c17e",
   "metadata": {},
   "source": [
    "### The price of speed\n",
    "\n",
    "The numeric representation also affects which answers can be stored. `np.iinfo(np.int64).max` gives the largest value a NumPy 64-bit signed integer can hold.\n",
    "\n",
    "**Predict:** Python's integers can grow as big as they need to, however, NumPy's `int64` integers always use exactly 64 bits. What could happen if we repeat the sum using `int64`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c053",
   "metadata": {},
   "outputs": [],
   "source": [
    "integers = np.arange(n, dtype=np.int64)\n",
    "overflowed = int((integers * integers).sum())\n",
    "\n",
    "print(\"Python's answer :\", exact)\n",
    "print(\"NumPy's int64   :\", overflowed)\n",
    "print(\"agree?          :\", overflowed == exact)\n",
    "print(\"largest int64   :\", np.iinfo(np.int64).max)\n",
    "print(\"true value above that limit?\", exact > np.iinfo(np.int64).max)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c054",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-warning\">\n",
    "<b>Watch out: no warning!</b>\n",
    "\n",
    "The wrong answer arrived without a single warning. The true total is bigger than the largest number an `int64` can hold, so the sum wrapped around (a bit like an old car's mileage counter rolling back to zero), and ***nothing complained***. Python's own integers don't have this limit, and that flexibility is part of why they are slower: every addition works on general-purpose number objects that can grow as large as needed.\n",
    "</div>\n",
    "\n",
    "So here's the trade-off. Fixed-size integers are fast, but they can **overflow** without telling you. Python's integers can grow until your computer runs out of memory, but they are slower.\n",
    "\n",
    "All of this has just been to illustrate: some tools are faster than others, but may come with their own restrictions. For you, in the future, part of learning different programming languages will be learning more about these trade-offs, and learning how to pick the right tool for each job."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c058",
   "metadata": {},
   "source": [
    "## 6. Esoteric languages"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "596a8405",
   "metadata": {},
   "source": [
    "Okay, we've discussed a lot and it's almost time to wrap up... but not before we've had a laugh. **Esoteric languages** are programming languages that are usually designed to make a point or a joke, rather than to be used for real work.\n",
    "\n",
    "Anyone has the power to write a programming language... but with great power comes great responsibility."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c059",
   "metadata": {},
   "source": [
    "### Chef\n",
    "\n",
    "In **Chef**, programs look like cooking recipes. Here is the complete *Hello World Souffle*, one of the example programs published on the language's own website:\n",
    "\n",
    "```text\n",
    "Hello World Souffle.\n",
    "\n",
    "This recipe prints the immortal words \"Hello world!\", in a basically brute force way. It also makes a lot of food for one person.\n",
    "\n",
    "Ingredients.\n",
    "72 g haricot beans\n",
    "101 eggs\n",
    "108 g lard\n",
    "111 cups oil\n",
    "32 zucchinis\n",
    "119 ml water\n",
    "114 g red salmon\n",
    "100 g dijon mustard\n",
    "33 potatoes\n",
    "\n",
    "Method.\n",
    "Put potatoes into the mixing bowl. Put dijon mustard into the mixing bowl. Put lard into the mixing bowl. Put red salmon into the mixing bowl.\n",
    "Put oil into the mixing bowl. Put water into the mixing bowl. Put zucchinis into the mixing bowl.\n",
    "Put oil into the mixing bowl. Put lard into the mixing bowl. Put lard into the mixing bowl.\n",
    "Put eggs into the mixing bowl. Put haricot beans into the mixing bowl. Liquefy contents of the mixing bowl.\n",
    "Pour contents of the mixing bowl into the baking dish.\n",
    "\n",
    "Serves 1.\n",
    "```\n",
    "\n",
    "Every ingredient holds a number. The mixing bowl works like a stack of pancakes: each `Put` places a value on top, and serving the dish takes the values off the top, one at a time. `Liquefy` turns the numbers into characters, so each amount is really a character code. (Pouring copies the bowl into the baking dish in the same order, so in the cell below we serve straight from the bowl.)\n",
    "\n",
    "In Python, `chr(number)` does the same conversion, turning a character code into a one-character string. The cell below follows the recipe using a list as the mixing bowl: `.append()` puts a value on top, and `.pop()` takes the top one off again.\n",
    "\n",
    "**Predict:** Look at the amounts, and at the order in which the ingredients go into the bowl. What does the recipe print?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c060",
   "metadata": {},
   "outputs": [],
   "source": [
    "# The amounts, in the order the Method puts them into the mixing bowl\n",
    "amounts_in_order = [33, 100, 108, 114, 111, 119, 32, 111, 108, 108, 101, 72]\n",
    "\n",
    "bowl = []\n",
    "for amount in amounts_in_order:\n",
    "    bowl.append(amount)              # \"Put ... into the mixing bowl\": on top of the stack\n",
    "\n",
    "served = []\n",
    "while len(bowl) > 0:\n",
    "    served.append(chr(bowl.pop()))   # \"Serves 1\": off the top, as characters\n",
    "\n",
    "print(repr(\"\".join(served)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c060a",
   "metadata": {},
   "source": [
    "### Shakespeare\n",
    "\n",
    "In the **Shakespeare Programming Language**, programs look like plays. Its variables are characters from Shakespeare's plays, and they get their values from what the other characters say to them. Here's one line from the language's own *Hello World* program, in which Hamlet speaks to Ophelia:\n",
    "\n",
    "```text\n",
    "Hamlet:\n",
    " Thou art as lovely as the product of a large rural town and my amazing\n",
    " bottomless embroidered purse. Speak thy mind!\n",
    "```\n",
    "\n",
    "The rules for numbers go like this. Every noun is worth 1, or -1 if it's a nasty one, like 'pig'. Each adjective in front of a noun doubles it. 'Thou art as lovely as...' gives Ophelia her value, and 'Speak thy mind!' makes her say it out loud, as a character.\n",
    "\n",
    "**Predict:** What does Ophelia say?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c060b",
   "metadata": {},
   "outputs": [],
   "source": [
    "large_rural_town = 2 * 2 * 1                           # two adjectives: doubled twice\n",
    "amazing_bottomless_embroidered_purse = 2 * 2 * 2 * 1   # three adjectives: doubled three times\n",
    "\n",
    "ophelia = large_rural_town * amazing_bottomless_embroidered_purse\n",
    "print(ophelia, repr(chr(ophelia)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "32cbe6b5",
   "metadata": {},
   "source": [
    "Did you guess them? The recipe serves `'Hello world!'`, while Hamlet's whole flowery sentence makes Ophelia say... a single space! It's the gap between 'Hello' and 'World' in the Shakespeare program's output."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c061",
   "metadata": {},
   "source": [
    "### Interpreters and expressivity\n",
    "\n",
    "There are two lessons hiding in these cells.\n",
    "\n",
    "First, each cell carries out the steps of a program written in another language, using Python. That's the same idea as the compiler in Section 2, 'a program whose input is another program'. A real **interpreter** for Chef or Shakespeare would read the recipe or the play itself, rather than numbers we copied out by hand, and it would carry out the program instead of translating it.\n",
    "\n",
    "Second, `print(\"Hello world!\")` and that whole recipe do exactly the same thing. Both languages *look* friendly, since you can read every single word, but saying anything at all takes a huge effort. Being *able* to express something is not the same as being able to express it *well*. That's the difference between a language being **powerful** and a language being **expressive**.\n",
    "\n",
    "Chef and Shakespeare are far from the only joke languages out there:\n",
    "\n",
    "| Language | The joke | The point |\n",
    "| --- | --- | --- |\n",
    "| Whitespace | only spaces, tabs, and newlines count as code | syntax is a decision about human readers |\n",
    "| INTERCAL | some statements must say `PLEASE`: too few and the program is rejected as impolite, too many as over-polite | a language can have a sense of humour |\n",
    "| Rockstar | programs read like power ballads | source code is a genre with conventions |\n",
    "| Piet | programs are abstract paintings, run by colour | code does not have to be text at all |\n",
    "| Malbolge | designed to be as hard to program in as possible | its first working program is reported to have been found by a search program, not written by a person |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd909023-60f5-4767-9764-7efffa867b1b",
   "metadata": {},
   "source": [
    "### APL\n",
    "\n",
    "Now for one that looks quite esoteric but is absolutely *not* a joke. **APL** was designed in the 1960s and uses its own special set of symbols, letting you combine operations into very short expressions. Here's how you calculate the mean of `x`:\n",
    "\n",
    "```apl\n",
    "(+/x)÷≢x\n",
    "```\n",
    "\n",
    "That reads as 'the sum of `x`, divided by the number of items in `x`': our functional version from Section 4, squeezed into just eight characters.\n",
    "\n",
    "APL's descendants are reported to still be in use in parts of the finance industry, though not much, as you need a way to enter its symbols, such as an [APL keyboard layout](https://microapl.com/apl/introduction_chapter2.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c062",
   "metadata": {},
   "source": [
    "## 7. How to choose a language"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c063",
   "metadata": {},
   "source": [
    "Now we have everything we need to answer the big question: how do you actually choose a language? In practice, it is rarely about which language is the most elegant. Instead, it usually comes down to questions like these:\n",
    "\n",
    "1. **Does the platform decide for me?** It often does, and when it does, that beats everything else. Code that runs in a web browser means JavaScript (or WebAssembly). Programming a graphics card means CUDA or similar. C and Rust are common on small microcontrollers, while Swift is common for iPhone apps. Platforms can strongly constrain a choice even where alternatives exist.\n",
    "2. **Is there a library that already does most of the work?** A weekend in Python with a good library beats a month in a language where you have to build everything from scratch. That's why so much scientific computing happens in Python and R... not because they're somehow the 'best', but because they have large ecosystems and many people are familiar with them.\n",
    "3. **How fast does it need to be?** Most programs spend their time waiting for a disk, a network, or a person. Picking a fast language to speed up a program that's mostly waiting won't help much.\n",
    "4. **How bad would a bug be?** A script that tidies up a spreadsheet, a service that moves money around, and a device that delivers medicine are three very different levels of risk. This is something you might keep in mind, for example when deciding between dynamically or statically typed languages.\n",
    "5. **Is there existing code, and who will maintain it?** The answer to the first part is almost always 'some', and rewriting a working system in a nicer language can take quite a bit of time. As for the second part, the community that matters most is often not the whole world, but the people in your team.\n",
    "6. **Is it alive and well, and do your tools know it?** An active community, up-to-date documentation, a package manager that works, and helpful error messages are all part of what it is like to *use* a language. These days, so is how well AI assistants handle it: they tend to be more reliable in popular languages with lots of public code than in obscure ones.\n",
    "7. **Taste.** Yes, this counts! You'll write more code, and better code, in a language you enjoy. Try out different ones, and see what you like!\n",
    "\n",
    "It might seem like an impossible world out there, with dozens of competing programming languages, especially if this course is your first foray into programming. But don't worry too much about that. So far, in this course, we have seen:\n",
    "\n",
    "- breaking a problem down into steps and functions (Lectures 1 and 6)\n",
    "- variables, types, and expressions (Lectures 2 and 3)\n",
    "- repetition with loops (Lecture 4)\n",
    "- choosing a data structure that fits the way you need to use your data (Lectures 5 and 12)\n",
    "- reading an error message and working out what caused it (Lecture 13)\n",
    "- naming, structuring, and testing your code, so that other people can work with it (Lectures 9 and 14)\n",
    "\n",
    "None of these are specific to Python. What *is* Python-specific, and what you will have to look up every time you switch languages, is the syntax, the names of things in the standard library, and the tools. But good news: that is usually the easy part to pick up. It's thinking like a programmer that is often the big barrier, but here, at the end of Part 2, you're already a long way.\n",
    "\n",
    "> A language that doesn't affect the way you think about programming, is not worth knowing.\n",
    ">\n",
    "> Alan Perlis, *Epigrams on Programming*, 1982\n",
    "\n",
    "The point of learning a second language is not just that you might need it one day (although you very likely might). It's that meeting a new language shows you habits you never noticed you had, back when you only knew one way of doing things."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-consolidation-prompt",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "## Consolidation challenge\n",
    "\n",
    "We did not really do much coding this lecture - so instead, let's try a writing challenge, to bring some of the ideas we discussed today together.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: your first week at Polyglot Solutions</b>\n",
    "\n",
    "Congratulations, you've just been hired at *Polyglot Solutions*, a small software consultancy! Your first week is looking busy.\n",
    "\n",
    "Four clients have come to you for advice. For each one, pick a language, give the **one reason** you'd defend in a meeting, and name the **cost** you are knowingly accepting. There's no single correct answer, but an answer without a reason does not count!\n",
    "\n",
    "1. A research group has 40,000 lines of working Fortran that simulates airflow. Their new PhD student wants to rewrite it all in Python \"so that it's easier to read\".\n",
    "2. An online shop needs to check 500 million lines of log files against a pattern, every night, before 6 a.m.\n",
    "3. A hospital needs software that calculates how fast to give a patient a drug, based on their weight.\n",
    "4. A researcher needs a chart for a grant application that is due tomorrow morning.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-consolidation-work",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# 1.\n",
    "# 2.\n",
    "# 3.\n",
    "# 4."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-consolidation-solution",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "Here are some answers you could defend. Remember, it is the reason that counts.\n",
    "\n",
    "1. **Keep the Fortran!** 40,000 lines of working, tested code represent years of debugging, and a rewrite throws all of that away (and would probably run slower, too). The cost: the group needs to keep someone around who can read Fortran. A nice middle ground could be to write a Python interface on top of the existing Fortran... which is exactly how a lot of scientific Python already works.\n",
    "2. **A compiled language, or a tool built for the job, like `grep` or `awk`.** With this much data and a hard deadline, speed is what matters most, not how quickly you can write the program. The cost: the team must understand and maintain the chosen tool and its patterns. A short `awk` program may be quite readable to a team familiar with it.\n",
    "3. **A statically typed language with a track record in safety-critical software, such as Ada, Rust, or C written under strict rules**, plus whatever the regulators require. As we saw in Section 3, a whole class of errors can be ruled out before the software ever reaches a patient. The cost: the team needs suitable expertise and a rigorous validation process. That process takes time regardless of the language, though: while static typing can help catch some mistakes earlier, it definitely does not catch everything.\n",
    "4. **Python, or honestly, even a spreadsheet!** The only thing in short supply is time. The cost: there is little time to generalise the solution. Keep enough checks and notes to trust the chart, then decide later whether the task needs a reusable program.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-consolidation-summary",
   "metadata": {
    "tags": [
     "summary"
    ]
   },
   "source": [
    "## Summary\n",
    "\n",
    "Well done! In this lecture, we looked at where Python fits among its many relatives, and hopefully you are now convinced that what you have been learning all along is *programming*. Hopefully you're not feeling too lost in translation...\n",
    "\n",
    "### Key terms\n",
    "\n",
    "<dl>\n",
    "\t<dt><b>Programming language</b></dt>\n",
    "\t<dd>A notation with a defined syntax, a defined meaning for everything you can write, and a machine that can carry that meaning out.</dd>\n",
    "\t<dt><b>Domain-specific language</b></dt>\n",
    "\t<dd>A language designed for a particular area, such as questions about tables (SQL) or patterns in text (regular expressions).</dd>\n",
    "\t<dt><b>Implementation</b></dt>\n",
    "\t<dd>A program that runs code written in a particular language. CPython is one implementation of Python, written in C.</dd>\n",
    "\t<dt><b>Compiler</b></dt>\n",
    "\t<dd>A program that translates code into another representation, such as machine code or bytecode.</dd>\n",
    "\t<dt><b>Interpreter</b></dt>\n",
    "\t<dd>A program that carries out instructions expressed in source code or an intermediate representation.</dd>\n",
    "\t<dt><b>Semantics</b></dt>\n",
    "\t<dd>What a piece of code means, as opposed to its syntax, which is what you are allowed to type.</dd>\n",
    "\t<dt><b>Type system</b></dt>\n",
    "\t<dd>The rules a language uses to decide which operations are allowed on which values.</dd>\n",
    "\t<dt><b>Static typing</b></dt>\n",
    "\t<dd>Checking type rules before execution. This catches many incompatible operations early, but it does not prevent every runtime failure or incorrect result.</dd>\n",
    "\t<dt><b>Dynamic typing</b></dt>\n",
    "\t<dd>Checking the type rules while the program runs, so that type errors only appear when the line containing them is reached.</dd>\n",
    "\t<dt><b>Paradigm</b></dt>\n",
    "\t<dd>The style of solution a language makes easy. <em>Imperative</em> code describes steps, <em>functional</em> code describes values built from other values, and <em>declarative</em> code describes the result and leaves the method to the engine.</dd>\n",
    "\t<dt><b>Overflow</b></dt>\n",
    "\t<dd>What happens when a result is too big for the fixed number of bits used to store it. NumPy's <code>int64</code> arrays wrap in this example; other types and languages may have different rules.</dd>\n",
    "\t<dt><b>Esoteric language</b></dt>\n",
    "\t<dd>A language designed to make a point or a joke, rather than to be used for real work, such as Chef, Shakespeare, or Piet.</dd>\n",
    "</dl>\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
