Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Lisp and Scheme have helped my C programming

Name: Anonymous 2008-04-23 22:58

Yesterday I wrote a silly program that randomly places queens onto a chess board until every space either has a queen or is blocked by a queen. The "hardest" part was writing the code to mark the appropriate spaces as blocked by the placement of a new queen.

I started by writing code like this.

if(r >= 0)
    for(i = r - NUM_COLS; i >= 0; i -= NUM_COLS)
        mark(board, i, BLOCK);


But after doing this for the first couple types of blocks, I realized that I could factor a pattern out of it.


if(blocks[j].pre(r, r) == blocks[j].expected_pre)
    for(i = r + blocks[j].change;
        blocks[j].during(i, r) == blocks[j].expected_during;
        i += blocks[j].change)
            mark(board, i, BLOCK);


Then I could just write an array of structures that hold information on the prerequisites for each type of block, the loop checking function, and the loop change offset, like this.


Block blocks[] = {
    {isUnderTopEdge,    true,  isUnderTopEdge,    true,  -NUM_COLS},
    {isAboveBottomEdge, true,  isAboveBottomEdge, true,  NUM_COLS},
    {isLeftEdge,        false, isRightEdge,       false, -1},
    {isRightEdge,       false, isLeftEdge,        false, 1},
    {isLeftEdge,        false, isLeftOf,          true,  -(NUM_COLS+1)},
    {isRightEdge,       false, isRightOf,         true,  -(NUM_COLS-1)},
    {isLeftEdge,        false, isLeftOf,          true,  (NUM_COLS-1)},
    {isRightEdge,       false, isRightOf,         true,  (NUM_COLS+1)},
    {0},
};


That made it much easier to write the last types of blocks (i.e. left, right, and diagonal).

Of course, I learned a lot about factoring out patterns by learning Lisp and Scheme, specifically reading and watching SICP.

Name: Anonymous 2008-04-23 23:32

>>1
Lisp and Scheme have helped my C programming
Of course, lisp shall be learned even if one does not intend to use it.
>>3
No, it doesn't.
>>4
I don't think OP lives under a god damn rock.
>>5
They'd be reduntant, but not syntactic salt or sugar. Learn what syntactic sugar is.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List