SlideShare a Scribd company logo
Loop	Like	a	Functional	Programing	native
Jiaming	Zhang
03/22/2017
Recap:	FP	Principles
Treat	computation	as	the	evaluation	of	math	functions
Prefer	expression	over	statement
Prefer	recursion	over	iteration
Pure	Function
No	side	effect
Same	Input	->	Same	Output
Higher-order	Function
Avoid	Mutation
Why	talk	about	loop?
Scala	Tutorial
List
A	class	for	immutable	linked	list
val	list	=	List(1,	2,	3)
list.head	//	=>	1
list.tail	//	=>	List(2,	3)
0	::	list	
//	=>	List(0,1,2,3)
0	::	1	::	Nil
//	=>	List(0,1)
List(1,2)	++	List(3,4)
//	=>	List(1,2,3,4)
Scala	Documentation	-	List
Scala	Tutorial
Stream
Scala	Documentation	-	Stream
Scala	Tutorial
Stream
A	Stream	is	like	a	list	except	that	its	elements	are	computed	 lazily .
//	Stream	is	similar	to	list
val	stream	=	Stream(1,	2,	3)
stream.head	//	=>	1
stream.tail	//	=>	Stream(2,	3)
0	#::	stream	
//	=>	Stream(0,1,2,3)
0	#::	1	#::	Stream.Empty
//	=>	Stream(0,1)
Stream(1,2)	++	Stream(3,4)
//	=>	Stream(1,2,3,4)
Scala	Documentation	-	Stream
Scala	Tutorial
Stream
//	Stream	is	the	lazy	version	of	List
def	foo:	Int	=	{
		println("I	am	called")
		42
}
val	list	=	0	::	foo	::	Nil
//	=>	print	"I	am	called"
val	stream	=	0	#::	foo	#::	Stream.Empty
//	=>	print	nothing
stream.tail
//	=>	print	"I	am	called"
//	=>	return	Stream(42)
Scala	Documentation	-	Stream
Scala	Tutorial
Pattern	Match
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	match	constant	just	as	 switch	...	case	... 	in	Java
def	getNumAsWord(n:	Int):	String	=	n	match	{
		case	1	=>	"One"
		case	2	=>	"Two"
		case	_	=>	"Neither	One	Nor	Two"
}
getNumAsWord(1)		//	=>	"One"
getNumAsWord(2)		//	=>	"Two"
getNumAsWord(42)	//	=>	"Neither	One	Nor	Two"
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	create	type	alias	Person
type	Person	=	(String,	Int)
def	AskAge(person:	Person)	=	person	match	{	
		case	("Fibonacci",	_)	=>	"Fibonacci	don't	want	to	talk	about	his	age"
		case	(name,	age)	=>	s"$name	is	$age	years	old"	
}
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	create	type	alias	Person
type	Person	=	(String,	Int)
def	AskAge(person:	Person)	=	person	match	{	
		case	("Fibonacci",	_)	=>	"Fibonacci	don't	want	to	talk	about	his	age"
		case	(name,	age)	=>	s"$name	is	$age	years	old"	
}
AskAge(("Martin",	58))
//	=>	"Martin	is	58	years	old"
AskAge(("Fibonacci",	842))
//	=>	"Fibonacci	don't	want	to	talk	about	his	age"
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	case	class	is	like	Struct	in	other	languages
case	class	Person(name:	String,	age:	Int)
def	AskAge(person:	Person)	=	person	match	{	
		case	Person("Fibonacci",	_)	=>	"Fibonacci	don't	want	to	talk	about	his	age"
		case	Person(name,	age)	=>	s"$name	is	$age	years	old"	
}
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	case	class	is	like	Struct	in	other	languages
case	class	Person(name:	String,	age:	Int)
def	AskAge(person:	Person)	=	person	match	{	
		case	Person("Fibonacci",	_)	=>	"Fibonacci	don't	want	to	talk	about	his	age"
		case	Person(name,	age)	=>	s"$name	is	$age	years	old"	
}
AskAge(Person("Martin",	58))
//	=>	"Martin	is	58	years	old"
AskAge(Person("Fibonacci",	842))
//	=>	"Fibonacci	don't	want	to	talk	about	his	age"
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	List	can	be	used	as	a	case	class
def	head[T](list:	List[T]):	T	=	list	match	{
		case	List(head,	tail)	=>	head
		case	Nil	=>	throw	new	java.util.NoSuchElementException
}
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	List	can	be	used	as	a	case	class
def	head[T](list:	List[T]):	T	=	list	match	{
		case	List(head,	tail)	=>	head
		case	Nil	=>	throw	new	java.util.NoSuchElementException
}
//	`head	::	tail`	is	equivalent	to	`List(head,	tail)`
def	head[T](list:	List[T]):	Option[T]	=	list	match	{
		case	head	::	tail	=>	head
		case	Nil	=>	throw	new	java.util.NoSuchElementException
}
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
It	can	also	unpack	some	structured	data	(e.g.	tuple,	case	class,	list)
//	List	can	be	used	as	a	case	class
def	head[T](list:	List[T]):	T	=	list	match	{
		case	List(head,	tail)	=>	head
		case	Nil	=>	throw	new	java.util.NoSuchElementException
}
//	`head	::	tail`	is	equivalent	to	`List(head,	tail)`
def	head[T](list:	List[T]):	Option[T]	=	list	match	{
		case	head	::	tail	=>	head
		case	Nil	=>	throw	new	java.util.NoSuchElementException
}
head(List(1,2))	//	=>	Some(1)
head(List())				//	=>	None
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
Here	is	an	example	of	how	you	can	use	pattern	matching	to	deal	w/	different	subtypes
sealed	trait	Tree
case	class	Branch(v:	Int,	left:	Tree,	right:	Tree)	extends	Tree
case	class	Leaf(v:	Int)	extends	Tree
def	sum(t:	Tree):	Int	=	t	match	{
		case	Branch(v,	left,	right)	=>	v	+	sum(left)	+	sum(right)
		case	Leaf(v)	=>	v
}
val	tree1	:	Tree	=	Branch(1,	Leaf(1),	Leaf(2))
val	tree2	:	Tree	=	Branch(1,	Branch(1,	Leaf(1),	Leaf(2)),	Leaf(2))
sum(tree2)	//	=>	7
sum(tree1)	//	=>	4
Playing	with	Scala’s	pattern	matching
Scala	Tutorial
Pattern	Match
Sometime	we	want	to	perform	diff	operation	based	on	the	object	type.	Here	is	the	comparison	between	doing
this	via	pattern	match	and	via	Java's	 instanceof 	method.
//	Compiler	will	complain	before	Integer	does	not	have	method	`toChar`
def	f(x:	Any):	String	=	x	match	{
		case	i:	Int	=>	"Integer:	"	+	i.toChar(0)
		case	s:	String	=>	"String:	"	+	s
		case	_	=>	"Unknown	Input"
}
//	Compiler	won't	complain	and	exception	will	raise	at	run-time
public	String	f(Object	x)	{
		if	(x	instanceof	Integer)	{
				return	"Integer:	"	+	i.charAt(0)
		}	
		//	.....
}
Playing	with	Scala’s	pattern	matching
Use	Recursion
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
Use	Recursion
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
//	Imperative
def	fact(n:	Int):	Int	=	{
		var	res	=	1
		for(i	<-	1	to	n)	{
				res	*=	i
		}
		return	res
}
Use	Recursion
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
//	Imperative
def	fact(n:	Int):	Int	=	{
		var	res	=	1
		for(i	<-	1	to	n)	{
				res	*=	i
		}
		return	res
}
//	Functional
def	fact(n:	Int):	Int	=	
		if	(n	==	0)	1	
		else	n	*	fact(n-1)
