Introducing The K&R Challenge

Recently, I inherited a copy of The C Programming Language, aka “K&R”. I was borrowing it, and today I tried to give it back, but the book’s former owner didn’t want it back. I was going to put it back in it’s deep dark box, likely to never been seen again, when I had a thought. Surely there’s something in this ancient tome of knowledge waiting for me.

On a whim, I decided to go through the exercises. This post marks the first task in the K&R Challenge.

The rules: the book is about the C programming langauge. The book is not about glib, linux programming, gtk, or any other library or framework. Therefore, the solutions to the exercises should only use the standard library, unless the book specifically calls out a library. I will attempt to stay as true to the wording of the excercise as possible.

Seems pretty straightforward, right? Well this brings us to part two; after doing an excercise in C, I will do it in Haskell. For these examples, I will attempt to implement the program in idiomatic Haskell. The ends are more important than the means here, so if the example calls out a specific function or technique, I will only use it if I feel it’s the best way to do it. For the Haskell portion, I will minimize the use of libraries as well.

So, without further ado…

Excercise 1.1

Excercise 1.1 is simply to implement “Hello World” Shockingly this is a trivial problem in C:

#include "stdio.h" int main (int argc, char ** argv) { printf("Hello World!\n"); return 0; }

First, we include stdio.h to gain access to printf, then we say hello to the world. You’ll notice I put curly braces on their own lines. Sue me.

To compile this, assuming you’re using gcc, enter the following:

gcc -Wall ex1.c -o ex1

Running the produced program produces the output:

Hello World!

Amazing!

In Haskell, this is even easier:

main :: IO () main = putStrLn "Hello World!"

As putStrLn and the IO monad are in prelude, this program does not require any imports.

To run this, simply type the following at the prompt:

runhaskell ex1.hs

Which produces the following output:

Hello World!

If you were able to follow all of that, then congratulations! You are an elite hacker! Your black fedora is in the mail.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: