SlideShare a Scribd company logo
Intro to Functional Programming Part 1:  Single-assignment and Recursive Techniques
What is Functional Programming? Functions return values Given a set of values in the parameter list, the function can only have one possible result. Functions have no side-effects Do not modify variables passed to them Do not modify any global variable Variables only assigned once
What’s the Point? Principle of Least Surprise Principle of Least Surprise All possible inputs to any function are listed in the parameter list - no worries about global state Single assignment means that you never have to wonder how a variable got its definition since it is only defined one place in the entire function Loops much easier to comprehend and debug Simpler execution model makes program proving easier, both for computers and humans (i.e. debugging) Explicitly mention stateless.  Might also talk about theoretical statelessness of the web, but also why it isn’t truly stateless.
No assignments!  How do you loop? Functional programs are usually heavily recursive Looping is either done with a looping construct (such as  map ,  each ,  select , etc.) or with recursion Rather than setting values on each iteration, the loop itself is a function that calls itself recursively Each iteration the function simply gets called with new values Need to mention that although you _can_ do recursive algorithms and modify state, that is usually the worst of both worlds.
Recursion Basics Before we talk about looping with recursion, let’s talk about recursion itself Recursion is where a function calls itself In recursion the goal is to get the data to a smaller  version to solve, until it is to a point where the solution is a simple operation -- this is called the  base case If your recursive function does not have a base case, it will  never return .  That’s usually considered bad.
Recursion Example: The Factorial Function The Factorial Function The factorial function multiplies a number by each number below it until 1 5! (! means factorial) is the same as 5 * 4 * 3 * 2 * 1 Here’s the factorial function in ruby: def factorial(number)  if number == 1  #Base Case -- compute answer  return 1  else  #Get us closer to the base case  return number * factorial(number - 1)  endend Note that we didn’t do ANY assignment in the whole program -- we just passed parameters.  Function calls create new variables, so if we think we want to do assignment, in functional programming you usually want to call a function or create a different variable.
Selection Sort Example Two lists: already-sorted values and unsorted values First list will start empty Each iteration, find the smallest unsorted value and put it at the end of the sorted list Base case: unsorted values list is empty - just return the sorted values
Selection Sort Example def select_sort(values)  select_sort_loop([], values)enddef select_sort_loop(sorted_values, unsorted_values)  if unsorted_values.empty? #BASE CASE!  return sorted_values  else #FIND SMALLEST VALUE AND ITS INDEX  smallest_value_index = find_smallest_value_index(unsorted_values)  smallest_value = unsorted_values[smallest_value_index] #CREATE NEW SORTED AND UNSORTED ARRAYS  new_sorted_values = add_element(sorted_values, smallest_value)  new_unsorted_values = remove_element_index(unsorted_values, smallest_value_index) #LOOP WITH NEW VALUES  return select_sort_loop(new_sorted_values, new_unsorted_values)  endend select_sort([1,5,23,8,3,5,6,8,34,65,2,5,3])
Selection Sort:  Utility Functions Utility Functions def add_element(ary, val)  ary.dup.push(val)enddef remove_element_index(ary, idx)  idx == 0 ? ary[1..-1] :  (idx == (ary.size - 1)) ? ary[1..-2] :  ary.slice(0, idx - 1).concat(ary.slice(idx + 1, ary.size - 1))enddef find_smallest_value_index(ary)  smallest_idx = 0  ary.each_index do |idx|  if ary[idx] < ary[smallest_idx]  smallest_idx = idx  smallest_val = ary[idx]  end  end  return smallest_idxend
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) In this basic example, it looks like the standard loop is better.  But as the loop gets more complicated, knowing exactly what defines your variables makes all the difference between an understandable and a totally incoherent loop.
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Definition with Parameter Declaration Note that the recursive loop explicitly names its inputs, while the standard loop does not, meaning that to truly know what contributes to the standard loops functionality requires full inspection of the whole loop. Loop Definition
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Initialization Loop Initialization
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Invocation An explicit invocation step is not needed for standard loops, as the while statement invokes it implicitly.
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Condition Loop Condition
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Body Loop Body
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Modification of Loop Variables Modification of Loop Variables Note that in the standard loop assignments can occur anywhere, while in recursive loops they only occur by passing new parameters as part of the loop iteration process.  Which do you think leads to easier bug detection in large loops? Recursive loops can create new definitions for new variables within the loop, but cannot modify already-assigned variables.
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Control Variable Modification Control Variable Modification Note that since this is done as a function parameter, no assignment needs to be made.  The new value is placed into a new variable (with the same name) in the next function call.
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Iteration Loop Iteration Not e that since the loop is represented as a function, to get back to the beginning of the loop, all we need to do is a function call.  But remember that unless the function call is the last thing you do, the function will return back to the loop!
Basic Recursive Loop A standard loop:   i = 0   while(i < 10) {   #Do Stuff   i = i + 1   } A recursive loop:   def myloop(i, other, changeable, loop, vars)   if i < 10   #Do Stuff   return myloop(i + 1, other, changeable, loop, vars)   else   return whatever  #exit loop   end   end   myloop(0, other, changeable, initial, values) Loop Exit Note that the loop exit is explicit in the standard loop but implicit in the recursive loop.
Packaged Looping Constructs These put all of the loop control in a function, and thus out of your hands In these, the loop logic is guaranteed reliable, and you are only responsible for the per-iteration logic These take a block (or in other languages, a function or lambda expression) which is the per-iteration code This usually (but not always) do not carry state from iteration to iteration Should I give an example somewhere?
Packaged Looping Constructs map  - takes a list, and for each list member, runs a transformation and returns a new element: [1, 2, 3, 4, 5].map{|x| x * x}  =>  [1, 4, 9, 16, 25] each  - takes a list, and for each list member, performs an action: [1, 2, 3, 4, 5].each{|x| puts “The value is #{x}”} select  - filters a list and returns only members for whome the condition is true [1, 2, 3, 4, 5].select{|x| x.remainder(2) == 1}  =>  [1,3,5] Include upto? Somewhere I need to talk about fold and unfold, but that is probably for a different talk.
Functional Looping Advantages For nearly all common cases, packaged looping works best.  It is easy to do and easy to get right. For more exceptional cases, recursive looping principles offer more structure and more guarantees about your loop state: Explicit input parameters Single assignment of all variables Disadvantages: a little more typing, a lot less familiarity Note that these are the same ones we talked about for FP in general.  Also, in general this makes the programs easier to reason about.
General Functional Programming Issues Input/output difficult to deal with Requires garbage collection Produces more garbage to collect Sometimes slower (but usually not by much) Some operations are intrinsically stateful - there may be a functional way of doing it but they are cumbersome Mention Monads briefly Do I need to talk about stateful/stateless somewhere?
Practical Tips Use a language (like Ruby!) with plenty of support for functional programming constructs, but that doesn’t force them Use packaged loops for iteration whenever you can For complicated loops, strongly consider recursive versions As much as you can, try to create new variables instead of assigning to existing ones You will likely need to modify state at some point, but try to keep it out of as many functions as possible On state modification - might mention how ruby uses ! to mark non-functional versions of traditionally functional functions. When a task requires both computation and state modification, it is often best to separate them into two functions - one to perform the computation and one to actually perform the state change (usually with the state-change function calling the computational function, but not always).
References Mastering Recursive Programming http://www-128.ibm.com/developerworks/linux/library/l-recurs.html Introduction to Haskell (includes recursive techniques) http://www-128.ibm.com/developerworks/edu/os-dw-linuxhask-i.html Recursion Examples http://www.juniata.edu/faculty/kruse/cs2java/recursion2.htm More Recursion Examples http://www.sparknotes.com/cs/recursion/examples/
Ad

More Related Content

What's hot (20)

Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
WebF
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Clojure basics
Clojure basicsClojure basics
Clojure basics
Knoldus Inc.
 
Functional programming
Functional programmingFunctional programming
Functional programming
Christian Hujer
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
Damian Jureczko
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Lazy java
Lazy javaLazy java
Lazy java
Mario Fusco
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
Joseph Smith
 
Python functions
Python functionsPython functions
Python functions
Aliyamanasa
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
Andreas Pauley
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
WebF
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
Knoldus Inc.
 
Learning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a NeckbeardLearning Functional Programming Without Growing a Neckbeard
Learning Functional Programming Without Growing a Neckbeard
Kelsey Gilmore-Innis
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 
Introduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScriptIntroduction to Functional Programming in JavaScript
Introduction to Functional Programming in JavaScript
tmont
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
Damian Jureczko
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
Reuven Lerner
 
Functional programming in JavaScript
Functional programming in JavaScriptFunctional programming in JavaScript
Functional programming in JavaScript
Joseph Smith
 
Python functions
Python functionsPython functions
Python functions
Aliyamanasa
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
Andreas Pauley
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
Megha V
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 

Viewers also liked (20)

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Andreas Pauley
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Functional programming for optimization problems in Big Data
Functional programming for optimization problems in Big DataFunctional programming for optimization problems in Big Data
Functional programming for optimization problems in Big Data
Paco Nathan
 
Functional Programming Principles & Patterns
Functional Programming Principles & PatternsFunctional Programming Principles & Patterns
Functional Programming Principles & Patterns
zupzup.org
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
Wen-Tien Chang
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)
Alex Bunardzic
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculus
Edward Blurock
 
Functional programming
Functional programmingFunctional programming
Functional programming
edusmildo
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prateek Jain
 
Describe professional programing languages and talks
Describe professional programing languages and talks Describe professional programing languages and talks
Describe professional programing languages and talks
Ed Bray
 
Introduction of Functional Programming
Introduction of Functional ProgrammingIntroduction of Functional Programming
Introduction of Functional Programming
☁️ Mikhail Shilkov
 
Uses of Cupcakes For Any Occasion in Hyderabad!
 Uses of Cupcakes For Any Occasion in Hyderabad! Uses of Cupcakes For Any Occasion in Hyderabad!
Uses of Cupcakes For Any Occasion in Hyderabad!
bookthecake.com
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 
Core FP Concepts
Core FP ConceptsCore FP Concepts
Core FP Concepts
Diego Pacheco
 
Programming Languages
Programming LanguagesProgramming Languages
Programming Languages
Edward Blurock
 
Oop project briefing sem 1 2015 2016
Oop project briefing  sem 1 2015 2016Oop project briefing  sem 1 2015 2016
Oop project briefing sem 1 2015 2016
IIUM
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languages
py7rjs
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Andreas Pauley
 
Functional Programming Fundamentals
Functional Programming FundamentalsFunctional Programming Fundamentals
Functional Programming Fundamentals
Shahriar Hyder
 
Functional programming for optimization problems in Big Data
Functional programming for optimization problems in Big DataFunctional programming for optimization problems in Big Data
Functional programming for optimization problems in Big Data
Paco Nathan
 
Functional Programming Principles & Patterns
Functional Programming Principles & PatternsFunctional Programming Principles & Patterns
Functional Programming Principles & Patterns
zupzup.org
 
那些 Functional Programming 教我的事
那些 Functional Programming 教我的事那些 Functional Programming 教我的事
那些 Functional Programming 教我的事
Wen-Tien Chang
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
Scott Wlaschin
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
Scott Wlaschin
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
pramode_ce
 
From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)From Imperative to Functional Programming (for Absolute Beginners)
From Imperative to Functional Programming (for Absolute Beginners)
Alex Bunardzic
 
