Jumping around between multiple languages can help you notice some differences between idioms and best practices in different languages. One of the more interesting differences has to do with one function doing multiple things. Continue Reading
default parameters
All posts tagged default parameters
Recently, I posted about how you can use composition instead of inheritance, and in that article, I mentioned the Delegate Pattern. As a quick description, the pattern has you inherit from the parent interface (or, in Python, you can just implement the protocol), but all the methods either redirect to calling the method on an injected implementation of interface/protocol, possibly surrounding the call in its own code, or it completely fills the method with its own implementation.
For the most part, it is like manually implementing inheritance, except that the superclass in injectable.
Anyway, one of the more annoying parts of implementing the Delegate Pattern is having to write all of the delegated calls. So I decided to look into the possibility of of making a decorator that will do that for you for all the methods you don’t explicitly implement. Continue Reading
Last week, I talked about currying a little bit, and I’ve been thinking about how one could do in languages that don’t have it built in. It can be done in Java, but the type of even a two-parameter function would be something like Function<Integer, Function<Integer, Integer>>
, which is bad enough. Imagine 3- or 4-parameter functions.
There’s also the fact that calling curried functions doesn’t look good. Calling the two-parameter function with both parameters would look something like func.apply(1).apply(2)
. This isn’t what we want. At worst, we want to be stuck with func(1)(2)
, but that’s not possible in Java. At best, we want to be able to choose func(1)(2)
(calling it with the first argument at one point in time and using the second one later) OR func(1, 2)
, depending on our current need. It’s possible to do so in python, so I’m using that. Continue Reading
Functional programming encourages the use of recursive functions in order to tackle bigger problems, allowing you to avoid mutable state and express the problem as small problems. One of the most popular example of recursive functions is the factorial function, which can be written in python as follows:
def factorial(num):
"""
num must be an integer greater than 0
"""
if num == 1:
return num
else:
return num * factorial(num - 1)
That’s the old-school approach to recursive functions and an effective enough function for typical usage. But the biggest problem with typical old-school recursive functions is the stack buildup. If the input is too large, a recursive function will cause a stack overflow. Continue Reading