Sunday 28 November 2021

Yield based Trampolines

Some weeks ago I came across this article about using trampoline functions with generators to avoid stack overflows in recursive functions. I've recently written about "classic" trampolines for non tail recursions and about an alternative, using await, so I decided to transport the technique explained in that article to a javascript example.

Let's see first an example of adapting a Tail recursive function to be used with a trampoline function to prevent stack overflows in a runtime lacking of TCO (like node.js). We have a recursive factorial like this:


function recursiveFactorial(n, accumulator) {
    if (n <= 0) return accumulator;

    return recursiveFactorial(n-1, n*accumulator);
}

And we transform it into this:


function trampolineReadyFactorial(n, accumulator){
    if (n <= 0) return accumulator;

    return () => recursiveFactorial(n-1, n*accumulator);
}

To use it with a trampoline that we create with a factory:


function createTrampoline(fn){
    return (...args) => {
        let result = fn(...args);

        while (typeof result === "function")
            result = result();
        return result;
    };
}

let factorialTrampoline = createTrampoline(trampolineReadyFactorial);
console.log("factorialTrampoline: " + factorialTrampoline(50, 1));

Now let's do it differently, let's rewrite the "trampoline enabled" recursive function, using generators as explained in that python article.


//there's no recursion cause invoking the generator function returns a generator object, and the code
//inside the generator function is not executed until we call next() on the returned generator object (iterable/iterator)
function* yieldBasedFactorial(n, accumulator){
    if (n <= 0) 
        yield accumulator;
    else
        yield yieldBasedFactorial(n-1, n*accumulator);
}

So now the "trampoline enabled" function no longer returns a function (containing the "recursive" call), but a generator object (iterable-iterator). Calling next() on that generator object will perform the next "recursive" call). We can create a trampoline for this kind of "trampoline enabled" functions, like this:


function createTrampolineFromYieldBasedFn(yieldBasedFn){
    return (...args) => {
        let genObj = yieldBasedFn(...args);
        let item = genObj.next();
        while (item.value.next !== undefined )
            item = item.value.next();
        return item.value;
    }
}

let yieldBasedFactorialTrampoline = createTrampolineFromYieldBasedFn(yieldBasedFactorial);
let result = yieldBasedFactorialTrampoline(50, 1);
console.log("yield based Trampoline 2: " + result);

The trampoline function looks more complex to me in this case, but one could say that the adapted, recursive-like function, seems more close to the original with that yield. As usual, I've uploaded the code to a gist

Sunday 21 November 2021

Infinite Sequence and More

It's good that I still find interest in bizarre programming topics :-) I recently came across an article about recursive iterators in javascript. What mainly called my attention was the recursive way to create and endless iterator. The "classical", iterative way is something along these lines:


function* infiniteIterable(iter){
    while (true){
        yield* iter;
    }
} 

The recursive way (I managed to write it myself without looking it on the article, to make sure I understood it) is this:


function* infiniteIterableViaRecursion(iter){
    yield* iter;
    yield* infiniteIterableViaRecursion(iter);
} 

Somehow I also came across this other post with an odd title Eliminate try..catch when using async/await by chaining .catch() clauses. What!? Avoiding the "Promise Hell" of a mass of chained then-catch calls and writing it as sequential code is why we all love async-await, so this seemed senseless. Well, looking into the article he refers to a case for which it makes good sense, when the async call returns a value and even in case of an exception we still want to return a (sort of default) value. So rather than this:


let value;
try {
  value = await db.get('nonexistent'); // throws NotFoundError
} catch {
  value = null;
}

We write this, that is quite more concise:


const value = await db.get('nonexistent').catch(() => null);

Sunday 14 November 2021

LongChamp Marseille

Recently I've been lucky to spend (again) a few days in Marseille. I find this city mesmerizing, in spite of its massive problems: Le Grand Remplacement (it's not a theory, it's a painful reality in at least 1/2 of the city, where non-muslims have become a clear minority), the huge presence of far-left scum and the islamization and criminality that comes along with both previous issues... Marseille is placed in a privileged natural setting, encircled by mountains and the sea, and with a 150 meters high hill right at its center, from where the magical Notre-Dame de la Garde dominates the whole city. Additionally, I absolutely love its urban landscape, a dense city where the old and the new embrace each other and where high-rise constructions spring up unorderly here and there.