Computability, turing machines and lambda calculus
Computability, turing machines and lambda calculusComputability, turing machines and lambda calculus
Computability, turing machines and lambda calculus
Edward Blurock
 
Functional programming
Functional programmingFunctional programming
Functional programming
edusmildo
 
Functional programming
Functional programmingFunctional programming
Functional programming
Prateek Jain
 
Describe professional programing languages and talks
Describe professional programing languages and talks Describe professional programing languages and talks
Describe professional programing languages and talks
Ed Bray
 
Introduction of Functional Programming
Introduction of Functional ProgrammingIntroduction of Functional Programming
Introduction of Functional Programming
☁️ Mikhail Shilkov
 
Uses of Cupcakes For Any Occasion in Hyderabad!
 Uses of Cupcakes For Any Occasion in Hyderabad! Uses of Cupcakes For Any Occasion in Hyderabad!
Uses of Cupcakes For Any Occasion in Hyderabad!
bookthecake.com
 
Csc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigmCsc1100 lecture01 ch01 pt2-paradigm
Csc1100 lecture01 ch01 pt2-paradigm
IIUM
 
Oop project briefing sem 1 2015 2016
Oop project briefing  sem 1 2015 2016Oop project briefing  sem 1 2015 2016
Oop project briefing sem 1 2015 2016
IIUM
 