Use	Recursion
Why	Recursion?
1.	 Easy	to	understand
2.	 Easy	to	prove	its	correctness
Use	Recursion
Why	Recursion?
1.	 Easy	to	understand
2.	 Easy	to	prove	its	correctness
def	fact(n:	Int):	Int	=	
		if	(n	==	0)	1	
		else	n	*	fact(n-1)
Use	Recursion
Why	Recursion?
1.	 Easy	to	understand
2.	 Easy	to	prove	its	correctness
def	fact(n:	Int):	Int	=	
		if	(n	==	0)	1	
		else	n	*	fact(n-1)
Simply	a	function	call	using	substitution
fact(3)	=	if	(3	==	0)	1	else	3	*	fact(3-1)
								=	3	*	fact(2)
								=	3	*	(if	(2	==	0)	1	else	2	*	fact(2-1))
								=	...
								=	3	*	2	*	1	*	1
Use	Recursion
Question:	Find	the	length	of	a	list	using	recursion
Use	Recursion
Question:	Find	the	length	of	a	list	using	recursion
def	length[T](list:	List[T]):	Int	=	list	match	{
		case	Nil	=>	0
		case	head	::	tail	=>	1	+	length(tail)
}
Use	Recursion
Question:	Find	the	length	of	a	list	using	recursion
def	length[T](list:	List[T]):	Int	=	list	match	{
		case	Nil	=>	0
		case	head	::	tail	=>	1	+	length(tail)
}
length(List())	//	=>	0
length(List(1,2))	//	=>	2
Use	Recursion
Question:	Find	the	length	of	a	list	using	recursion
def	length[T](list:	List[T]):	Int	=	list	match	{
		case	Nil	=>	0
		case	head	::	tail	=>	1	+	length(tail)
}
length(List())	//	=>	0
length(List(1,2))	//	=>	2
However,	there	is	a	performance	issue	w/	this	function.
Use	Recursion
Question:	Find	the	length	of	a	list	using	recursion
def	length[T](list:	List[T]):	Int	=	list	match	{
		case	Nil	=>	0
		case	head	::	tail	=>	1	+	length(tail)
}
length(List())	//	=>	0
length(List(1,2))	//	=>	2
However,	there	is	a	performance	issue	w/	this	function.
val	bigList	=	(1	to	40000).toList
length(bigList)
//	=>	throw	java.lang.StackOverflowError
Use	Tail	Recursion
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
Use	Tail	Recursion
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
import	scala.annotation.tailrec
def	fact(n:	Int):	Int	=	{
		//	@tailrec	does	not	gurantee	tail	recursion
		//		it	simply	raise	an	exception	when	there	is	not
		@tailrec	
		def	factHelper(n:	Int,	acc:	Int):	Int	=	
				if	(n	==	0)	acc
				else	factHelper(n-1,	acc	*	n)
		factHelper(n,	1)
}
Use	Tail	Recursion
Question:	Find	the	length	of	a	list	using	tail	recursion
Use	Tail	Recursion
Question:	Find	the	length	of	a	list	using	tail	recursion
def	length[T](list:	List[T]):	Int	=	{
		def	lengthHelper(list:	List[T],	acc:	Int):	Int	=	list	match	{
				case	Nil	=>	acc
				case	head	::	tail	=>	lengthHelper(tail,	acc+1)
		}
		lengthHelper(list,	0)
}
Use	Tail	Recursion
Question:	Find	the	length	of	a	list	using	tail	recursion
def	length[T](list:	List[T]):	Int	=	{
		def	lengthHelper(list:	List[T],	acc:	Int):	Int	=	list	match	{
				case	Nil	=>	acc
				case	head	::	tail	=>	lengthHelper(tail,	acc+1)
		}
		lengthHelper(list,	0)
}
length((1	to	40000).toList)
//	=>	40000
Use	High-order	Function
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
Use	High-order	Function
Question:	Define	the	factorial	function	 fact(n) ,	given	 n	>=	0
def	fact(n:	Int):	Int	=	
		(1	to	n).fold(1)	{	(acc,	x)	=>	acc	*	x		}
