An FP pattern. What is it? Is it a Thrush?

I feel I’ve possibly stumbled on an FP pattern. I wish to understand what its name and field of applicability are.

It presents similarities with the Thrush presented in To mock a Mockingbird. But I read around that the Thrush, the T-combinator, is mostly used to create fluent interfaces. Which is not the case here.

The example I have in mind is the interplay between cons and head/tail shown in my post about purely functional lists.

cons = x,y -> w -> w(x,y)

head = c -> c(x,y -> x)

tail = c -> c(x,y -> y)

head(cons('a','b')) = (cons('a','b'))(x,y -> x) = 'a'

tail(cons('a','b')) = (cons('a','b'))(x,y -> y) = 'b'

After observing that both head and tail apply a binary function to a cons, it is possible to factorize their shared behavior by introducing an applier function that accepts in this case the binary function as its first parameter.

applier = binFun -> c -> c(binFun)

head = applier(x,y -> x)

tail = applier(x,y -> y)

Because the binary function is sent in visit to the cons parameters, I rename it generically visitor.

Because the cons is just holding together a group of values, so to present them to the visitor, I rename the cons a holder and the grouped values a tuple.

What we obtain is the following:

applier = visitor -> holder -> holder(visitor)

holder = tuple -> visitor -> visitor(tuple)

There seem to be some simmetry A -> B -> B(A), and here sings the Thrush: Txy = yx

But I reckon it’s not the right way of looking at this point: a group of values is fundamentally different from a visitor. Or is not?

The real constraint seems to be that order of tuple and arity of holder && visitor must be equal. To explicit that, we write:

applier = visitorN -> holderN -> holderN(visitorN)

holderN = tupleN -> visitorN -> visitorN(tupleN)

Is this a pattern? Does it show in other situations? Is there a monad lurking in the shadows?

The execution of the visitor allows side effects, for example the display of data in the UI.

The execution of the visitor may return another tuple, possibly with a different number of args.

The holder could possibly do more than just present the tuple to the visitor. On the other hand… this implementation of the holder IS the tuple! It doesn’t do anything else than keep the N values together.

Dividing what I here call tuples into sequences of parameters to be partially applied, dissolves this construction completely.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s