SlideShare a Scribd company logo
Func%onal	Programming	
	In	Prac%ce	
Michiel	Borkent		
@borkdude	
Hogeschool	Utrecht	
May	9th	2016
Agenda	
●  Func>onal	Programming	
●  Haskell,	Scala,	Clojure	
●  Full	stack	example	using	Clojure
First,	what	is	FP?	
•  First	class	func>ons	
•  Pure	func>ons	
•  Immutable	values	
•  No	or	few	side	effects
First	class	func%ons	
Func>ons	can	be	created	on	the	fly	
	
scala>	val	f	=	(x:	String)	=>	"Hello	"	+	x	
f:	String	=>	String	=	<function1>	
	
scala>	f("World")	
res10:	String	=	Hello	World
First	class	func%ons	
Func>ons	can	be	passed	around	as	values	
	
List("Clojure","Scala","Haskell").map(f)	
res:	List(Hello	Clojure,	Hello	Scala,	Hello	Haskell)
Pure	func%ons	
Func>on	with	same	input	always	yields	the	output:	
	
f(x)	==	y,	always
Not	a	pure	func%on	
scala>	val	f	=	(i:	Int)	=>	Math.random()	*	i	
f:	Int	=>	Double	=	<function1>	
	
scala>	f(1)	
res14:	Double	=	0.13536266885499726	
	
scala>	f(1)	
res15:	Double	=	0.4086671423543593
A	pure	func%on?	
val	add	=	(x:	Int,	y:	Int)	=>	x	+	y	
add(1,2)	//	3
A	pure	func%on?	
class	MutableInt(var	i:	Int)	{		
		override	def	toString	=	i.toString		
}	
	
val	add	=	(x:	MutableInt,	y:	MutableInt):	MutableInt	=>		
		new	MutableInt(x.i	+	y.i)	
	
val	x	=	new	MutableInt(1)	
val	y	=	new	MutableInt(2)		
	
add(x,y)	//	MutableInt	=	3
A	pure	func%on?	No!	
You	cannot	build	pure	func>ons	with	mutable	objects.	
	
add(x,y)	//	MutableInt	=	3	
	
x.i	=	2	
	
add(x,y)	//	MutableInt	=	4	
	
	
add(x,y)	does	not	always	yield	the	same	result!	
This	is	why	we	need	immutable	values	in	Func>onal	Programming.
A	pure	func%on?	
List(1,2,3)	is	immutable.	
	
def	addZero(l:	List[Int])	=	0	::	l	
	
addZero(List(1,2,3))	//	List(0,	1,	2,	3)
Immutable	data	structures	
Int,	String,	etc	are	already	immutable	
	
0	::	List(1,2,3)			//	List(0,1,2,3)	
Vector(1,2,3)	:+	4	//	Vector(1,2,3,4)	
Set(1,2,3)	+	4					//	Set(1,2,3,4)	
	
Efficient	by	re-using	structure	internally
source:	hVp://hypirion.com/musings/understanding-persistent-vector-pt-1
Systems	and	immutability	
•  Each	system	receives	a	message	
and/or	sends	a	message	
•  Muta>ng	a	message	does	not	
affect	other	system	
•  In	tradi>onal	OO	references	lead	
to	uncontrolled	muta>on,	also	
called	spooky	ac>on	at	a	distance	
•  You	can	protect	yourself	by	
using	Value	Objects	or	DTOs,	
but	takes	work	
•  Immutable	data	structures	
solve	this	problem
•  State	modifica>on	
•  Observable	ac>on	
	
Examples:	
•  Modifying	a	variable	
•  Wri>ng	to	a	file	
Side	effects
•  Pure	func>ons	have	no	side	effects	
•  Side	effects	are	difficult	to	test	(without	mocks)	
•  Pure	FP	languages	make	side	effects	explicit	
•  FP	languages	isolate/minimize	side	effects	
Side	effects
Where	are	the	side	effects?	
class	Program	extends	App	{	
		var	x:	Int	=	1	
		def	mutateX	=	{	
				x	=	(Math.random	*	100).toInt	
		}	
		mutateX	
		println(x)	
}
Where	are	the	side	effects?	
class	Program	extends	App	{	
		var	x:	Int	=	1	
		def	mutateX	=	{	
				x	=	(Math.random	*	100).toInt	
		}	
		mutateX	
		println(x)	
}
Why	Func%onal	Programming?	
•  Makes	codes	easier	to	reason	about	
•  Easier	to	test	
•  More	expressive,	less	code	=	less	bugs	
•  BeVer	suited	for	parallellisa>on	and	concurrency
Examples	in	Haskell,	Scala	and	Clojure	
•  Define	a	new	type	Person	
•  Create	a	list	of	Persons	
•  Count	total	length	of	first	names	with	length	
greater	than	4	
	