//	Or	a	shorter	version
def	fact(n:	Int):	Int	=	
		(1	to	n).fold(1)	{	_	*	_	}
Use	High-order	Function
Common	high-order	functions	for	collections	(e.g.	array,	list)	include:
(1	to	3).map(x	=>	x	*	2)
//	=>	Vector(2,	4,	6)
(0	to	1).flatMap(x	=>	(0	to	2).map(y	=>	(x,y)))
//	=>	Vector((0,0),	(0,1),	(1,0),	(1,1),	(2,0),	(2,1))
(1	to	10).filter(x	=>	isPrime(x))
//	=>	Vector(2,	3,	5,	7)
(1	to	10).fold(0)	{	(acc,	x)	=>	acc	+	x	}
//	=>	55
Use	High-order	Function
These	high-order	functions	 recursively 	apply	certain	computation	to	a	collection
abstract	class	List[+T]	{
		def	map[U](f:	T	=>	U):	List[U]	=	this	match	{
				case	x	::	xs	=>	f(x)	::	xs.map(f)
				case	Nil	=>	Nil
		}
		def	filter(p:	T	=>	Boolean):	List[T]	=	this	match	{
				case	x	::	xs	=>	
						if	(p(x))	x	::	xs.filter(p)	else	xs.filter(p)
				case	Nil	=>	Nil
		}
}
Use	High-order	Function
These	high-order	functions	 recursively 	apply	certain	computation	to	a	collection
abstract	class	List[+T]	{
		def	map[U](f:	T	=>	U):	List[U]	=	this	match	{
				case	x	::	xs	=>	f(x)	::	xs.map(f)
				case	Nil	=>	Nil
		}
		def	filter(p:	T	=>	Boolean):	List[T]	=	this	match	{
				case	x	::	xs	=>	
						if	(p(x))	x	::	xs.filter(p)	else	xs.filter(p)
				case	Nil	=>	Nil
		}
}
The	actual	implementation	are	 different 	from	this	simplied	version	in	order	to:
make	them	apply	to	arbitrary	collections,	not	just	lists
make	them	tail-recursive	on	lists
Use	High-order	Function
Question:	Find	the	longest	word	(assume	there	is	ONLY	one)
val	words	=	List("way",	"jam",	"complain",	"second-hand",	"elite")
//	Assume	this	method	is	given
def	findLongerWord(w1:	String,	w2:	String)	=	{	...	}
Use	High-order	Function
Question:	Find	the	longest	word	(assume	there	is	ONLY	one)
val	words	=	List("way",	"jam",	"complain",	"second-hand",	"elite")
//	Assume	this	method	is	given
def	findLongerWord(w1:	String,	w2:	String)	=	{	...	}
//	Tail	Recursion
def	findLongestWord(words:	List[String]):	String	=	{
		@tailrec
		def	go(words:	List[String],	longestWord:	String)	=	words	match	{
				case	Nil	=>	longestWord
				case	word	::	otherWords	=>	go(otherWords,	findLongerWord(longestWord,	word))
		}
		go(words,	"")
}
Use	High-order	Function
Question:	Find	the	longest	word	(assume	there	is	ONLY	one)
val	words	=	List("way",	"jam",	"complain",	"second-hand",	"elite")
//	Assume	this	method	is	given
def	findLongerWord(w1:	String,	w2:	String)	=	{	...	}
//	Use	High-order	Function
def	findLongestWord(words:	List[String]):	String	=	
				words.fold("")	{	(acc,	x)	=>	findLongerWord(acc,	x)	}
