In: Advanced Math
Haskell
Map and Filter
6. Let f1 = filter (\ x -> x > 0) and f2 = filter (\x -> x < 10), and let nbrFilter g x = length (filter g x).
a. Rewrite f1(f2[-5..15]) so that it uses function composition to apply just one function to the list.
b. Rewrite the nbrFilter function definition to have the form
nbrFilter g = function composition involving length and filter … and leaving out x.
Given Functions:
f1(x): This filter will pass the values which are more than 0,
f2(x): This filter will pass the values which are less than 10, and
nbrFilter g = function composition involving length and filter both.
So nbrFilter g(x) = length(filter(x)), where filter can be f1 or f2 or any other.
Part - a)
So to apply this function composition : f1(f2[-5..15]), we can make a function(say f3) having both conditions:
f3(x) = filter(\x -> x > 0 and \x -> x < 10).
Let's do the python implementation:
for f1(x), we have:
def f1(x):
z = []
for y in x:
if(y>0):
z.append(y)
return z
and for f2(x), we have:
def f2(x):
z = []
for y in x:
if(y<10):
z.append(y)
return z
and finally below is the python implementation of the composition function(f3):
def f1(x):
z = []
for y in x:
if(y<10 and y>0):
z.append(y)
return z
Part - b)
Since it is given: nbrFilter g(x) = length(filter(x)), where filter can be f1 or f2 or any other.
lets assume, we are using f3 filter here.
So, nbrFilter g(x) = length(filter(\x -> x > 0 and \x -> x < 10))
Below is the python implementation of nbrFilter g(x):
def f1(x):
z = []
for y in x:
if(y<10 and y>0):
z.append(y)
return len(z)