Generations Of Programming Languages
Generations Of Programming LanguagesGenerations Of Programming Languages
Generations Of Programming Languages
py7rjs
 
Ad

Similar to Introduction To Functional Programming (20)

Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2Introduction to Python Prog. - Lecture 2
Introduction to Python Prog. - Lecture 2
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
Carlo Fanara
 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.pptPPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.pptppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
Mahmoud Samir Fayed
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Bruno Lui
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
Geison Goes
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
Acácio Oliveira
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Notes5
Notes5Notes5
Notes5
hccit
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181
Mahmoud Samir Fayed
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptxJNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
AnirudhaGaikwad4
 
Notes2
Notes2Notes2
Notes2
hccit
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )Introduction to python programming ( part-2 )
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.pptPPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.pptppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
Mahmoud Samir Fayed
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Bruno Lui
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
Geison Goes
 
Pythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptxPythonlearn-04-Functions (1).pptx
Pythonlearn-04-Functions (1).pptx
leavatin
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Notes5
Notes5Notes5
Notes5
hccit
 
The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181The Ring programming language version 1.5.2 book - Part 31 of 181
The Ring programming language version 1.5.2 book - Part 31 of 181
Mahmoud Samir Fayed
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
Notes2
Notes2Notes2
Notes2
hccit
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Ad