Use	High-order	Function
Question:	Find	the	longest	word	(assume	there	is	ONLY	one)
val	words	=	List("way",	"jam",	"complain",	"second-hand",	"elite")
//	Assume	this	method	is	given
def	findLongerWord(w1:	String,	w2:	String)	=	{	...	}
//	Use	High-order	Function
def	findLongestWord(words:	List[String]):	String	=	
				words.fold("")	{	(acc,	x)	=>	findLongerWord(acc,	x)	}
def	findLongestWord(words:	List[String]):	String	=	
				words.fold("")(findLongerWord)
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
//	Here	are	the	data	model
//	`case	class`	is	Struct	(kind	of)	in	Scala
case	class	Employee(name:	String)
case	class	Department(name:	String,	employees:	List[Employee])
case	class	Company(name:	String,	revenue:	BigInt,	departments:	List[Department])
//	Association
//			A	company	has	many	departments
//			A	department	has	many	employees
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
val	companies	=	loadDataFromDatabase()
//	Works	but	not	very	readable
val	res	=	companies
		.filter(company	=>	company.revenue	>	5000000)
		.flatMap(company	=>	
				company.departments.
						filter(d	=>	d.name	==	"marketing").
						flatMap(d	=>	d.employees.map(e	=>	e.name))
		)
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
//	Easier	to	read	but
//			this	helper	function	is	too	specific	to	be	reused
def	getMarketingEmployeeName(company:	Company):	List[String]	=	{
			company.departments.
					filter(d	=>	d.name	==	"marketing").
					flatMap(d	=>	d.employees.map(e	=>	e.name))
}
val	res	=	companies
		.filter(company	=>	company.revenue	>	5000000)
		.flatMap(company	=>	getMarketingEmployeeName(company))
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
//	More	readable	but	less	efficient	-	
//		create	unnecessary	intermediate	result
val	res	=	companies
		.filter(c	=>	c.revenue	>	5000000)
		.flatMap(c	=>	c.departments)
		.filter(d	=>	d.name	==	"marketing")
		.flatMap(d	=>	d.employees)
		.map(e	=>	e.name)
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
//	As	efficient	as	the	1st/2nd	one	and
//		as	readable	as	the	3rd	one
for	{
		c	<-	companies
		if	c.revenue	>	5000000
		d	<-	c.departments
		if	d.name	==	"marketing"
		e	<-	d.employees
}	yield	e.name
Use	High-order	Function
Question:	Get	the	name	of	employees
who	work	at	a	company	w/	more	than	5	million	revenue
who	work	at	the	marketing	department
//	As	efficient	as	the	1st/2nd	one	and
//		as	readable	as	the	3rd	one
for	{
		c	<-	companies
		if	c.revenue	>	5000000
		d	<-	c.departments
		if	d.name	==	"marketing"
		e	<-	d.employees
}	yield	e.name
For	expression	will	be	converted	into	a	set	of	 map ,	 flatMap ,	 withFilter 	(or	 filter )	operations.
NOTE:	Skip	Lazy	Evaluation	and	Infinite	List	if	prev	section	takes	too	long
Lazy	Evaluation	and	Infinite	List
Question:	Find	nth	prime	number
nthPrime(0)	//	=>	2
nthPrime(1)	//	=>	3
nthPrime(5)	//	=>	13
Lazy	Evaluation	and	Infinite	List
Question:	Find	nth	prime	number
nthPrime(0)	//	=>	2
nthPrime(1)	//	=>	3
nthPrime(5)	//	=>	13
//	Imperative
//	This	solution	is	error-prone
def	nthPrime(n:	Int):	Int	=	{
		var	k	=	2
		var	counter	=	0
		while	(counter	<	n)	{
				k	+=	1
				if	(isPrime(k))	{	counter	+=	1	}
		}
		k
}
Lazy	Evaluation	and	Infinite	List
Question:	Find	nth	prime	number
nthPrime(0)	//	=>	2
nthPrime(1)	//	=>	3
nthPrime(5)	//	=>	13
//	Use	higher-order	function
def	nthPrime(n:	Int,	upperBound:	Int):	Int	=	{
		(1	to	upperBound).filter(isPrime)(n)
}
Lazy	Evaluation	and	Infinite	List
Question:	Find	nth	prime	number
nthPrime(0)	//	=>	2
nthPrime(1)	//	=>	3
nthPrime(5)	//	=>	13
But	...	how	do	we	know	the	value	of	 upperBound
Lazy	Evaluation	and	Infinite	List
Question:	Find	nth	prime	number
nthPrime(0)	//	=>	2
nthPrime(1)	//	=>	3
nthPrime(5)	//	=>	13
But	...	how	do	we	know	the	value	of	 upperBound
//	`upperBound`	is	too	small	=>	exception
nthPrime(50,	100)
//	`upperBound`	is	too	large	=>	run	forever
nthPrime(50,	Int.MaxValue)	
//	`upperBound`	has	the	perfect	value,	which	will	be	the	answer	itself
nthPrime(50,	229)
Lazy	Evaluation	and	Infinite	List
Question:	Find	nth	prime	number
nthPrime(0)	//	=>	2
nthPrime(1)	//	=>	3
nthPrime(5)	//	=>	13
//	http://stackoverflow.com/questions/13206552/scala-rangex-int-maxvalue-vs-stream-fromx
//	Use	Stream	for	Lazy	Evaluation
def	nthPrime(n:	Int):	Int	=	primeNums(n)
//	A	stream	of	prime	number
def	primeNums:	Stream[Int]	=	
		Stream.from(2).filter(isPrime)
primeNums.take(3)								//	=>	Stream(2,	?)
primeNums.take(3).toList	//	=>	List(2,3,5)
Lazy	Evaluation	and	Infinite	List
Question:	Get	the	nth	fib	number
//	Assume	n	>	0
def	fib(n:	Int):	Int	=	{
		if	(n	==	0)	1
		else	if	(n	==	1)	1
		else	fib(n-1)	+	fib(n-2)
}
def	fib(n:	Int):	Int	=	{
		def	fibNums(n1:	Int,	n2:	Int):	Stream[Int]	=	{
				n1	#::	fibNums(n2,	n1+	n2)
		}
		fibNums(1,	1)(n)
}
Lazy	Evaluation	and	Infinite	List
Question:	Create	the	prime	number	sequence	using	Sieve	of	Eratosthenes
def	sieve(s:	Stream[Int]):	Stream[Int]	=
		s.head	#::	sieve(s.tail	filter	(_	%	s.head	!=	0))
val	primes	=	sieve(Stream.from(2))
primes.take(5).toList
//	=>	List(2,	3,	5,	7,	11)
Lazy	Evaluation	and	Infinite	List
Question:	How	to	implement	 sqrt 	method	recursively
def	sqrtStream(x:	Double):	Stream[Double]	=	{
		def	improve(guess:	Double)	=	(guess	+	x	/	guess)	/	2
		//	TODO:	What	if	no	`lazy`
		lazy	val	guesses:	Stream[Double]	=	1	#::	(guesses	map	improve)
		guesses
}
Lazy	Evaluation	and	Infinite	List
Question:	How	to	implement	 sqrt 	method	recursively
def	sqrtStream(x:	Double):	Stream[Double]	=	{
		def	improve(guess:	Double)	=	(guess	+	x	/	guess)	/	2
		//	TODO:	What	if	no	`lazy`
		lazy	val	guesses:	Stream[Double]	=	1	#::	(guesses	map	improve)
		guesses
}
sqrtStream(4).take(8).toList
//	=>	List(1.0,	2.5,	2.05,	2.000609756097561,	2.0000000929222947,	2.000000000000002,	2.0,	2.0)
def	isGoodEnough(guess:	Double,	x:	Double)	=	
		math.abs((guess	*	guess	-	x)	/	x)	<	0.0001