hVps://github.com/borkdude/fp-hu-may-2016/blob/master/code
Degrees	of	FP	
Nirvana
Unsafe Safe
Useless
Useful C#, Java
Haskell
Scala
Clojure
SQL, Linq
Simon Peyton Jones, FP researcher
Learning	FP	
Choose	a	language	that	encourages	FP	
	
	
	
	
	
Apply	the	concepts	in	your	favorite	language	
‘Think	like	a	fundamentalist,	code	like	a	hacker’	–	Erik	Meijer	
Haskell Pure, lazy,
statically typed
Clojure Not pure. FP + Lisp on JVM,
dynamically typed
Scala Not pure. FP + (immutable) OO on
JVM, statically typed
Haskell	resources
Clojure	resources	
http://michielborkent.nl/clojurecursus
Scala	resources	
Functional Programming in Scala Coursera MOOC
Developers	love	FP	
Source: http://stackoverflow.com/research/developer-survey-2016
Companies	want	FP	devs	
Source: http://stackoverflow.com/research/developer-survey-2016
Once	you	know	FP	
…	you	can	apply	and	see	it	everywhere
FP	at	my	job	
•  Microservices	in	Scala	
•  UI	in	JavaScript	using	React,	ImmutableJS	and	
Redux
Functional Programming In Practice
Clojure	
•  dynamic	language	
•  Lisp	
•  func>onal	programming	
•  immutable	data	structures	
•  strong	concurrency	support	
•  embraces	host	plajorm	(JVM,	js)	
•  EDN
Clojure	in	industry	
hVps://www.youtube.com/watch?v=av9Xi6CNqq4	
	
	
http://dev.clojure.org/display/community/Clojure+Success+Stories
https://www.youtube.com/watch?v=iUC7noGU1mQ
Data	literals	
Keyword:				:a	
Vector:					[1	2	3	4]	
Hash	map:			{:a	1,	:b	2}	
Set:								#{1	2	3	4}	
List:							'(1	2	3	4)
Extensible	Data	Nota%on	
{:key1"Bar"	
	:key2	[1	2	3]	
	"key3",	#{1.0	2.0	c}	
	:key4,{:foo	{:bar	{:baz	'hello}}}}		
	
(pr-str	{:foo	"bar"})	
(read-string	"{:foo	"bar"}")
f(x)	->	(f	x)	
	
Syntax
Syntax	
if	(...)	{	
		...	
}	else	{							->	
		...		
}	
	
(if	...	
				...	
				...)
Syntax	
var	foo	=	"bar";		
	
(def	foo	"bar")
JavaScript	-	ClojureScript	
if	(bugs.length	>	0)	{	
		return	'Not	ready	for	release';	
}	else	{	
		return	'Ready	for	release';	
}	
	
(if	(pos?	(count	bugs))	
		"Not	ready	for	release"	
		"Ready	for	release")	
source:	hVp://himera.herokuapp.com/synonym.html
JavaScript	-	ClojureScript	
var	foo	=	{bar:	"baz"};	
foo.bar	=	"baz";	
foo["abc"]	=	17;	
	
alert('foo')	
new	Date().getTime()	
new	
Date().getTime().toString()	
	
	
(def	foo	(js-obj	"bar"	"baz"))	
(set!	(.-bar	foo)	"baz")	
(aset	foo	"abc"	17)	
	
(js/alert	"foo")	
(.getTime	(js/Date.))	
(..	(js/Date.)	(getTime)	
(toString))	
source:	hVp://himera.herokuapp.com/synonym.html
Persistent	data	structures	
(def	v	[1	2	3])	
(conj	v	4)	;;	=>	[1	2	3	4]	
(get	v	0)	;;	=>	1	
(v	0)	;;	=>	1
Persistent	data	structures	
(def	m	{:foo	1	:bar	2})	
(assoc	m	:foo	2)	;;	=>	{:foo	2	:bar	2}	
(get	m	:foo)	;;=>	1	
(m	:foo)	;;=>	1	
(:foo	m)	;;=>	1	
(dissoc	m	:foo)	;;=>	{:bar	2}
Func%onal	programming	
(def	r	(->>		
									(range	10)				;;	(0	1	2	..	9)	
									(filter	odd?)	;;	(1	3	5	7	9)	
									(map	inc)))			;;	(2	4	6	8	10)		
;;	r	is	(2	4	6	8	10)
Func%onal	programming	
;;	r	is	(2	4	6	8	10)	
(reduce	+	r)		
;;	=>	30	
(reductions	+	r)	
;;	=>	(2	6	12	20	30)	
	
	
	
var	sum	=	_.reduce(r,	function(memo,	num){	return	memo	+	num;	});
Sequence	abstrac%on	
Data	structures	as	seqs	
(first	[1	2	3])	;;=>	1	
(rest	[1	2	3])	;;=>	(2	3)	
General	seq	func>ons:	map,	reduce,	filter,	...	
(distinct	[1	1	2	3])	;;=>	(1	2	3)	
(take	2	(range	10))	;;=>	(0	1)	
	
See	hVp://clojure.org/cheatsheet	for	more
Sequence	abstrac%on	
Most	seq	func>ons	return	lazy	sequences:	
	
(take	2	(map		
										(fn	[n]	(js/alert	n)	n)		
												(range)))	
	 infinite	lazy	sequence	of	numbers	
side	effect
Mutable	state:	atoms	
(def	my-atom	(atom	0))	
@my-atom	;;	0	
(reset!	my-atom	1)	
(reset!	my-atom	(inc	@my-atom))	;;	bad	idiom	
(swap!	my-atom	(fn	[old-value]	
																		(inc	old-value)))	
(swap!	my-atom	inc)	;;	same	
@my-atom	;;	4
Lisp:	macros	
(map	inc		
		(filter	odd?		
				(range	10)))	
	
(->>		
		(range	10)	
		(filter	odd?)	
		(map	inc))	
thread	last	macro
Lisp:	macros	
(macroexpand		
		'(->>	(range	10)	(filter	odd?)))	
	
;;	=>	(filter	odd?	(range	10))	
	
(macroexpand		
		'(->>	(range	10)	(filter	odd?)	(map	inc)))	
	
;;	=>	(map	inc	(filter	odd?	(range	10)))
Lisp:	macros	
JVM	Clojure:	
	
(defmacro	defonce	[x	init]	
	`(when-not	(exists?	~x)	
				(def	~x	~init)))	
	
	
ClojureScript:	
	
(defonce	foo	1)	
(defonce	foo	2)	;;	no	effect	
notes:		
●  macros	must	be	wriVen	in	JVM	Clojure	
●  are	expanded	at	compile	>me	
●  generated	code	gets	executes	in	ClojureScript
Ar%kel	in	Java	Magazine	over	Clojure	
hVp://michielborkent.nl/nljug/18_21_Clojure.pdf
Demo	%me!	
https://github.com/borkdude/fp-hu-may-2016

More Related Content

What's hot (20)

PPTX
A Brief Intro to Scala
Tim Underwood
 
PDF
Programming in Scala: Notes
Roberto Casadei
 
PPTX
The Evolution of Scala
Martin Odersky
 
PPTX
Scala - The Simple Parts, SFScala presentation
Martin Odersky
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PPTX
Introduction to Scala
Rahul Jain
 
PDF
Martin Odersky - Evolution of Scala
Scala Italy
 
PDF
20160520 what youneedtoknowaboutlambdas
shinolajla
 
PPTX
Introduction to Scala
Mohammad Hossein Rimaz
 
PDF
Scalax
Martin Odersky
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
PDF
Procedure Typing for Scala
akuklev
 
PDF
Aggregate Programming in Scala
Roberto Casadei
 
PDF
Scala eXchange opening
Martin Odersky
 
PDF
Scala test
Inphina Technologies
 
PPTX
Joy of scala
Maxim Novak
 
PDF
Programming with Lambda Expressions in Java
langer4711
 
PDF
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
PPT
Oscon keynote: Working hard to keep it simple
Martin Odersky
 
PDF
Introduction to Scala
Saleem Ansari
 
A Brief Intro to Scala
Tim Underwood
 
Programming in Scala: Notes
Roberto Casadei
 
The Evolution of Scala
Martin Odersky
 
Scala - The Simple Parts, SFScala presentation
Martin Odersky
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Introduction to Scala
Rahul Jain
 
Martin Odersky - Evolution of Scala
Scala Italy
 
20160520 what youneedtoknowaboutlambdas
shinolajla
 
Introduction to Scala
Mohammad Hossein Rimaz
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Procedure Typing for Scala
akuklev
 
Aggregate Programming in Scala
Roberto Casadei
 
Scala eXchange opening
Martin Odersky
 
Joy of scala
Maxim Novak
 
Programming with Lambda Expressions in Java
langer4711
 
Metaprogramming in Scala 2.10, Eugene Burmako,
Vasil Remeniuk
 
Oscon keynote: Working hard to keep it simple
Martin Odersky
 
Introduction to Scala
Saleem Ansari
 

Similar to Functional Programming In Practice (20)

PDF
Functional Programming in Scala: Notes
Roberto Casadei
 
PPTX
Introduction to Functional Programming and Clojure
Soumendra Daas
 
PPTX
Introduction to Functional programming
Ny Fanilo Andrianjafy, B.Eng.
 
PDF
Functional programming is the most extreme programming
samthemonad
 
PDF
Functional programming scala_mod
Kishore
 
PDF
Functional programming 101
Marcle Rodrigues
 
PDF
It's All About Morphisms
Uberto Barbini
 
PDF
Functional programming in Scala
Damian Jureczko
 
PDF
Functional programming in scala
Stratio
 
PDF
Functional Programming In Scala Second Edition Meap V08 2nd All Chapters Avai...
cawulineriku
 
PDF
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
PPTX
About Functional Programming
Aapo Kyrölä
 
PPTX
Scala fundamentals
Alfonso Ruzafa
 
PDF
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
PDF
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
PDF
Scala Quick Introduction
Damian Jureczko
 
PDF
Functional programming with clojure
Lucy Fang
 
PDF
Intro to Functional Programming
Hugo Firth
 
PPTX
Functional programming
Prashant Kalkar
 
PDF
Intro to functional programming - Confoo
felixtrepanier
 
Functional Programming in Scala: Notes
Roberto Casadei
 
Introduction to Functional Programming and Clojure
Soumendra Daas
 
Introduction to Functional programming
Ny Fanilo Andrianjafy, B.Eng.
 
Functional programming is the most extreme programming
samthemonad
 
Functional programming scala_mod
Kishore
 
Functional programming 101
Marcle Rodrigues
 
It's All About Morphisms
Uberto Barbini
 
Functional programming in Scala
Damian Jureczko
 
Functional programming in scala
Stratio
 
Functional Programming In Scala Second Edition Meap V08 2nd All Chapters Avai...
cawulineriku
 
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
About Functional Programming
Aapo Kyrölä
 
Scala fundamentals
Alfonso Ruzafa
 
Ankara Jug - Practical Functional Programming with Scala
Ensar Basri Kahveci
 
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Scala Quick Introduction
Damian Jureczko
 
Functional programming with clojure
Lucy Fang
 
Intro to Functional Programming
Hugo Firth
 
Functional programming
Prashant Kalkar
 
Intro to functional programming - Confoo
felixtrepanier
 
Ad

More from Michiel Borkent (6)

PDF
re-find: fun with spec
Michiel Borkent
 
PDF
ClojureScript interfaces to React
Michiel Borkent
 
PDF
ClojureScript for the web
Michiel Borkent
 
PDF
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
PDF
Full Stack Clojure
Michiel Borkent
 
PPTX
Waarom plantaardig(er)?
Michiel Borkent
 
re-find: fun with spec
Michiel Borkent
 
ClojureScript interfaces to React
Michiel Borkent
 
ClojureScript for the web
Michiel Borkent
 
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
Full Stack Clojure
Michiel Borkent
 
Waarom plantaardig(er)?
Michiel Borkent
 
Ad

Recently uploaded (20)

PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
Deploy Faster, Run Smarter: Learn Containers with QNAP
QNAP Marketing
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PDF
Sound the Alarm: Detection and Response
VICTOR MAESTRE RAMIREZ
 
PDF
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
DoS Attack vs DDoS Attack_ The Silent Wars of the Internet.pdf
CyberPro Magazine
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
Deploy Faster, Run Smarter: Learn Containers with QNAP
QNAP Marketing
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
FME in Overdrive: Unleashing the Power of Parallel Processing
Safe Software
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Sound the Alarm: Detection and Response
VICTOR MAESTRE RAMIREZ
 
Quantum Threats Are Closer Than You Think – Act Now to Stay Secure
WSO2
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 

Functional Programming In Practice