Frege Tutorial at JavaOne 2015

59
Purely functional programming - the red pill JavaOne 2015

Transcript of Frege Tutorial at JavaOne 2015

Page 1: Frege Tutorial at JavaOne 2015

Purely functional programming - the red pillJavaOne 2015

Page 2: Frege Tutorial at JavaOne 2015

Dierk König Canoo

mittie

Page 3: Frege Tutorial at JavaOne 2015

TakeawayFrege is fundamentally different

based on science

made for practical use

Page 4: Frege Tutorial at JavaOne 2015

Why do we care?a=1

b=2

c=b

b=a

a=c

1

1 2

1 2

2

1

1

22

1 2

time1time2time3

state1 state2 state3

Page 5: Frege Tutorial at JavaOne 2015

Operational Reasoninga=1

b=2

c=b

b=a

a=c

1

1 2

1 2 2

1 1 2

2 1 2

time1time2time3

state1 state2 state3

We need a debugger!

Page 6: Frege Tutorial at JavaOne 2015

Using functionsa=1

b=2

1

1 2

Page 7: Frege Tutorial at JavaOne 2015

Using functionsa=1

b=2

1

1 2

2 1

swap(a,b)=(b,a)

Page 8: Frege Tutorial at JavaOne 2015

The Key IdeaAssignments change state and introduce time.Statements do side effects.

Let’s just program without assignments or statements!

Page 9: Frege Tutorial at JavaOne 2015

Developer Discipline

Pure Functional Language

Page 10: Frege Tutorial at JavaOne 2015

Online REPL try.frege-lang.org

Page 11: Frege Tutorial at JavaOne 2015

Define a Functionfrege>timesab=a*b

frege>times34

12

frege>:typetimes

Numα=>α->α->α

Page 12: Frege Tutorial at JavaOne 2015

Define a Functionfrege>timesab=a*b

frege>(times3)4

12

frege>:typetimes

Numα=>α->(α->α)

no types declared

function appl. left associative

tell the inferred type

typeclassonly 1

parameter!return type is

a function!

thumb: „two params of same numeric type returning that type“

no comma

Page 13: Frege Tutorial at JavaOne 2015

Reference a Functionfrege>twotimes=times2

frege>twotimes3

6

frege>:ttwotimes

Int->Int

Page 14: Frege Tutorial at JavaOne 2015

Reference a Functionfrege>twotimes=times2

frege>twotimes3

6

frege>:ttwotimes

Int->Int

No second argument!

„Currying“, „schönfinkeling“, or „partial function

application“. Concept invented by

Gottlob Frege.

inferred types are more specific

Page 15: Frege Tutorial at JavaOne 2015

Function Compositionfrege>twotimes(threetimes2)

12

frege>sixtimes=twotimes.threetimes

frege>sixtimes2

frege>:tsixtimes

Int->Int

Page 16: Frege Tutorial at JavaOne 2015

Function Compositionfrege>twotimes(threetimes2)

12

frege>sixtimes=twotimes.threetimes

frege>sixtimes2

frege>:tsixtimes

Int->Int

f(g(x))

more about this later

(f ° g) (x)

Page 17: Frege Tutorial at JavaOne 2015

Pattern Matchingfrege>times0(threetimes2)

0

frege>times0b=0

Page 18: Frege Tutorial at JavaOne 2015

Pattern Matchingfrege>times0(threetimes2)

0

frege>times0b=0

unnecessarily evaluated

shortcuttingpattern matching

Page 19: Frege Tutorial at JavaOne 2015

Lazy Evaluationfrege>times0(length[1..])

0endless sequence

evaluation would never stop

Pattern matching and non-strict evaluation

to the rescue!

Page 20: Frege Tutorial at JavaOne 2015

Pure FunctionsJava

Tfoo(Pair<T,U>p){…}

Frege

foo::(α,β)->α

What could possibly happen?

What could possibly happen?

Page 21: Frege Tutorial at JavaOne 2015

Pure FunctionsJava

Tfoo(Pair<T,U>p){…}

Frege

foo::(α,β)->α

Everything! State changes,

file or db access, missile launch,…

a is returned

Page 22: Frege Tutorial at JavaOne 2015

can be cached (memoized) can be evaluated lazily can be evaluated in advance can be evaluated concurrently can be eliminated in common subexpressions