sqrtStream(4).filter(isGoodEnough(_,	4)).take(1).head
//	=>	2.0000000929222947
Coursera:	Functional	Programing	Design	in	Scala
Summary
Here	are	the	Functional	Programing	approaches	that	replaces	the	imperative	 for 	or	 while 	loop:
Recursion
Tail	Recursion
High-order	Function
Lazy	Eval	and	Infinite	List

More Related Content

What's hot (17)

Data structure lecture 5
Data structure lecture 5Data structure lecture 5
Data structure lecture 5
 
Sql slid
Sql slidSql slid
Sql slid
 
Linked list
Linked listLinked list
Linked list
 
Lists
Lists Lists
Lists
 
Linked list
Linked listLinked list
Linked list
 
Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]Data Structures - Lecture 7 [Linked List]
Data Structures - Lecture 7 [Linked List]
 
Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)Data Structure (Dynamic Array and Linked List)
Data Structure (Dynamic Array and Linked List)
 
Link List
Link ListLink List
Link List
 
Linked lists in Data Structure
Linked lists in Data StructureLinked lists in Data Structure
Linked lists in Data Structure
 
Linked list
Linked listLinked list
Linked list
 
Queues and Stacks
Queues and StacksQueues and Stacks
Queues and Stacks
 
Data Structure Lecture 5
Data Structure Lecture 5Data Structure Lecture 5
Data Structure Lecture 5
 