Recently uploaded (20)

TrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI PaymentsTrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI Payments
Trs Labs
 
5kW Solar System in India – Cost, Benefits & Subsidy 2025
5kW Solar System in India – Cost, Benefits & Subsidy 20255kW Solar System in India – Cost, Benefits & Subsidy 2025
5kW Solar System in India – Cost, Benefits & Subsidy 2025
Ksquare Energy Pvt. Ltd.
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Hundred applicable AI Cases for oil and Gas
Hundred applicable AI Cases for oil and GasHundred applicable AI Cases for oil and Gas
Hundred applicable AI Cases for oil and Gas
bengsoon3
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
TrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI PaymentsTrsLabs - Leverage the Power of UPI Payments
TrsLabs - Leverage the Power of UPI Payments
Trs Labs
 
5kW Solar System in India – Cost, Benefits & Subsidy 2025
5kW Solar System in India – Cost, Benefits & Subsidy 20255kW Solar System in India – Cost, Benefits & Subsidy 2025
5kW Solar System in India – Cost, Benefits & Subsidy 2025
Ksquare Energy Pvt. Ltd.
 
UiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer OpportunitiesUiPath Agentic Automation: Community Developer Opportunities
UiPath Agentic Automation: Community Developer Opportunities
DianaGray10
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Hundred applicable AI Cases for oil and Gas
Hundred applicable AI Cases for oil and GasHundred applicable AI Cases for oil and Gas
Hundred applicable AI Cases for oil and Gas
bengsoon3
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 

