LearnProgramming Course 1: Functional Programming

This lecture follows the first LearnProgramming route:

/course/functional

The central idea is familiar: spreadsheet formulas and code describe the same transformations.

ch01 — Raw Calculus

Before naming a function, calculate directly.

Spreadsheet JavaScript
=3 * 2 3 * 2
=10 + 5 10 + 5
=20 / 4 20 / 4

The operators are already programming: +, -, *, and /.

Raw Calculus: Try It

3 * 2       // 6
10 + 5      // 15
20 / 4      // 5
(3 + 2) * 4 // 20

The browser console and a spreadsheet are both places to test a calculation.

ch02 — Cells and Values

A spreadsheet column is a list of values. In JavaScript, the same idea is an array.

const A = [1, 2, 3, 4]
const B = [4, 5, 6, 7]
Spreadsheet idea JavaScript idea
Cell Value
Column Array
Formula Function

Cells Become Named Data

const scores = [85, 92, 78, 95, 88]
const name = "Alice"

scores[0] // 85
scores.length // 5

Give data useful names. Named data is easier to read and reuse than isolated numbers.

ch03 — Pure Functions

A function takes input, applies one rule, and returns output.

const add3 = x => x + 3

add3(1)  // 4
add3(10) // 13

The same input produces the same output. This is a pure function.

Spreadsheet Formula = Pure Function

Spreadsheet: =A1 + 3
JavaScript:  const add3 = x => x + 3

Both mean: take a value and add three. The spreadsheet hides the function name; JavaScript lets us name and reuse it.

ch04 — Lambda Functions

A lambda is a small function written where it is needed.

const double = x => x * 2
const greeting = name => "Hello " + name

double(5)       // 10
greeting("Ada") // "Hello Ada"

x => x * 2 means “input x, output x * 2.”

Lambda: Named or Inline

const addTax = price => price * 1.1

addTax(100) // 110

// The same kind of function can be used inline later:
[100, 200].map(price => price * 1.1)
// [110, 220]

Small, single-purpose functions are the building blocks for larger programs.

ch05 — Combining Functions

Build a larger transformation from small ones.

const add1 = x => x + 1
const double = x => x * 2

const add1ThenDouble = x => double(add1(x))

add1ThenDouble(3) // 8

The output of one function becomes the input of the next.

Functional Foundations Summary

Values → named data → pure functions → lambdas → composition

ch06 — Logic and Conditions

Functions can also choose an output.

const result = score => {
  if (score >= 60) return "Pass"
  return "Try again"
}

result(85) // "Pass"
result(42) // "Try again"

This matches the spreadsheet formula =IF(A1 >= 60, "Pass", "Try again").