Latex workshop: Essentials and Practices
Latex workshop: Essentials and PracticesLatex workshop: Essentials and Practices
Latex workshop: Essentials and Practices
 
linked list
linked list linked list
linked list
 
Sql server select queries ppt 18
Sql server select queries ppt 18Sql server select queries ppt 18
Sql server select queries ppt 18
 
Linked list
Linked listLinked list
Linked list
 
The LaTeX Workshop: Document design in LaTeX: Invocation
The LaTeX Workshop: Document design in LaTeX: InvocationThe LaTeX Workshop: Document design in LaTeX: Invocation
The LaTeX Workshop: Document design in LaTeX: Invocation
 

Viewers also liked

ENC Times-March 24,2017
ENC Times-March 24,2017ENC Times-March 24,2017
ENC Times-March 24,2017ENC
 
Proceso de producción agrícola de la fresa
Proceso de producción agrícola de la fresaProceso de producción agrícola de la fresa
Proceso de producción agrícola de la fresaJavier1402
 
Taller de insercion laboral
Taller de insercion laboralTaller de insercion laboral
Taller de insercion laboralsebastian diaz
 
Confined space – hazards –risk –control measures
Confined space – hazards –risk –control measuresConfined space – hazards –risk –control measures
Confined space – hazards –risk –control measuresAnand Prakash
 
Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)
Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)
Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)Oscar Raul Dominguez
 
3Com 655000201
3Com 6550002013Com 655000201
3Com 655000201savomir
 

Viewers also liked (10)

Slideshare
SlideshareSlideshare
Slideshare
 
Story research
Story researchStory research
Story research
 
ENC Times-March 24,2017
ENC Times-March 24,2017ENC Times-March 24,2017
ENC Times-March 24,2017
 
Proceso de producción agrícola de la fresa
Proceso de producción agrícola de la fresaProceso de producción agrícola de la fresa
Proceso de producción agrícola de la fresa
 
Taller de insercion laboral
Taller de insercion laboralTaller de insercion laboral
Taller de insercion laboral
 
Confined space – hazards –risk –control measures
Confined space – hazards –risk –control measuresConfined space – hazards –risk –control measures
Confined space – hazards –risk –control measures
 
Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)
Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)
Manual tipos-rodillos-tractores-orugas-cadenas-bulldozer (1)
 
3Com 655000201
3Com 6550002013Com 655000201
3Com 655000201
 
Calendario Ass. Mon'Do'
Calendario Ass. Mon'Do'Calendario Ass. Mon'Do'
Calendario Ass. Mon'Do'
 
Ab censeñanza ddhh
Ab censeñanza ddhhAb censeñanza ddhh
Ab censeñanza ddhh
 

Similar to Loop Like a Functional Programing Native

Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkAngelo Leto
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1Hang Zhao
 
Relational data model
Relational data modelRelational data model
Relational data modelSURBHI SAROHA
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキストOpt Technologies
 
LISP: Introduction To Lisp
LISP: Introduction To LispLISP: Introduction To Lisp
LISP: Introduction To LispLISP Content
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Sedna XML Database System: Internal Representation
Sedna XML Database System: Internal RepresentationSedna XML Database System: Internal Representation
Sedna XML Database System: Internal RepresentationIvan Shcheklein
 
Mandatory sql functions for beginners
Mandatory sql functions for beginnersMandatory sql functions for beginners
Mandatory sql functions for beginnersshravan kumar chelika
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalUrs Peter
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptxssuser8e50d8
 

Similar to Loop Like a Functional Programing Native (20)

Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Module III.pdf
Module III.pdfModule III.pdf
Module III.pdf
 
FINAL revised LIST in Python.pdf
FINAL revised LIST in Python.pdfFINAL revised LIST in Python.pdf
FINAL revised LIST in Python.pdf
 
