A Functional Primer - SDD Conferencesddconf.com/brands/sdd/library/A_Functional_Primer.pdfExcel is...
Transcript of A Functional Primer - SDD Conferencesddconf.com/brands/sdd/library/A_Functional_Primer.pdfExcel is...
a functional primer
@KevlinHenney
Excel is the world's most popular functional language.
Simon Peyton-Jones
f(x) = expression
In functional programming, programs are executed by evaluating expressions, in contrast with imperative programming where programs are composed of statements which change global state when executed. Functional programming typically avoids using mutable state.
https://wiki.haskell.org/Functional_programming
Referential transparency is a very
desirable property: it implies that
functions consistently yield the same
results given the same input,
irrespective of where and when they are
invoked. That is, function evaluation
depends less—ideally, not at all—on the
side effects of mutable state.
Edward Garson "Apply Functional Programming Principles"
Many programming languages support programming in both functional and imperative style but the syntax and facilities of a language are typically optimised for only one of these styles, and social factors like coding conventions and libraries often force the programmer towards one of the styles.
https://wiki.haskell.org/Functional_programming
https://twitter.com/mfeathers/status/29581296216
functional
programming
higher-order functions
recursion
statelessness
first-class functions
immutability
pure functions
unification
declarative
pattern matching
non-strict evaluation
idempotence
lists
mathematics
lambdas currying
monads
int square(int x) { return x * x; }
function square(x) { return x * x }
public class Square { public static int square(int x) { return x * x; } }
square(X) -> X * X.
square x = x * x
square :: Int -> Int square x = x * x
square :: Num a => a -> a square x = x * x
do
for
foreach
while
To iterate is human, to recurse divine.
L Peter Deutsch
function factorial(n) {
var result = 1;
while (n > 1)
result *= n--;
return result;
}
function factorial(n) {
if (n > 1)
return n * factorial(n - 1);
else
return 1;
}
function factorial(n) {
return (
n > 1
? n * factorial(n - 1)
: 1);
}
Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function.
The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.
http://stackoverflow.com/questions/310974/what-is-tail-call-optimization
function factorial(n) {
function loop(n, result) {
return (
n > 1
? loop(n - 1, n * result)
: result);
}
return loop(n, 1);
}
n! = 1
(n – 1)! n
if n = 0,
if n > 0. {
n! =
n
k = 1
k
factorial n = product [1..n]
factorial n = foldl (*) 1 [1..n]
A higher-order function is a function that takes other functions as arguments or returns a function as result.
https://wiki.haskell.org/Higher_order_function
map reduce
factorial n = foldr (*) 1 [1..n]
foldl (-) 0 [1..3]
foldl (-) (0 – 1) [2..3]
foldl (-) ((0 – 1) – 2) [3]
foldl (-) (((0 – 1) – 2) – 3) []
((0 – 1) – 2) – 3
(-1 – 2) – 3
-3 – 3
-6
foldr (-) 0 [1..3]
1 – (foldr (-) 0 [2..3])
1 – (2 – (foldr (-) 0 [3]))
1 – (2 – (3 – (foldr (-) 0 [])))
1 – (2 – (3 – 0))
1 – (2 – 3)
1 – (-1)
2
f = λ x· expression
square = function(x) { return x * x }
square = x => x * x
square = \x -> x * x
map square [1..100]
map (\x -> x * x) [1..100]
[](){}
[](){}()
product = foldr (*) 1
Partial application is the conversion of a polyadic function into a function taking fewer arguments by providing one or more arguments in advance.
http://raganwald.com/2013/03/07/currying-and-partial-application.html
product [1..3]
foldr (*) 1 [1..3]
1 * (foldr (*) 1 [2..3])
1 * (2 * (foldr (*) 1 [3]))
1 * (2 * (3 * (foldr (*) 1 [])))
1 * (2 * (3 * 1))
1 * (2 * 3)
1 * (6)
6
intension, n. (Logic)
the set of characteristics or properties by which the referent or referents of a given expression is determined; the sense of an expression that determines its reference in every possible world, as opposed to its actual reference. For example, the intension of prime number may be having non-trivial integral factors, whereas its extension would be the set {2, 3, 5, 7, ...}.
E J Borowski and J M Borwein
Dictionary of Mathematics
{ x2 | x , x ≥ 1 x ≤ 100 }
select from where
A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.
http://en.wikipedia.org/wiki/List_comprehension
{ x2 | x , x ≥ 1 }
Lazy evaluation
https://twitter.com/richardadalton/status/591534529086693376
def fizzbuzz(n): result = '' if n % 3 == 0: result += 'Fizz' if n % 5 == 0: result += 'Buzz' if not result: result = str(n) return result
def fizzbuzz(n): if n % 15 == 0: return 'FizzBuzz' elif n % 3 == 0: return 'Fizz' elif n % 5 == 0: return 'Buzz' else: return str(n)
def fizzbuzz(n): return ( 'FizzBuzz' if n % 15 == 0 else 'Fizz' if n % 3 == 0 else 'Buzz' if n % 5 == 0 else str(n))
def fizzbuzz(n): return ( 'FizzBuzz' if n in range(0, 101, 15) else 'Fizz' if n in range(0, 101, 3) else 'Buzz' if n in range(0, 101, 5) else str(n))
fizzes = [''] + ([''] * 2 + ['Fizz']) * 33 + ['']
buzzes = [''] + ([''] * 4 + ['Buzz']) * 20
numbers = list(map(str, range(0, 101)))
def fizzbuzz(n): return fizzes[n] + buzzes[n] or numbers[n]
actual = [fizzbuzz(n) for n in range(1, 101)]
truths = [
every result is 'Fizz', 'Buzz', 'FizzBuzz' or a decimal string,
every decimal result corresponds to its ordinal position,
every third result contains 'Fizz',
every fifth result contains 'Buzz',
every fifteenth result is 'FizzBuzz',
the ordinal position of every 'Fizz' result is divisible by 3,
the ordinal position of every 'Buzz' result is divisible by 5,
the ordinal position of every 'FizzBuzz' result is divisible by 15
]
assert all(truths)
actual = [fizzbuzz(n) for n in range(1, 101)]
truths = [
all(a in {'Fizz', 'Buzz', 'FizzBuzz'} or a.isdecimal() for a in actual),
all(int(a) == n for n, a in enumerate(actual, 1) if a.isdecimal()),
all('Fizz' in a for a in actual[2::3]),
all('Buzz' in a for a in actual[4::5]),
all(a == 'FizzBuzz' for a in actual[14::15]),
all(n % 3 == 0 for n, a in enumerate(actual, 1) if a == 'Fizz'),
all(n % 5 == 0 for n, a in enumerate(actual, 1) if a == 'Buzz'),
all(n % 15 == 0 for n, a in enumerate(actual, 1) if a == 'FizzBuzz')
]
assert all(truths)
I still have a deep fondness for the Lisp model. It is simple, elegant, and something with which all developers should have an infatuation at least once in their programming life.
Kevlin Henney "A Fair Share (Part I)", CUJ C++ Experts Forum, October 2002
(How to Write a (Lisp)
Interpreter (in Python))
http://norvig.com/lispy.html
################ Lispy: Scheme Interpreter in Python ## (c) Peter Norvig, 2010-14; See http://norvig.com/lispy.html ################ Types from __future__ import division Symbol = str # A Lisp Symbol is implemented as a Python str List = list # A Lisp List is implemented as a Python list Number = (int, float) # A Lisp Number is implemented as a Python int or float ################ Parsing: parse, tokenize, and read_from_tokens def parse(program): "Read a Scheme expression from a string." return read_from_tokens(tokenize(program)) def tokenize(s): "Convert a string into a list of tokens." return s.replace('(',' ( ').replace(')',' ) ').split() def read_from_tokens(tokens): "Read an expression from a sequence of tokens." if len(tokens) == 0: raise SyntaxError('unexpected EOF while reading') token = tokens.pop(0) if '(' == token: L = [] while tokens[0] != ')': L.append(read_from_tokens(tokens)) tokens.pop(0) # pop off ')' return L elif ')' == token: raise SyntaxError('unexpected )') else: return atom(token) def atom(token): "Numbers become numbers; every other token is a symbol." try: return int(token) except ValueError: try: return float(token) except ValueError: return Symbol(token) ################ Environments def standard_env(): "An environment with some Scheme standard procedures." import math, operator as op env = Env() env.update(vars(math)) # sin, cos, sqrt, pi, ... env.update({ '+':op.add, '-':op.sub, '*':op.mul, '/':op.div, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'abs': abs, 'append': op.add, 'apply': apply, 'begin': lambda *x: x[-1], 'car': lambda x: x[0], 'cdr': lambda x: x[1:], 'cons': lambda x,y: [x] + y, 'eq?': op.is_, 'equal?': op.eq, 'length': len, 'list': lambda *x: list(x), 'list?': lambda x: isinstance(x,list), 'map': map, 'max': max, 'min': min, 'not': op.not_, 'null?': lambda x: x == [], 'number?': lambda x: isinstance(x, Number), 'procedure?': callable, 'round': round, 'symbol?': lambda x: isinstance(x, Symbol), }) return env
class Env(dict): "An environment: a dict of {'var':val} pairs, with an outer Env." def __init__(self, parms=(), args=(), outer=None): self.update(zip(parms, args)) self.outer = outer def find(self, var): "Find the innermost Env where var appears." return self if (var in self) else self.outer.find(var) global_env = standard_env() ################ Interaction: A REPL def repl(prompt='lis.py> '): "A prompt-read-eval-print loop." while True: val = eval(parse(raw_input(prompt))) if val is not None: print(lispstr(val)) def lispstr(exp): "Convert a Python object back into a Lisp-readable string." if isinstance(exp, list): return '(' + ' '.join(map(lispstr, exp)) + ')' else: return str(exp) ################ Procedures class Procedure(object): "A user-defined Scheme procedure." def __init__(self, parms, body, env): self.parms, self.body, self.env = parms, body, env def __call__(self, *args): return eval(self.body, Env(self.parms, args, self.env)) ################ eval def eval(x, env=global_env): "Evaluate an expression in an environment." if isinstance(x, Symbol): # variable reference return env.find(x)[x] elif not isinstance(x, List): # constant literal return x elif x[0] == 'quote': # (quote exp) (_, exp) = x return exp elif x[0] == 'if': # (if test conseq alt) (_, test, conseq, alt) = x exp = (conseq if eval(test, env) else alt) return eval(exp, env) elif x[0] == 'define': # (define var exp) (_, var, exp) = x env[var] = eval(exp, env) elif x[0] == 'set!': # (set! var exp) (_, var, exp) = x env.find(var)[var] = eval(exp, env) elif x[0] == 'lambda': # (lambda (var...) body) (_, parms, body) = x return Procedure(parms, body, env) else: # (proc arg...) proc = eval(x[0], env) args = [eval(exp, env) for exp in x[1:]] return proc(*args)
def eval(x, env=global_env): "Evaluate an expression in an environment." if isinstance(x, Symbol): # variable reference return env.find(x)[x] elif not isinstance(x, List): # constant literal return x elif x[0] == 'quote': # (quote exp) (_, exp) = x return exp elif x[0] == 'if': # (if test conseq alt) (_, test, conseq, alt) = x exp = (conseq if eval(test, env) else alt) return eval(exp, env) elif x[0] == 'define': # (define var exp) (_, var, exp) = x env[var] = eval(exp, env) elif x[0] == 'set!': # (set! var exp) (_, var, exp) = x env.find(var)[var] = eval(exp, env) elif x[0] == 'lambda': # (lambda (var...) body) (_, parms, body) = x return Procedure(parms, body, env) else: # (proc arg...) proc = eval(x[0], env) args = [eval(exp, env) for exp in x[1:]] return proc(*args)
(An ((Even Better) Lisp)
Interpreter (in Python))
http://norvig.com/lispy2.html
################ Scheme Interpreter in Python ## (c) Peter Norvig, 2010; See http://norvig.com/lispy2.html ################ Symbol, Procedure, classes from __future__ import division import re, sys, StringIO class Symbol(str): pass def Sym(s, symbol_table={}): "Find or create unique Symbol entry for str s in symbol table." if s not in symbol_table: symbol_table[s] = Symbol(s) return symbol_table[s] _quote, _if, _set, _define, _lambda, _begin, _definemacro, = map(Sym, "quote if set! define lambda begin define-macro".split()) _quasiquote, _unquote, _unquotesplicing = map(Sym, "quasiquote unquote unquote-splicing".split()) class Procedure(object): "A user-defined Scheme procedure." def __init__(self, parms, exp, env): self.parms, self.exp, self.env = parms, exp, env def __call__(self, *args): return eval(self.exp, Env(self.parms, args, self.env)) ################ parse, read, and user interaction def parse(inport): "Parse a program: read and expand/error-check it." # Backwards compatibility: given a str, convert it to an InPort if isinstance(inport, str): inport = InPort(StringIO.StringIO(inport)) return expand(read(inport), toplevel=True) eof_object = Symbol('#<eof-object>') # Note: uninterned; can't be read class InPort(object): "An input port. Retains a line of chars." tokenizer = r"""\s*(,@|[('`,)]|"(?:[\\].|[^\\"])*"|;.*|[^\s('"`,;)]*)(.*)""" def __init__(self, file): self.file = file; self.line = '' def next_token(self): "Return the next token, reading new text into line buffer if needed." while True: if self.line == '': self.line = self.file.readline() if self.line == '': return eof_object token, self.line = re.match(InPort.tokenizer, self.line).groups() if token != '' and not token.startswith(';'): return token def readchar(inport): "Read the next character from an input port." if inport.line != '': ch, inport.line = inport.line[0], inport.line[1:] return ch else: return inport.file.read(1) or eof_object def read(inport): "Read a Scheme expression from an input port." def read_ahead(token): if '(' == token: L = [] while True: token = inport.next_token() if token == ')': return L else: L.append(read_ahead(token)) elif ')' == token: raise SyntaxError('unexpected )') elif token in quotes: return [quotes[token], read(inport)] elif token is eof_object: raise SyntaxError('unexpected EOF in list') else: return atom(token) # body of read: token1 = inport.next_token() return eof_object if token1 is eof_object else read_ahead(token1) quotes = {"'":_quote, "`":_quasiquote, ",":_unquote, ",@":_unquotesplicing} def atom(token): 'Numbers become numbers; #t and #f are booleans; "..." string; otherwise Symbol.' if token == '#t': return True elif token == '#f': return False elif token[0] == '"': return token[1:-1].decode('string_escape') try: return int(token) except ValueError: try: return float(token) except ValueError: try: return complex(token.replace('i', 'j', 1)) except ValueError: return Sym(token) def to_string(x): "Convert a Python object back into a Lisp-readable string." if x is True: return "#t" elif x is False: return "#f" elif isa(x, Symbol): return x elif isa(x, str): return '"%s"' % x.encode('string_escape').replace('"',r'\"') elif isa(x, list): return '('+' '.join(map(to_string, x))+')' elif isa(x, complex): return str(x).replace('j', 'i') else: return str(x) def load(filename): "Eval every expression from a file." repl(None, InPort(open(filename)), None)
def repl(prompt='lispy> ', inport=InPort(sys.stdin), out=sys.stdout): "A prompt-read-eval-print loop." sys.stderr.write("Lispy version 2.0\n") while True: try: if prompt: sys.stderr.write(prompt) x = parse(inport) if x is eof_object: return val = eval(x) if val is not None and out: print >> out, to_string(val) except Exception as e: print '%s: %s' % (type(e).__name__, e) ################ Environment class class Env(dict): "An environment: a dict of {'var':val} pairs, with an outer Env." def __init__(self, parms=(), args=(), outer=None): # Bind parm list to corresponding args, or single parm to list of args self.outer = outer if isa(parms, Symbol): self.update({parms:list(args)}) else: if len(args) != len(parms): raise TypeError('expected %s, given %s, ' % (to_string(parms), to_string(args))) self.update(zip(parms,args)) def find(self, var): "Find the innermost Env where var appears." if var in self: return self elif self.outer is None: raise LookupError(var) else: return self.outer.find(var) def is_pair(x): return x != [] and isa(x, list) def cons(x, y): return [x]+y def callcc(proc): "Call proc with current continuation; escape only" ball = RuntimeWarning("Sorry, can't continue this continuation any longer.") def throw(retval): ball.retval = retval; raise ball try: return proc(throw) except RuntimeWarning as w: if w is ball: return ball.retval else: raise w def add_globals(self): "Add some Scheme standard procedures." import math, cmath, operator as op self.update(vars(math)) self.update(vars(cmath)) self.update({ '+':op.add, '-':op.sub, '*':op.mul, '/':op.div, 'not':op.not_, '>':op.gt, '<':op.lt, '>=':op.ge, '<=':op.le, '=':op.eq, 'equal?':op.eq, 'eq?':op.is_, 'length':len, 'cons':cons, 'car':lambda x:x[0], 'cdr':lambda x:x[1:], 'append':op.add, 'list':lambda *x:list(x), 'list?': lambda x:isa(x,list), 'null?':lambda x:x==[], 'symbol?':lambda x: isa(x, Symbol), 'boolean?':lambda x: isa(x, bool), 'pair?':is_pair, 'port?': lambda x:isa(x,file), 'apply':lambda proc,l: proc(*l), 'eval':lambda x: eval(expand(x)), 'load':lambda fn: load(fn), 'call/cc':callcc, 'open-input-file':open,'close-input-port':lambda p: p.file.close(), 'open-output-file':lambda f:open(f,'w'), 'close-output-port':lambda p: p.close(), 'eof-object?':lambda x:x is eof_object, 'read-char':readchar, 'read':read, 'write':lambda x,port=sys.stdout:port.write(to_string(x)), 'display':lambda x,port=sys.stdout:port.write(x if isa(x,str) else to_string(x))}) return self isa = isinstance global_env = add_globals(Env()) ################ eval (tail recursive) def eval(x, env=global_env): "Evaluate an expression in an environment." while True: if isa(x, Symbol): # variable reference return env.find(x)[x] elif not isa(x, list): # constant literal return x elif x[0] is _quote: # (quote exp) (_, exp) = x return exp elif x[0] is _if: # (if test conseq alt) (_, test, conseq, alt) = x x = (conseq if eval(test, env) else alt) elif x[0] is _set: # (set! var exp) (_, var, exp) = x env.find(var)[var] = eval(exp, env) return None elif x[0] is _define: # (define var exp) (_, var, exp) = x env[var] = eval(exp, env) return None elif x[0] is _lambda: # (lambda (var*) exp) (_, vars, exp) = x return Procedure(vars, exp, env) elif x[0] is _begin: # (begin exp+) for exp in x[1:-1]: eval(exp, env) x = x[-1] else: # (proc exp*) exps = [eval(exp, env) for exp in x] proc = exps.pop(0) if isa(proc, Procedure): x = proc.exp env = Env(proc.parms, exps, proc.env) else: return proc(*exps)
################ expand def expand(x, toplevel=False): "Walk tree of x, making optimizations/fixes, and signaling SyntaxError." require(x, x!=[]) # () => Error if not isa(x, list): # constant => unchanged return x elif x[0] is _quote: # (quote exp) require(x, len(x)==2) return x elif x[0] is _if: if len(x)==3: x = x + [None] # (if t c) => (if t c None) require(x, len(x)==4) return map(expand, x) elif x[0] is _set: require(x, len(x)==3); var = x[1] # (set! non-var exp) => Error require(x, isa(var, Symbol), "can set! only a symbol") return [_set, var, expand(x[2])] elif x[0] is _define or x[0] is _definemacro: require(x, len(x)>=3) _def, v, body = x[0], x[1], x[2:] if isa(v, list) and v: # (define (f args) body) f, args = v[0], v[1:] # => (define f (lambda (args) body)) return expand([_def, f, [_lambda, args]+body]) else: require(x, len(x)==3) # (define non-var/list exp) => Error require(x, isa(v, Symbol), "can define only a symbol") exp = expand(x[2]) if _def is _definemacro: require(x, toplevel, "define-macro only allowed at top level") proc = eval(exp) require(x, callable(proc), "macro must be a procedure") macro_table[v] = proc # (define-macro v proc) return None # => None; add v:proc to macro_table return [_define, v, exp] elif x[0] is _begin: if len(x)==1: return None # (begin) => None else: return [expand(xi, toplevel) for xi in x] elif x[0] is _lambda: # (lambda (x) e1 e2) require(x, len(x)>=3) # => (lambda (x) (begin e1 e2)) vars, body = x[1], x[2:] require(x, (isa(vars, list) and all(isa(v, Symbol) for v in vars)) or isa(vars, Symbol), "illegal lambda argument list") exp = body[0] if len(body) == 1 else [_begin] + body return [_lambda, vars, expand(exp)] elif x[0] is _quasiquote: # `x => expand_quasiquote(x) require(x, len(x)==2) return expand_quasiquote(x[1]) elif isa(x[0], Symbol) and x[0] in macro_table: return expand(macro_table[x[0]](*x[1:]), toplevel) # (m arg...) else: # => macroexpand if m isa macro return map(expand, x) # (f arg...) => expand each def require(x, predicate, msg="wrong length"): "Signal a syntax error if predicate is false." if not predicate: raise SyntaxError(to_string(x)+': '+msg) _append, _cons, _let = map(Sym, "append cons let".split()) def expand_quasiquote(x): """Expand `x => 'x; `,x => x; `(,@x y) => (append x y) """ if not is_pair(x): return [_quote, x] require(x, x[0] is not _unquotesplicing, "can't splice here") if x[0] is _unquote: require(x, len(x)==2) return x[1] elif is_pair(x[0]) and x[0][0] is _unquotesplicing: require(x[0], len(x[0])==2) return [_append, x[0][1], expand_quasiquote(x[1:])] else: return [_cons, expand_quasiquote(x[0]), expand_quasiquote(x[1:])] def let(*args): args = list(args) x = cons(_let, args) require(x, len(args)>1) bindings, body = args[0], args[1:] require(x, all(isa(b, list) and len(b)==2 and isa(b[0], Symbol) for b in bindings), "illegal binding list") vars, vals = zip(*bindings) return [[_lambda, list(vars)]+map(expand, body)] + map(expand, vals) macro_table = {_let:let} ## More macros can go here eval(parse("""(begin (define-macro and (lambda args (if (null? args) #t (if (= (length args) 1) (car args) `(if ,(car args) (and ,@(cdr args)) #f))))) ;; More macros can also go here )""")) if __name__ == '__main__': repl()
def eval(x, env=global_env): "Evaluate an expression in an environment." while True: if isa(x, Symbol): # variable reference return env.find(x)[x] elif not isa(x, list): # constant literal return x elif x[0] is _quote: # (quote exp) (_, exp) = x return exp elif x[0] is _if: # (if test conseq alt) (_, test, conseq, alt) = x x = (conseq if eval(test, env) else alt) elif x[0] is _set: # (set! var exp) (_, var, exp) = x env.find(var)[var] = eval(exp, env) return None elif x[0] is _define: # (define var exp) (_, var, exp) = x env[var] = eval(exp, env) return None elif x[0] is _lambda: # (lambda (var*) exp) (_, vars, exp) = x return Procedure(vars, exp, env) elif x[0] is _begin: # (begin exp+) for exp in x[1:-1]: eval(exp, env) x = x[-1] else: # (proc exp*) exps = [eval(exp, env) for exp in x] proc = exps.pop(0) if isa(proc, Procedure): x = proc.exp env = Env(proc.parms, exps, proc.env) else: return proc(*exps)
LISP uses a variant of prefix (Polish) notation called Cambridge Polish Notation.
All expressions are fully parenthesized, with the first element of an executable form being the name of a function, macro, or special form.
For example, the expression written as in traditional infix notation is
written as in LISP.
http://www.math-cs.gordon.edu/courses/cs323/LISP/lisp.html
(define square (lambda (x) (* x x)))
(define (square x) (* x x))
(define (map do all)
(if (null? all)
(list)
(cons (do (car all))
(map do (cdr all)))))
(define (map do all)
(if (null? all)
nil
(cons (do (head all))
(map do (tail all)))))
(define head car)
(define tail cdr)
(define nil (list))
(map square (list 1 2 3))
(cons (square 1)
(cons (square 2)
(cons (square 3) nil)))
(define (reduce do it all) ; foldr
(if (null? all)
it
(do (head all)
(reduce do it (tail all)))))
(reduce * 1 (list 1 2 3))
(* 1 (reduce * 1 (list 2 3)))
(* 1 (* 2 (reduce * 1 (list 3))))
(* 1 (* 2 (* 3 (reduce * 1 nil))))
(* 1 (* 2 (* 3 1)))
(* 1 (* 2 3))
(* 1 6)
6
(define (reduce do it all) ; foldl
(if (null? all)
it
(reduce do
(do it (head all))
(tail all))))
(reduce * 1 (list 1 2 3))
(reduce * (* 1 1) (list 2 3))
(reduce * 1 (list 2 3))
(reduce * (* 1 2) (list 3))
(reduce * 2 (list 3))
(reduce * (* 2 3) nil)
(reduce * 6 nil)
6
(define (reverse all)
(define (snoc a b) (cons b a))
(reduce snoc nil all))
(reverse (list 1 2 3))
(reduce snoc nil (list 1 2 3))
(reduce snoc (list 1) (list 2 3))
(reduce snoc (list 2 1) (list 3))
(reduce snoc (list 3 2 1) nil)
(list 3 2 1)
https://twitter.com/mattpodwysocki/status/393474697699921921
Concurrency
Concurrency
Threads
Concurrency
Threads
Locks
All computers wait at the same speed.
Mutable
Immutable
Unshared Shared
Unshared mutable data needs no synchronisation
Unshared immutable data needs no synchronisation
Shared mutable data needs synchronisation
Shared immutable data needs no synchronisation
Mutable
Immutable
Unshared Shared
Unshared mutable data needs no synchronisation
Unshared immutable data needs no synchronisation
Shared mutable data needs synchronisation
Shared immutable data needs no synchronisation
The Synchronisation Quadrant
public class Money : ... { ... public int Units { get ... set ... } public int Hundredths { get ... set ... } public string Currency { get ... set ... } ... }
public class Money : ... { ... public int Units { get ... } public int Hundredths { get ... } public string Currency { get ... } ... }
When it is not necessary to change, it is necessary not to change.
Lucius Cary
Idempotence is the property of certain operations in mathematics and computer science, that they can be applied multiple times without changing the result beyond the initial application.
The concept of idempotence arises in a number of places in abstract algebra [...] and functional programming (in which it is connected to the property of referential transparency).
http://en.wikipedia.org/wiki/Idempotent
Asking a question should not change the answer.
Bertrand Meyer
Asking a question should not change the answer, and nor should asking it twice!
In computing, a persistent data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (visibly) update the structure in-place, but instead always yield a new updated structure.
http://en.wikipedia.org/wiki/Persistent_data_structure
(A persistent data structure is not a data structure committed to persistent storage, such as a disk; this is a different and unrelated sense of the word "persistent.")
Instead of using threads and shared memory
as our programming model, we can use
processes and message passing. Process here
just means a protected independent state
with executing code, not necessarily an
operating system process.
Russel Winder "Message Passing Leads to Better Scalability in Parallel Systems"
Languages such as Erlang (and occam before
it) have shown that processes are a very
successful mechanism for programming
concurrent and parallel systems. Such
systems do not have all the synchronization
stresses that shared-memory, multithreaded
systems have.
Russel Winder "Message Passing Leads to Better Scalability in Parallel Systems"
Sender Receiver A
Message 1 Message 3
Receiver B
In response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received.
http://en.wikipedia.org/wiki/Actor_model
Multithreading is just one damn thing after, before, or simultaneous with another.
Andrei Alexandrescu
Actor-based concurrency is just one damn message after another.
Stack
alphabet(Stack) = {push, pop, popped, empty}
trace(Stack) = {⟨ ⟩, ⟨push⟩, ⟨pop, empty⟩, ⟨push, push⟩, ⟨push, pop, popped⟩, ⟨push, push, pop, popped⟩, ⟨push, pop, popped, pop, empty⟩, ...}
Non-Empty Empty
pop / empty push pop / popped
push
pop / popped
empty() -> receive {push, Top} -> non_empty(Top); {pop, Return} -> Return ! empty end, empty().
non_empty(Value) -> receive {push, Top} -> non_empty(Top), non_empty(Value); {pop, Return} -> Return ! {popped, Value} end.
Stack = spawn(stack, empty, []).
Stack ! {pop, self()}.
empty
Stack ! {push, 20}.
Stack ! {pop, self()}.
{popped, 20}
Stack ! {push, 20}.
Stack ! {push, 17}.
Stack ! {pop, self()}.
{popped, 17}
Stack ! {pop, self()}.
{popped, 20}
https://twitter.com/wm/status/7206700352