I thought I had already written about Marseille after my initial discovery of this impressive city, but I've just realised that unfortunately I never finished a rather long article that I was writing in August 2014!. All I've published about Marseille is this short post. It's strange that I did not mention in it the incredible place that I'm going to describe now, LongChamps.

LongChamp is a park, a garden and gorgeous palace Palais Longchamp, with a beautiful, imposing and delicate fountain (Chateau d'eau). It's the kind of classic French refinement that maybe you would not expect to find in Marseille, though the city has some other excellent examples of magnificent "so French" architecture, e.g. the Prefecture, the Banque de France and the Caisse d'Epargne buildings (the 3 of them really close). Indeed, my first time there, in 2014, I was almost shocked. After that, it was under renovation for like almost 2 years, and now it looks even better. This renovation included improvements to the lightning of the monument, which reminds me that I have pending to go there one day at night. The main sculpture and the cascade are one of those exquisite pieces of art that make you think about what their creators could feel the day it was complete, to what extend they were aware of the beauty they were gifting us with.

From the wikipedia article I've learnt that the achievement that it celebrates, the construction of the Canal de Marseille is still relevant these days, as it still provides 2/3's of its drinking water to Marseille. This is in contrast with another of the great French construction works of all times, the Canal du Midi, that remains an essential source of visual joy for most Toulousains, but no longer has much practical use.

I've come to profoundly hate French rap, save for some Patriotic acts like Tepa (Repose en Paix, combatant) or Millesime K. but well, there is a clip by Soprano with some nice views of LongChamp (you can just mute the sound).

Monday 1 November 2021

DbContext Creation

There are several ways to create a DBContext in (modern) .Net and they are explained here. There 2 of them that I normally use. This one, when I'm not using any IoC container:


var connectionstring = "Data Source=blogging.db";

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite(connectionstring);
optionsBuilder.UseLazyLoadingProxies();

BloggingContext dbContext = new BloggingContext(optionsBuilder.Options);

The above is pretty clear. We set several options through a builder object, build the options object and pass it over to the DBContext constructor, so that we get a DBContext fully set with all its options. This is much better than if we wereconstructing the object and then setting options on it, that would allow having a partially initialized (and useless) object.

This other mechanism is used when using the built-in IoC container provided by the .Net Base Class Library:


var connectionstring = "Data Source=blogging.db";
ServiceCollection services = new ServiceCollection();
services.AddDbContextFactory<BloggingContext>( optionsBuilder => {
	optionsBuilder.UseSqlite(connectionstring);
	optionsBuilder.UseLazyLoadingProxies();
});

var provider = services.BuildServiceProvider();

BloggingContext dbContext = provider.GetService<BloggingContext>();


Usually I just copy/paste it from some article or from a previous project and don't pay it much more attention, but it has always seemed a bit odd to me, so I've been reflecting a bit on it. We register in the IoC container our DbContext, providing a callback function that configures the DbContextOptionsBuilder and will be invoked when the Container instanciates the DbContext. This callback is not a factory, as it does not create the DbContext, it helps to configure it. This technique is possible becaue the built-in container has "extra knowledge" about DbContexts. I could think of 2 different ways to create the DbContext through the container that look a bit more natural to me.

1. Almost any IoC container allows registering parameters to pass to a constructor. For example in Autofac we can register constant values or register a factory function that is invoked by the container to create the non constant parameter each time it needs to provide the service. We would need that for our case with the DbContextOptions. I think the built-in .Net container does not support this.

2. Registering a Factory that creates a new DbContext each time the IoC container needs one. Indeed we can do that with the built-in container:


            var connectionstring = "Data Source=blogging.db";
            ServiceCollection services = new ServiceCollection();
            
            services.AddTransient<BloggingContext>(s => {
                var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
                optionsBuilder.UseSqlite(connectionstring);
                optionsBuilder.UseLazyLoadingProxies();
                return new BloggingContext(optionsBuilder.Options);
            });
            var provider = services.BuildServiceProvider();
            return provider.GetService<BloggingContext>();

I think this seems more natural to me as it's a generic technique that I'm more accustomed to use with other containers and for different object types, but it's slightly more verbose than the specific technique featured by the built-in container.