Quantcast
Channel: Chaos Folded
Viewing all articles
Browse latest Browse all 10

Obscure C from a new perspective

$
0
0

C is probably one of the most uninteresting programming languages in the world, from a language theory standpoint. It is very simple, doesn’t provide any advanced control constructs, the type system only provides most basic functionality, and its execution model is very simple and predictable. This is one reason why many people love C, including even me in the past. However, I went on to functional programming, which bent my mind a lot. In my opinion, C’s simplicity can quickly become an illusion of easiness. A lot of people think that a good reason to use C is that code written in it is easy to reason about, very predictable and also very fast.

This is not another attempt to prove the opposite. What I want instead is to experiment trying to bring concepts from functional languages into C. As it turned out, this yields very obscure code, and is mostly even impossible in C99. For example, there is no direct or indirect support for closures in C, so I had to use a GCC extension (namely lexically scoped functions) to get things to work.

Now what is the canonical first function you write in a functional language, the “hello world” in functional programming? It’s the notorious factorial function. A very integral part of my implementations is the concept of continuation-passing style (CPS). If you haven’t heard about continuations before, I recommend reading Continuations Made Simple and Illustrated written by Denys Duchier. Although it’s Python-specific, it sheds quite some light on CPS.

I have written four versions of the factorial function in C, each as a little program, which accepts a number as its first command line argument and prints its factorial in response. The codes are very obscure, even for experienced C programmers, and I admit that this was intended to some extent. It shows how incompatible concepts can turn an otherwise familiar language into a beast. However, differently from other approaches to obscure C programming, I didn’t achieve this by intentionally unbeautifying the code, because that would be boring. Anyway, here is the code:

  • Version 1 — using setjmp/longjmp continuations
  • Version 2 — using function pointer continuations
  • Version 3 — implementing algebraic lists and folds using closures
  • Version 4 — lambda calculus with fixpoint operator

Viewing all articles
Browse latest Browse all 10

Trending Articles