- Create a new array with
nelements, each initialized tox
new Array(n).fill(x)- Create a new array with
nelements, each initialized asf()
// Imperatively
const a = []
for (let i = 0; i < n; i++) a[i] = f()| function Fraction(n, d) { | |
| this.n = n; | |
| if (d) this.d = d; | |
| else this.d = 1; | |
| } | |
| Fraction.prototype.reciprocal = function() { | |
| return {n: this.d, d: this.n}; | |
| } |
| #include <Adafruit_NeoPixel.h> | |
| #ifdef __AVR__ | |
| #include <avr/power.h> | |
| #endif | |
| #define START_PIN 3 | |
| #define NUM_STRIPS 3 | |
| #define NUM_PIXELS 150 | |
| // Parameter 1 = number of pixels in strip |
| (module | |
| ;; Memory layout | |
| ;; 0 - 63: lookup | |
| ;; 64 - 186: revLookup | |
| ;; 187 - : input, followed by output | |
| (global $INPUT (export "INPUT") i32 (i32.const 187)) | |
| (memory (export "memory") 1) | |
| (data (i32.const 0) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") | |
| (func (export "init") | |
| (local $i i32) |
Consider how stateful computations could be expressed in a pure functional language like Haskell. We will use a mutable stack as an example, but we'll see later that the same ideas generalize to any sort of mutable state.
A stack is a simple data structure used extensively to model imperative computation.
It is an ordered collection of values where all modifications happen at one end of the collection.
In Java, for example, a Stack is accessed/manipulated with the following two methods:
| CC = clang-with-asan | |
| CFLAGS = -Wall -Wextra | |
| graph: function.o graph.o main.o | |
| $(CC) $(CFLAGS) -lm $^ -o $@ | |
| %.o: %.c | |
| $(CC) $(CFLAGS) -c $^ -o $@ |