Fp in scala part 1
Fp in scala part 1Fp in scala part 1
Fp in scala part 1
 
Relational data model
Relational data modelRelational data model
Relational data model
 
学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト学生向けScalaハンズオンテキスト
学生向けScalaハンズオンテキスト
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
LISP: Introduction To Lisp
LISP: Introduction To LispLISP: Introduction To Lisp
LISP: Introduction To Lisp
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Sedna XML Database System: Internal Representation
Sedna XML Database System: Internal RepresentationSedna XML Database System: Internal Representation
Sedna XML Database System: Internal Representation
 
Mandatory sql functions for beginners
Mandatory sql functions for beginnersMandatory sql functions for beginners
Mandatory sql functions for beginners
 
List,Stacks and Queues.pptx
List,Stacks and Queues.pptxList,Stacks and Queues.pptx
List,Stacks and Queues.pptx
 
6. list
6. list6. list
6. list
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Python lists
Python listsPython lists
Python lists
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
ADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASADADVANCE ITT BY PRASAD
ADVANCE ITT BY PRASAD
 

More from Jiaming Zhang

Elasticsearch Internal - Shards
Elasticsearch Internal - ShardsElasticsearch Internal - Shards
Elasticsearch Internal - ShardsJiaming Zhang
 
Option - A Better Way to Handle Null Value
Option - A Better Way to Handle Null ValueOption - A Better Way to Handle Null Value
Option - A Better Way to Handle Null ValueJiaming Zhang
 
Functional Programing Principles
Functional Programing PrinciplesFunctional Programing Principles
Functional Programing PrinciplesJiaming Zhang
 
Job Posts Comparison (Linkedin vs Indeed)
Job Posts Comparison (Linkedin vs Indeed) Job Posts Comparison (Linkedin vs Indeed)
Job Posts Comparison (Linkedin vs Indeed) Jiaming Zhang
 
Understand the Demand of Analyst Opportunity in U.S
Understand the Demand of Analyst Opportunity in U.SUnderstand the Demand of Analyst Opportunity in U.S
Understand the Demand of Analyst Opportunity in U.SJiaming Zhang
 
Course Project: Collaboration Proposal Between Port Authority and Tiramisu Team
Course Project: Collaboration Proposal Between Port Authority and Tiramisu TeamCourse Project: Collaboration Proposal Between Port Authority and Tiramisu Team
Course Project: Collaboration Proposal Between Port Authority and Tiramisu TeamJiaming Zhang
 

More from Jiaming Zhang (6)

Elasticsearch Internal - Shards
Elasticsearch Internal - ShardsElasticsearch Internal - Shards
Elasticsearch Internal - Shards
 
Option - A Better Way to Handle Null Value
Option - A Better Way to Handle Null ValueOption - A Better Way to Handle Null Value
Option - A Better Way to Handle Null Value
 
Functional Programing Principles
Functional Programing PrinciplesFunctional Programing Principles
Functional Programing Principles
 
Job Posts Comparison (Linkedin vs Indeed)
Job Posts Comparison (Linkedin vs Indeed) Job Posts Comparison (Linkedin vs Indeed)
Job Posts Comparison (Linkedin vs Indeed)
 
Understand the Demand of Analyst Opportunity in U.S
Understand the Demand of Analyst Opportunity in U.SUnderstand the Demand of Analyst Opportunity in U.S
Understand the Demand of Analyst Opportunity in U.S
 
Course Project: Collaboration Proposal Between Port Authority and Tiramisu Team
Course Project: Collaboration Proposal Between Port Authority and Tiramisu TeamCourse Project: Collaboration Proposal Between Port Authority and Tiramisu Team
Course Project: Collaboration Proposal Between Port Authority and Tiramisu Team
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024Stephanie Beckett
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backElena Simperl
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2DianaGray10
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekCzechDreamin
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2UiPath Test Automation using UiPath Test Suite series, part 2
UiPath Test Automation using UiPath Test Suite series, part 2
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 

Loop Like a Functional Programing Native