Hey rahmu, great article! Here are some thoughts:
rahmu wrote
def square_of_even_elements(sequence):
"""returns a new sequence consisting of the odd elements in the
original one, elevated to the square.
"""
new_sequence = []
for element in sequence:
if element % 2 == 0: # if element is odd
new_sequence.append(element**2)
return new_sequence
This function does what it says in its docstring, namely pick every odd element in the original sequence and elevate it to the square.
No it doesn't! The docstring is out of date! :D
rahmu wroteIt will then create a listcomp by applying the function "key" to each element of sequence and return the values sorted numerically.
You might want to explain that the contract for the sort() function now expects the key() function to return a numerical value, because internally it uses sort_numerically(). In Haskell-talk,
key is a function with type
a -> Int. Actually, I'm not sure if a beginner would care very much about that.
I like how you introduced map, filter, and accumulate. For the record I like the word accumulate better than fold or reduce, and it's really good that you explained the difference between a right and left fold.
I think another powerful idea when you have higher-order functions is function composition. In Haskell, the composition operator is a function that's defined like this:
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \x -> f (g x)
So given a function
f that takes a
b to a
c, and
g that takes an
a to a
b the composition of
f and
g is the function that takes an
x, applies
g to
x, and then applies
f to the result.
So now you can compose multiple functions to create new functions, here's a function that adds 1 to a number and then squares the result, it uses
succ to increment the number, and
square to do the squaring:
addOneAndSquare = square . succ
addOneAndSquare 1
>>> 4
How do you express this in Python or Lua? I think it might be built-in.
I felt your article was a great introduction, it doesn't scare away beginners and it gives enough code that someone can experiment with their own higher-order functions. Good job, and keep writing cool stuff!