Introduction To Functional Programming

  • 1. Intro to Functional Programming Part 1: Single-assignment and Recursive Techniques
  • 2. What is Functional Programming? Functions return values Given a set of values in the parameter list, the function can only have one possible result. Functions have no side-effects Do not modify variables passed to them Do not modify any global variable Variables only assigned once
  • 3. What’s the Point? Principle of Least Surprise Principle of Least Surprise All possible inputs to any function are listed in the parameter list - no worries about global state Single assignment means that you never have to wonder how a variable got its definition since it is only defined one place in the entire function Loops much easier to comprehend and debug Simpler execution model makes program proving easier, both for computers and humans (i.e. debugging) Explicitly mention stateless. Might also talk about theoretical statelessness of the web, but also why it isn’t truly stateless.
  • 4. No assignments! How do you loop? Functional programs are usually heavily recursive Looping is either done with a looping construct (such as map , each , select , etc.) or with recursion Rather than setting values on each iteration, the loop itself is a function that calls itself recursively Each iteration the function simply gets called with new values Need to mention that although you _can_ do recursive algorithms and modify state, that is usually the worst of both worlds.
  • 5. Recursion Basics Before we talk about looping with recursion, let’s talk about recursion itself Recursion is where a function calls itself In recursion the goal is to get the data to a smaller version to solve, until it is to a point where the solution is a simple operation -- this is called the base case If your recursive function does not have a base case, it will never return . That’s usually considered bad.
  • 6. Recursion Example: The Factorial Function The Factorial Function The factorial function multiplies a number by each number below it until 1 5! (! means factorial) is the same as 5 * 4 * 3 * 2 * 1 Here’s the factorial function in ruby: def factorial(number) if number == 1 #Base Case -- compute answer return 1 else #Get us closer to the base case return number * factorial(number - 1) endend Note that we didn’t do ANY assignment in the whole program -- we just passed parameters. Function calls create new variables, so if we think we want to do assignment, in functional programming you usually want to call a function or create a different variable.
  • 7. Selection Sort Example Two lists: already-sorted values and unsorted values First list will start empty Each iteration, find the smallest unsorted value and put it at the end of the sorted list Base case: unsorted values list is empty - just return the sorted values
  • 8. Selection Sort Example def select_sort(values) select_sort_loop([], values)enddef select_sort_loop(sorted_values, unsorted_values) if unsorted_values.empty? #BASE CASE! return sorted_values else #FIND SMALLEST VALUE AND ITS INDEX smallest_value_index = find_smallest_value_index(unsorted_values) smallest_value = unsorted_values[smallest_value_index] #CREATE NEW SORTED AND UNSORTED ARRAYS new_sorted_values = add_element(sorted_values, smallest_value) new_unsorted_values = remove_element_index(unsorted_values, smallest_value_index) #LOOP WITH NEW VALUES return select_sort_loop(new_sorted_values, new_unsorted_values) endend select_sort([1,5,23,8,3,5,6,8,34,65,2,5,3])
  • 9. Selection Sort: Utility Functions Utility Functions def add_element(ary, val) ary.dup.push(val)enddef remove_element_index(ary, idx) idx == 0 ? ary[1..-1] : (idx == (ary.size - 1)) ? ary[1..-2] : ary.slice(0, idx - 1).concat(ary.slice(idx + 1, ary.size - 1))enddef find_smallest_value_index(ary) smallest_idx = 0 ary.each_index do |idx| if ary[idx] < ary[smallest_idx] smallest_idx = idx smallest_val = ary[idx] end end return smallest_idxend
  • 10. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) In this basic example, it looks like the standard loop is better. But as the loop gets more complicated, knowing exactly what defines your variables makes all the difference between an understandable and a totally incoherent loop.
  • 11. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Definition with Parameter Declaration Note that the recursive loop explicitly names its inputs, while the standard loop does not, meaning that to truly know what contributes to the standard loops functionality requires full inspection of the whole loop. Loop Definition
  • 12. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Initialization Loop Initialization
  • 13. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Invocation An explicit invocation step is not needed for standard loops, as the while statement invokes it implicitly.
  • 14. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Condition Loop Condition
  • 15. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Body Loop Body
  • 16. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Modification of Loop Variables Modification of Loop Variables Note that in the standard loop assignments can occur anywhere, while in recursive loops they only occur by passing new parameters as part of the loop iteration process. Which do you think leads to easier bug detection in large loops? Recursive loops can create new definitions for new variables within the loop, but cannot modify already-assigned variables.
  • 17. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Control Variable Modification Control Variable Modification Note that since this is done as a function parameter, no assignment needs to be made. The new value is placed into a new variable (with the same name) in the next function call.
  • 18. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Iteration Loop Iteration Not e that since the loop is represented as a function, to get back to the beginning of the loop, all we need to do is a function call. But remember that unless the function call is the last thing you do, the function will return back to the loop!
  • 19. Basic Recursive Loop A standard loop: i = 0 while(i < 10) { #Do Stuff i = i + 1 } A recursive loop: def myloop(i, other, changeable, loop, vars) if i < 10 #Do Stuff return myloop(i + 1, other, changeable, loop, vars) else return whatever #exit loop end end myloop(0, other, changeable, initial, values) Loop Exit Note that the loop exit is explicit in the standard loop but implicit in the recursive loop.
  • 20. Packaged Looping Constructs These put all of the loop control in a function, and thus out of your hands In these, the loop logic is guaranteed reliable, and you are only responsible for the per-iteration logic These take a block (or in other languages, a function or lambda expression) which is the per-iteration code This usually (but not always) do not carry state from iteration to iteration Should I give an example somewhere?
  • 21. Packaged Looping Constructs map - takes a list, and for each list member, runs a transformation and returns a new element: [1, 2, 3, 4, 5].map{|x| x * x} => [1, 4, 9, 16, 25] each - takes a list, and for each list member, performs an action: [1, 2, 3, 4, 5].each{|x| puts “The value is #{x}”} select - filters a list and returns only members for whome the condition is true [1, 2, 3, 4, 5].select{|x| x.remainder(2) == 1} => [1,3,5] Include upto? Somewhere I need to talk about fold and unfold, but that is probably for a different talk.
  • 22. Functional Looping Advantages For nearly all common cases, packaged looping works best. It is easy to do and easy to get right. For more exceptional cases, recursive looping principles offer more structure and more guarantees about your loop state: Explicit input parameters Single assignment of all variables Disadvantages: a little more typing, a lot less familiarity Note that these are the same ones we talked about for FP in general. Also, in general this makes the programs easier to reason about.
  • 23. General Functional Programming Issues Input/output difficult to deal with Requires garbage collection Produces more garbage to collect Sometimes slower (but usually not by much) Some operations are intrinsically stateful - there may be a functional way of doing it but they are cumbersome Mention Monads briefly Do I need to talk about stateful/stateless somewhere?
  • 24. Practical Tips Use a language (like Ruby!) with plenty of support for functional programming constructs, but that doesn’t force them Use packaged loops for iteration whenever you can For complicated loops, strongly consider recursive versions As much as you can, try to create new variables instead of assigning to existing ones You will likely need to modify state at some point, but try to keep it out of as many functions as possible On state modification - might mention how ruby uses ! to mark non-functional versions of traditionally functional functions. When a task requires both computation and state modification, it is often best to separate them into two functions - one to perform the computation and one to actually perform the state change (usually with the state-change function calling the computational function, but not always).
  • 25. References Mastering Recursive Programming http://www-128.ibm.com/developerworks/linux/library/l-recurs.html Introduction to Haskell (includes recursive techniques) http://www-128.ibm.com/developerworks/edu/os-dw-linuxhask-i.html Recursion Examples http://www.juniata.edu/faculty/kruse/cs2java/recursion2.htm More Recursion Examples http://www.sparknotes.com/cs/recursion/examples/