can be optimized

Pure Functions

Page 23: Frege Tutorial at JavaOne 2015

Is my method pure?

Let the type system find out!

Page 24: Frege Tutorial at JavaOne 2015

Magic (?)Thinkofagenericfunction

f::[a]->[a]

andanyspecificfunction

g::a->b

Page 25: Frege Tutorial at JavaOne 2015

Magic (?)

[a] [a]

[b] [b]

f

f

map g map g

Page 26: Frege Tutorial at JavaOne 2015

Magic (?)

[1,2,3] [3,2,1]

[2,4,6] [6,4,2]

reverse

reverse

map (*2) map (*2)

Commutative square of natural transformations.

Page 27: Frege Tutorial at JavaOne 2015

Robust RefactoringChanging the order of operationsRequires purity.100% safe if the type system can detect natural transformations

Applied Category Theorycredits: Phil Wadler, Tech Mesh 2012 - Faith, Evolution, and Programming Languages

Page 28: Frege Tutorial at JavaOne 2015

QuickCheckimportTest.QuickCheckf=reverseg=(*2)

commutativity=property(\xs->mapg(fxs)==f(mapgxs))

Page 29: Frege Tutorial at JavaOne 2015

Java Interoperability do not mix OO and FP

combine them

Page 30: Frege Tutorial at JavaOne 2015

Java -> FregeScripting: JSR 223

Service:compile *.fr file call static method

simple

Page 31: Frege Tutorial at JavaOne 2015

pure native encode java.net.URLEncoder.encode :: String -> String encode “Dierk König“

native millis java.lang.System.currentTimeMillis :: () -> IO Long millis () millis () past = millis () - 1000

Does not compile!

Frege -> Java

This is a key distinction between Frege and other JVM languages!

even Java can be pure

Page 32: Frege Tutorial at JavaOne 2015

allows calling Java but never unprotected!

is explicit about effects just like Haskell

Frege

Page 33: Frege Tutorial at JavaOne 2015

Type SystemGlobal type inference and thus more safety and less work for the programmer

You don’t need to specify any types at all! But sometimes you do anyway…

Page 34: Frege Tutorial at JavaOne 2015

Mutable I/O

Mutable

Mutable

Keep the mess out!

Pure Computation

Pure Computation

Pure Computation

Page 35: Frege Tutorial at JavaOne 2015

Mutable I/O

Mutable

Mutable

Keep the mess out!

Pure Computation

Pure Computation

Pure Computation

Ok, these are Monads. Be brave. Think of them as contexts that the type system propagates and makes un-escapable.

Thread-safe by design! Checked

by compiler

Page 36: Frege Tutorial at JavaOne 2015

JavaJava

Java

Service Based Design

Frege

Frege

Frege

A typical integration option: use Frege code for services

Page 37: Frege Tutorial at JavaOne 2015

Some Cool Stuff

Page 38: Frege Tutorial at JavaOne 2015

Zippingaddzip[]_=[]addzip_[]=[]

addzip(x:xs)(y:ys)=(x+y:addzipxsys)

Page 39: Frege Tutorial at JavaOne 2015

Zippingaddzip[]_=[]addzip_[]=[]

addzip(x:xs)(y:ys)=(x+y:addzipxsys)

use as addzip[1,2,3][1,2,3]==[2,4,6]

Pattern matching feels like Prolog

Why only for the (+) function? We could be more general…

Page 40: Frege Tutorial at JavaOne 2015

High Order FunctionszipWithf[]_=[]zipWithf_[]=[]

zipWithf(x:xs)(y:ys)=(fxy:zipWithxsys)

Page 41: Frege Tutorial at JavaOne 2015

High Order FunctionszipWithf[]_=[]zipWithf_[]=[]

zipWithf(x:xs)(y:ys)=(fxy:zipWithxsys)

use as zipWith(+)[1,2,3][1,2,3]==[2,4,6]

and, yes we can now define addzip= zipWith(+)

invented by Gottlob Frege

Page 42: Frege Tutorial at JavaOne 2015

Fizzbuzzhttp://c2.com/cgi/wiki?FizzBuzzTest

https://dierk.gitbooks.io/fregegoodness/ chapter 8 „FizzBuzz“

Page 43: Frege Tutorial at JavaOne 2015

