18 ms·
Before I start, let me say that I'm on mobile and I don't know how to post code on this site. I'm assuming backticks work. --- One benefit is that functions a
by agent281 4y ago
Before I start, let me say that I'm on mobile and I don't know how to post code on this site. I'm assuming backticks work.
---
One benefit is that functions are more reusable. Functions with more arguments can be partially applied and used where applicable.
For instance, if you wanted to increment the values in a list you might do something like this in python:
map(lambda x: x + 1, [1,2,3])
But in an ML like language you can do something like:
map((+ 1), [1,2,3])
Because plus is actually a function that takes two arguments and can be curried down to one argument.
Additionally, you can think of currying as a form of dependency injection.
For example, if you wanted to inject a database client and a logger before running a query you might do something like this:
def queryer(db, logger):
def _q(query):
logger.info("before query")
results = db.fetch(query)
logger.info("after query")
return results
return _q
rows = queryer(db, logger)(query)
You could write it a bit more simply in this hypothetical ML like language:
queryer db logger query =
logger.info("before query")
results = db.fetch(query)
logger.info("after query")
results
MLs don't require parens/commas for function calls, but you can use parens to force a particular execution order. The lines below have the same result, but some produce and execute intermediate curried functions
rows = queryer db logger query
rows = (queryer db) logger query
rows = ((queryer db) logger) query
It's a bit contrived, but you have the flexibility to provide some arguments based on the call site rather than the definition site. I.e., the first example was broken up into 2 function calls at the definition site, but the second example could have 1, 2, or 3 function calls.
---
I hope this makes sense and I wish I could preview my comment to see if it was formatted reasonably!