SlideShare une entreprise Scribd logo
1  sur  63
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Dernier (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Loop Like a Functional Programing Native