Fizzbuzz ImperativepublicclassFizzBuzz{publicstaticvoidmain(String[]args){for(inti=1;i<=100;i++){if(i%15==0{System.out.println(„FizzBuzz");}elseif(i%3==0){System.out.println("Fizz");}elseif(i%5==0){System.out.println("Buzz");}else{System.out.println(i);}}}}

Page 44: Frege Tutorial at JavaOne 2015

Fizzbuzz Logicalfizzes=cycle["","","fizz"]buzzes=cycle["","","","","buzz"]pattern=zipWith(++)fizzesbuzzesnumbers=mapshow[1..]

fizzbuzz=zipWithmaxpatternnumbers

main_=dofor(take100fizzbuzz)println

Page 45: Frege Tutorial at JavaOne 2015

Fizzbuzz ComparisonImperative Logical

Conditionals 4 0

Operators 7 1

Nesting level 3 0

Sequencing sensitive transparent

Maintainability - - - +

Page 46: Frege Tutorial at JavaOne 2015

List ComprehensionPythagorean triples: a2 + b2 = c2

pythn=[

(x,y,z)

|x<-[1..n],y<-[1..n],z<-[1..n],

x*x+y*y==z*z

]

Page 47: Frege Tutorial at JavaOne 2015

List ComprehensionPythagorean triples: a2 + b2 = c2

pythn=[

(x,y,z)

|x<-[1..n],y<-[1..n],z<-[1..n],

x*x+y*y==z*z

]

select from

where

„brute force“ or „executable specification“. A more efficient solution:

Page 48: Frege Tutorial at JavaOne 2015

List ComprehensionPythagorean triples: a2 + b2 = c2

[(m*m-n*n,2*m*n,m*m+n*n)

|m<-[2..],n<-[1..m-1]

]

endless production think „nested loop“

„select“ functions

dynamic „from“

empty „where“

Page 49: Frege Tutorial at JavaOne 2015

HistoryJava promise: „No more pointers!“

But NullPointerExceptions (?)

Page 50: Frege Tutorial at JavaOne 2015

Frege is differentNo More But

state no state (unless declared)statements expressions (+ „do“ notation)assignments definitionsvariables ST monad as „agent“interfaces type classesclasses & objects algebraic data typesinheritance parametric polymorphismnull references MaybeNullPointerExceptions Bottom, error

Page 51: Frege Tutorial at JavaOne 2015

Frege in comparison

practical

robust

JavaGroovy

FregeHaskell

Page 52: Frege Tutorial at JavaOne 2015

Frege in comparison

JavaGroovy

FregeHaskell

concept by Simon Peyton-Jones

Frege makes the Haskell spirit accessible to the Java programmer and provides a new level of safety.

apply logic

run computers

practical

robust

Page 53: Frege Tutorial at JavaOne 2015

Unique in FregeExplicit effectsPurity = no effectsGuarantees extend into Java callsLaziness enforces purity and immutable values (no assignments)Global type inference requires a purely functional language (only expressions, no statements)

Page 54: Frege Tutorial at JavaOne 2015

Why FregeRobustness under parallel execution Robustness under composition Robustness under incrementsRobustness under refactoring

Enables local and equational reasoning

Best way to learn FP

Page 55: Frege Tutorial at JavaOne 2015

Why FP mattersEnabling incremental development www.canoo.com/blog/fp1 Brush up computational fundamentals

„An investment in knowledge always pays the best interest.“

—Benjamin Franklin

Page 56: Frege Tutorial at JavaOne 2015

Why Frege

it is just a pleasure to work with

Page 57: Frege Tutorial at JavaOne 2015

How?http://www.frege-lang.org@fregelangstackoverflow „frege“ tagedX FP101 MOOC (still possible to join!)

Page 58: Frege Tutorial at JavaOne 2015

Gottlob Frege

"As I think about acts of integrity and grace, I realise that there is nothing in my knowledge that compares with Frege’s dedication to truth… It was almost superhuman.“ —Bertrand Russel

"Not many people managed to create a revolution in thought. Frege did.“ —Graham Priest Lecture on Gottlob Frege: http://www.youtube.com/watch?v=foITiYYu2bc

Page 59: Frege Tutorial at JavaOne 2015

Dierk König Canoo

mittie

Please vote at the machine!