@@ -4,7 +4,7 @@ title: "An Introduction to Functional Programming with Python - Part 1"
44categories : functional python tutorial
55tags : blog
66author : Alex
7- comments : false
7+ comments : true
88---
99
1010This is the first part of a tutorial series meant to introduce the functional programming paradigm
@@ -22,41 +22,40 @@ If you have completed Vince's [Computing for Maths][cfm] class then you will hav
2222programming language but using the [ imperative] [ imperative-wiki ] and [ object oriented] [ oop-wiki ] paradaigms.
2323
2424Ok that's the fancy stuff out of the way, in plain English this means that you tell the computer what
25- to do step-by-step for example consider the following bit of Python
25+ to do step-by-step for example consider the following bit of Python:
2626
2727{% highlight py3 %}
2828
2929def calc_average(nums):
3030 """
3131 This function calculates the average of a list of numbers, it assumes the
32- list conatins only numbers and is non-empty
32+ list conatins only numbers and is non-empty
3333
3434 Arguments:
3535 - nums: A list of numbers
3636
3737 Outputs:
38- - The average, a floating point number
38+ - The average, a floating point number
3939 """
4040
4141 sum = 0
4242
4343 for n in nums:
4444 sum += n
4545
46- return sum/float( len(nums) )
46+ return sum/len(nums)
4747{% endhighlight %}
4848
4949Here we have to tell Python exactly what it needs to do verbaitum
5050
5151 1. Create a variable called sum, assign it the value zero.
52- 2. Go through each item in the list in turn and add it's value to the variable sum
53- 3. Divide that by the number of items there were in the list - oh! and
54- don't forget to cast to a float
52+ 2. Go through each item in the list in turn and add it's value to the variable sum.
53+ 3. Divide that by the number of items there were in the list.
5554
5655Whereas the functional paradigm is part of a family of [ declarative programming] [ declarative-wiki ]
5756paradgims, where instead of detailing all the steps you simply 'declare' what something is or how to
5857transform it into another form. In the case of [ functional programming] [ functional-wiki ] this is done
59- (suprisingly) using functions , for example we can rewrite the above as the following.
58+ (suprisingly) using functions, for example we can rewrite the above as the following.
6059
6160{% highlight py3 %}
6261
@@ -68,7 +67,7 @@ def f_average(nums):
6867 """
6968 sum = reduce(lambda x, y: x + y, nums, 0)
7069
71- return list(sum/float( len(nums) ))
70+ return list(sum/len(nums))
7271{% endhighlight %}
7372
7473> Python 2.7.x Differences
@@ -94,8 +93,8 @@ def f(x):
9493def g(x):
9594 if isTuesday():
9695 return x + 1
97- else:
98- return x
96+ else:
97+ return x
9998{% endhighlight %}
10099
101100The function ``` g ``` is the impure function since it depends on the state of the system it is run on.
0 commit comments