Functional programming scala_mod
-
Upload
kishore-nair -
Category
Technology
-
view
201 -
download
0
description
Transcript of Functional programming scala_mod
FunctionalProgramming
KKishore
FunctionalParadigm>
ImmutablevsMutable>
FunctionsandHigherOrderFunctions>
PatternMatching>
InThisTalk
WhatisFunctionalProgramming?>FunctionalProgramminglanguageisonewhichdoesnothavemutablevariables,assignments,controlstructures.Itenablestheconstructionofelegantprogramsthatfocusonfunctions.(FPhasbeenaroundfor50years).Languages:
Lisp,XQuery,FP,Haskell,Scala,Clojure,etcFunctionalProgrammingisbecomingincreasinglypopularbecauseitoffersanattractivemethodforexploitingparallelismformulticoreandcloudcomputing.
FunctionalParadigm
Needacatalyzer,somethingthatsparksinitialadoptionuntiltheotheradvantagesbecomecleartoeveryone.
>
Multicore(=parallelprogramming)-Cloudcomputing(=distributedprogramming)-
FunctionalParadigm(Why?)
Non‑‑determinism=Parallelprocessing+Mutablestate
>
MutableState>varage=20-age=age+1-
Togetdeterministicprocessing,avoidthemutablestate!Avoidingmutablestatemeansprogrammingfunctionally.
>
TherootoftheProblem
ButwhataboutObjects?>So,shouldweforgetOOandallprograminfunctionalprogramminglanguages?
-
WeneedtocombineOOandFP-
NewObject>Previously:“Objectsarecharacterizedbystate,identity,andbehavior.”(Booch)
-
Now:Eliminateorreducemutablestate.
-
Objects
Scala(ScalableLanguage)
Prof.MartinOdersky
WhatisImmutable?>Examples:-
valage=18//InScala-finalintage=18//Java-constintage=18//C-
WhatisMutable>Examples:-
varage=20//InScala-age=18//Java,C,C++-
ImmutableandMutable
vallist=List(1,2,3)(or)(1::2::3::Nil)>
ImmutableList
1
2
3
Nil
ToDoublethevaluesinthelist.i.e.foralist(1,2,3,4,5)theresultshouldbe(2,4,6,8,10).
>
Let'sdoinJava-
int[]numbers=newint[]{1,2,3,4,5};List<Integer>doubled=newArrayList<>();for(intelem:numbers){doubled.add(elem*2);}System.out.println(doubled);
ImmutableandMutable
PrimitiveObsession
ToDoublethevaluesinthelist.i.e.foralist(1,2,3,4,5)theresultshouldbe(2,4,6,8,10).
>
‑‑ Let'sdoinScalavalnumbers=List(1,2,3,4,5,6)valresult=numbers.map(elem=>elem*2)valresult=numbers.map((elem:Int)=>elem*2)valresult=numbers.map(_*2)
ImmutableandMutable
AnotherSolution:>valnumbers=List(1,2,3,4,5,6)for(elemnumbers){println(elem*2)}
-
Problem:>Ifwelistallthenaturalnumbersbelow10thataremultiplesof3or5,weget3,5,6and9.Thesumofthesemultiplesis23.
Findthesumofallthemultiplesof3or5below1000.
-
(1until1000).filter(elem=>elem%3==0||elem%5==0).sum-
ImmutableandMutable
FunctionsarefirstclassCitizens.AfunctionConsistsof4things.
>
Name-Parameters-Body-ReturnType-
Example:defadd(x:Int,y:Int):Int=x+y
Functions
FunctionKeywordNameParametersBodyReturnType
defadd(x:Int,y:Int):Int=x+y>
Functions
Name
Parameters
ReturnType
Body
AFunctionWithoutaName>Example:-valsum=(x:Int,y:Int)=>x+y-println(sum(5,1))-
WriteaSquarefunctioninScala.i.e.ForInput4theresultis16(4*4)Solutions:
‑‑ defsquare(x:Int)=x*x‑‑ defsquares(x:Int):Int=x*x‑‑ valresult=(x:Int)=>x*x
AnonymousFunction
FuntionsthattakesotherfunctionshasparametersorreturningafunctioniscalledHigherOrderFunction.
>
Example:>
valpriceList=List(5,10,15,17,20,25,28,30,35,40)
Goal:TosumallthepricesdefsumPrices(priceList:List[Int]):Int={varsum=0for(pricepriceList){sum+=price}sum}
HigherOrderFunctions
Goal:TosumallthepricesUnder25>defsumPricesUnder25(prices:List[Int]):Int={varsum=0for(priceprices){if(price<25)sum+=price}sum}
Goal:TosumallthepricesOver25,Under30,etc>
HowwillYouSolvethisProblem?
Key:Weneedgenericfunctioni.e.SinglefunctiontocomputesumofallpricesOver25,Under30,etc
HigherOrderFunctions
Solution:>defsumPrices(prices:List[Int],cond:Int=>Boolean):Int={varsum=0for(priceprices){if(cond(price))sum+=price}sum}
AlterantiveSolution:>defsumPrices(prices:List[Int],cond:Int=>Boolean):Int=prices.filter(cond).sum
HigherOrderFunctions
Problem:ToTestYes/No> deftest(number:Int):String=numbermatch{case0=>"No"case1=>"Yes"case_=>"Error"
}
PatternMatching
Tosumallthevaluesinthelist.i.eList(1,2,3,4,5)=>15> defsum(list:List[Int]):Int=listmatch{
caseNil=>0casex::xs=>x+sum(xs)
}
PatternMatching
1 2 3 4 5 Nil
x xs
ToPrintHelloWorldNtimes>
defntimes(n:Int)=for(in)println("HelloWorld")
SumofOddelementsinaList>
defoddSum(list:List[Int]):Int=list.filter(elem=>elem%2!=0).sum
Problems
Findlengthofthelistwithoutusinglengthfunction>deflength(list:List[Int]):Int=list.map(elem=>1).sumdeflength(list:List[Int]):Int=listmatch{
caseNil=>0casex::xs=>1+length(xs)
}
Problems
Definehead,tail,initandlastmethodsforlist>
Problems
1 2 3 4 5 12
21
56
45
head last
tail
init
twitter.github.com/scala_school>
twitter.github.io/effectivescala/>
CourseraScalacourse(50Kstudentslastyear)>
Scalamadeeasy>
ProgrammingScala>
HowtoLearn
https://www.coursera.org/>http://www.udacity.com/>https://www.edx.org/>http://www.learnstreet.com/>http://teamtreehouse.com>http://nptel.iitm.ac.in/>
Resources