functional programing principles
TRANSCRIPT
ScopeThesewon'tbecoveredinthissection(butalreadyonmyradar!)
FPLanguage
FPDesignPattern
FPDataStructures
FPw/OOP
SuccessStories
What'sFunctionalPrograming?Incomputerscience,functionalprogrammingisaprogramming
paradigmthattreatscomputationastheevaluationofmathematical
functionsandavoidschanging-stateandmutabledata.[1]
[1]Wikipedia-FunctionalProgramining
What'sFunctionalPrograming?What'sprogramingparadigm?
Astyleofbuildingthestructureandelementsofcomputerprograms.Commonparadiagmincludes[1]:
Imperative
Declarative
Object-oriented
Functional
Note:Paradigmcanoverlaporcanbeusedw/eachother.
[1]DefinitionofProgramingParadigms
FPPrinciplesTreatcomputationastheevaluationofmathfunctions
PureFunction
High-orderFunction(orFunctor)
AvoidMutation
...
FPPrinciples
TreatcomputationastheevaluationofmathfunctionsAmathfunctionmapsasetofinputtoasetofoutput.
FPPrinciples
TreatcomputationastheevaluationofmathfunctionsFPusuallyprefersexpressionoverstatement
#Assumevalisint
#Statementdefabs1(val):ifval<0:return-valelse:returnval
#Expressiondefabs2(val):return-valifval<0elseval
FPPrinciples
TreatcomputationastheevaluationofmathfunctionsAnequivalentHaskellexample
abs::Int->Intabsval|val<0=-val|otherwise=val
FPPrinciples
TreatcomputationastheevaluationofmathfunctionsFPusuallyprefersrecursionoveriteration
#Iteration-ProceduralStyledefsum1(nums):total=0fornuminnums:total+=numreturntotal
#Recursion-FunctionalStyledefsum2(nums):#NotveryefficientinPythonbutyougottheideareturn0iflen(nums)==0elsenums[0]+sum2(nums[1:])
FPPrinciples
TreatcomputationastheevaluationofmathfunctionsAnequivalentHaskellexample
sum::[Int]->Intsumnums=casenumsof[]->0x:xs->x+sum2xs
FPPrinciples
PureFunction#1Nosideeffect
ExampleofFunctionw/SiteEffect
defsayhi(name)print("Hithere,mynameis%s"%name)
defwrite_to_file(file,text):withopen(file,'w+')asf:f.write(text)
defsort_nums(nums):nums.sort()#inplacesortreturnnums
FPPrinciples
PureFunction#1Nosideeffect
Butwhycreateanappthatcan'tchangethe"world"?
Inpractice,applicationsneedtohavesomesideeffects.Simon
Peyton-Jones,amajorcontributortothefunctionalprogramming
languageHaskell,saidthefollowing:"Intheend,anyprogrammust
manipulatestate.Aprogramthathasnosideeffectswhatsoeverisa
kindofblackbox.Allyoucantellisthattheboxgetshotter."Thekey
istolimitsideeffects,clearlyidentifythem,andavoidscattering
themthroughoutthecode.[1]
[1]Whyareside-effectsconsideredevilinfunctionalprogramming?
FPPrinciples
PureFunction#2Sameinput,sameoutput
ExampleofFunctionthatViolatesthis
gloabl_counter=0
functionfoo(x){gloabl_counter+=1;returngloabl_counter+x;}
foo(1)//=>2foo(1)//=>3
FPPrinciples
PureFunction#2Sameinput,sameoutput
ExampleofFunctionthatViolatesthis
gloabl_counter=0
functionfoo(x){gloabl_counter+=1;returngloabl_counter+x;}
foo(1)//=>2foo(1)//=>3
Otherexamples?
FPPrinciples
High-orderFunction(orFunctor)Example:Afunctionthattakesanotherfunctionasinput
nums=[1,2,3]
map(lambdax:x*2,nums)#=>[2,4,6]
filter(lambdax:x%2==0,nums)#=>[2]
reduce(lambdatotal,num:total*num,nums)#=>6
FPPrinciples
High-orderFunction(orFunctor)Example:Afunctionthatreturnsafunctionasoutput
dirs=['lib','bin','log']
#`functools`isabuilt-inPythonmodule#`functools.partial`returnapartial-appliedfuncfunc=functools.partial(os.path.join,'/User/jason')
map(func,dirs)#=>['/User/jason/lib','/User/jason/bin','/User/jason/log']
FPPrinciples
High-orderFunction(orFunctor)Q:Canyoudothisw/justlambda?
map(lambdadirname:os.path.join('/User/jason',dirname),dirs)#=>['/User/jason/lib','/User/jason/bin','/User/jason/log']
FPPrinciples
High-orderFunction(orFunctor)AnotherExample--Compose
defcompose(f,g):defcomposed_func(val):returng(f(val))returncomposed_func
FPPrinciples
High-orderFunction(orFunctor)AnotherExample--Compose
defcompose(f,g):defcomposed_func(val):returng(f(val))returncomposed_func
dirname='~/lib/../log'
os.path.abspath(os.path.expanduser(dirname))#=>/Users/jiamingz/log
expandpath=compose(os.path.expanduser,os.path.abspath)expandpath(dirname)expandpath('~/lib/python/..')
FPPrinciples
High-orderFunction(orFunctor)Composeisacommonhigh-orderfunctioninFPlang
add5::Int->Intadd5x=5+x
mul5::Int->Intmul5x=5*x
mul5_and_add5::Int->Intmul5_and_add5=add5.mul5
FPPrinciples
AvoidMutation[1,2,3]->[1,2,42]
Example:Mutation
defchange(arr,idx,new_val):arr[idx]=new_valreturnarr
FPPrinciples
AvoidMutation[1,2,3]->[1,2,42]
Example:Mutation
defchange(arr,idx,new_val):arr[idx]=new_valreturnarr
Example:NoMutation
defchange(arr,idx,new_val):returnarr[:idx]+[new_val]+arr[idx+1:]
change([1,2,3],2,42)#=>[1,2,42]
FPPrinciples
AvoidMutationWait...whatabouttheefficiency?
Persistentdatastructure
Notgonnacovertothistime.Ifyou'reinterested,checkthisIdealHashTree
Reference/ReadingWikipedia-FunctionalPrograming
Wikipedia-PureFunction
Wikipedia-HigherOrderFunction
AnjanaVakil:LearningFunctionalProgrammingwithJavaScript-
JSUnconf2016
TheOriginsofScala
Eassy-WhyFunctionalProgramingMattersbyJohnHughes
Youtube-WhyFunctionalProgrammingMattersbyJohnHughesat
FunctionalConf2016