hawkeye
hawkeye

Reputation: 35762

Is there a way in Clojure to make a protocol (or other type structure) closed to extension?

In Clojure we have various extension mechanisms: extend-type, extend-protocol, extend.

Now we're making some assumptions:

There is some background to this question. Philip Wadler talks about the expression problem. This discussion is expanded here as it relates to algebraic data types:

With algebraic data types,

It is very cheap to add a new operation on things: you just define a new function. All the old functions on those things continue to work unchanged.

It is very expensive to add a new kind of thing: you have to add a new constructor an existing data type, and you have to edit and recompile every function which uses that type.

With classes,

It is very cheap to add a new kind of thing: just add a new subclass, and as needed you define specialized methods, in that class, for all the existing operations. The superclass and all the other subclasses continue to work unchanged.

It is very expensive to add a new operation on things: you have to add a new method declaration to the superclass and potentially add a method definition to every existing subclass. In practice, the burden varies depending on the method.

Now the driver behind this (and they're speaking from a Haskell perspective) is a concept in functional programming called total functions. (This is related to parametricity in functional programming). The benefit of total functions is that the programs written are provably terminating.

Now that might seem like a fluffy Computer Science benefit - but it has a real benefit for us in the Clojure World. Guys like Steve Miner and Reid Draper are working on simple-check. Now if we have a total function then we can have confidence that given a domain of inputs, we can guarantee the range of outputs.

Now if you can close a type to extension, you can more easily declare a function a 'total function' - and make the work for tools like simple-check easier and more comprehensive. (And have greater confidence a function does what it says it does).

Now it looks like Ambrose' work on core.typed is starting to approach this goal.

So my question is: Is there a way in Clojure to make a protocol (or other type structure) closed to extension? (Or is this just completely non-idiomatic?)

Upvotes: 1

Views: 171

Answers (1)

metasoarous
metasoarous

Reputation: 2943

Creating objects with reify would give you an object with an anonymous type. Since that type is anonymous, there is no way to extend it to any further protocols. But this is only one sided; it doesn't prevent anyone else from extending the protocols found in the body of reify to other types/records.

I don't think there is any way to accomplish this with records, types or protocols (except perhaps by digging into the underlying implementations).

Upvotes: 1

Related Questions