25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

for an expression g(f(x), f(x)), this is always equivalent to g(a, a). In other words the values computed<br />

by functions can always be substituted freely at all occurrences.<br />

e central idea of functional programming is to structure our programs in such a way that we can reason<br />

about them as a system of equations just like we can in mathematics. e evaluation of a pure function<br />

is one in which side effects are prohibited, a function may only return a result without altering the world<br />

in any observable way.<br />

e implementation may perform effects, but central to this definition is the unobservability of such<br />

effects. A function is said to be referentially transparent if replacing a function with its computed value<br />

output yields the same observable behavior.<br />

By contrast impure functions are ones which allow unrestricted and observable side effects. e invocation<br />

of an impure function always allows for the possibility of performing any functionality before<br />

yielding a value.<br />

// impure: mutation side effects<br />

function f() {<br />

x += 3;<br />

return 42;<br />

}<br />

// impure: international side effects<br />

function f() {<br />

launchMissiles();<br />

return 42;<br />

}<br />

e behavior of a pure function is independent of where and when it is evaluated, whereas the behavior<br />

of an impure function is intrinsically tied to its execution order.<br />

Functional programming is defined simply as programming strictly with pure referentially transparent<br />

functions.<br />

Static Typing<br />

Types are a formal language integrated with a programming language that refines the space of allowable<br />

behavior and degree of expressible programs for the language. Types are the world’s most popular formal<br />

method for analyzing programs.<br />

In a language like Python all expressions have the same type at compile time, and all syntactically valid<br />

programs can be evaluated. In the case where the program is nonsensical the runtime will bubble up<br />

exceptions during evaluation. e Python interpreter makes no attempt to analyze the given program<br />

for soundness at all before running it.<br />

>>> True & ”false”<br />

Traceback (most recent call last):<br />

8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!