Currying in “newLisp”

Written by on November 14, 2021 in newLisp, Programming with 0 Comments

In the last two articles, I discussed what I believe are some interesting features of “newLisp”. Today’s topic is “currying”, another useful feature.

For those of you who are new to this topic, I had earlier written about “currying” in Mathematica here. You may want to take a look at that too.

Unlike, for example, Haskell, “currying” is not supported by default in “newLisp”. Instead, there is a function called “curry” that must be explicitly called to get the required behavior.

Simply put, the function “curry” transforms a 2-argument function to a single argument function by bundling in the first (left most) argument. Further, it does not evaluate its arguments.

Let us look at an example:

Example of Currying

Example of Currying

We first define a function called “bar” that takes two arguments and subtracts the second from the first as its computation.

We then “curry” this function to get a new function, by passing “10” as the fixed first argument. The returned function object is stored in the variable “bar2”.

When we call “bar2” by passing 4, we get 6 as expected. This is exactly the same as calling “bar” with arguments 10 and 4.

Here are some more usage patterns:

More Examples

More Examples

As you can see, “currying” simplifies certain function calls and makes the code more readable.

If you look at the “lambda” returned from “curry”, you can see that it names its single in-coming argument as “$x”. We can therefore use this name in our bundled argument expression!

Using "$x" in Curry

Using “$x” in Curry

Please remember that “curry” does not evaluate its arguments. So watch out for situations like this:

Curry Argument Not Evaluated

Curry Argument Not Evaluated

In the above example, if we use “letex” instead of “let”, then this is what we get:

"letex" Expands Statically

“letex” Substitutes Argument

Notice that in this case, “letex” has substituted the “x” inside “curry” with its initial value.

I think the discussion so far adequately covers the different use cases of “curry”. The fact that “currying” is not supported by default in “newLisp” or that it is limited to 2-argument functions could a limitation, but I feel it is useful even as it is.

Have a great weekend!

Tags: ,


If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published. Required fields are marked *