Log in

Daily Source Code's Journal
[Most Recent Entries] [Calendar View] [Friends]

Below are the 14 most recent journal entries recorded in Daily Source Code's LiveJournal:

Sunday, November 16th, 2008
6:06 pm
handling less than, equal to and greater than gracefully
I hate repetetive code, perhaps pathologically so. In particular, I always find myself glaring at:
        if (a < -300) {
        } else if (a == -300) {
        } else {

Why should I have to write -300 so many times? This has always bugged me. I was thinking about what I'd like some imagined language syntax to look like for handling this more gracefully and realized that I could do it in C++ with templates as is:
template<typename Ta, typename Tb>
static char
cmp(Ta a, Tb b)
        return (a < b ? '<' : a == b ? '=' : '>');

Which allows for the perhaps better:
        switch (cmp(a, -300)) {
        case '<':
        case '=':
        case '>':

Some trivial testing even suggests that GCC's c++ compiler properly optimizes through the template, getting rid of the character intermediaries which were just there for human eyes in the first place. Cool.
Tuesday, April 17th, 2007
5:44 pm
Using method-static data for static data in templated classes.
For a long time, I've been looking for ways to include static members of templated classes that don't require consumers to instantiate the templated classes' static members in their own code. My results have failed to materialize. Many shortcuts that are decidedly less ugly are mentioned on the Internet, but fail to work outside of specific Microsoft compilers or specific GNU compilers. Moreover, the GNU line is moving towards a more strict language that is closer to the standard, so some once-acceptable shortcuts in the GNU language are no longer workable. Frustratingly, static members prove impossible to instantiate without providing an initializer, which is problematic for void-constructored static members, as the compiler seems to want to treat them as either a forward-declaration of the variable, rather than a definition, or (if you parenthesise) as a forward-declaration of a method.

A solution (though I have not verified if this is standard) is to make the data static to a static member function. This also (perhaps unwantedly, if one is wanting to use static members to e.g. perform startup tasks) introduces lazy allocation to the fold, only constructing the static member when its use is requested. This is also how we can end up with a simple template for Singleton classes, as:

template<typename T>
class Singleton {
public: static T *instance(void) { static T object; return (&object); }

Note that it is, in this case, also possible to return a reference to the object and still maintain lazy-allocation (if your compiler delays allocation and initialization of static data in static methods until their first invocation), unlike with the traditional static-pointer method, though this may complicate locking, though many compilers seem to synchronize the process of creation of static data, as here, but I am not sure if they guarantee against two invocations of the method using two different cases of data, or if they merely guard against use of incomplete values for the static data.

Extensive tests have shown that (at least with my compiler) each templated version of the class will get unique static data for its static methods. In the singleton case, this is obviously required, and it is probably semantically required even in other cases, as each static method is distinct.

Note also that the problems with the compiler's misparse of void-constructored static data definitions does not occur with this, as (without extern) this will always be treated as a definition when in non-global scope.

Example: bitmask with automatic bit-allocation.Collapse )
Wednesday, February 21st, 2007
6:08 pm
Getting values from a binary tree within a range.
Sloppy, but quick enoughCollapse )

I have a much better approach stuck in my head (which should be a lot faster), but I can't quite work out how to get the code right. Mind, that approach is only faster if you can find the node with the value closest to but not less than min in O(1) time (for example, if you have a pointer to that node already and are finding all nodes which are greater than it but less than some constraint.) It's sort of like what you do to iterate through all items greater than a given starting point, but avoids excess exploration of the left branches of parent nodes.
Thursday, June 1st, 2006
7:15 pm
creative (ab)use of threads and setjmp
i've discovered (?) what i think is an extremely creative misuse of threads:
  • create a new thread and save the stack with setjmp.
  • from the main thread, longjmp to this saved stack.
  • the main thread will start executing the stack of the worker thread!
if the worker thread is still running, this generally causes a problem... but surprisingly, it works if the worker thread has exited. i'm using a loose definition of working, as i'm sure the operating system thinks the memory that was being used for the worker thread stack is free. but the fact that it works at all is shocking. zombie threads!

the setjmp interface predates threading by... a decade or more? i got started on this path by wondering how an interface as old and not-designed-for-threads as setjmp would possibly behave in a brave-new-world. now i've got a whole playground i never knew existed.

i totally deserve a medal! this is probably my best hack evar. ^_^ now if only i could figure out a way to actually *use* it.

the codeCollapse )

the outputCollapse )

[x-posted to aisa0, cs_wos, cprogramming, and dailysrc.]
Tuesday, August 16th, 2005
2:52 am
Monday, August 15th, 2005
12:33 am
Tuesday, May 17th, 2005
1:11 am
(((lambda (f)
   ((lambda (g) (g g))
    (lambda (g) (lambda (x) ((g g) (f x))))))
  (lambda (x) (+ x 1))) 0)
Monday, May 2nd, 2005
7:42 pm
anonymous recursive power-of-2 factorization in Ruby
#! /usr/bin/env ruby

ARGV.each do |w|
  p proc { |f| f.call(f) }.call( proc { |f|
    proc { |y|
      proc { |x|
        if y == 0 then
          [ 0 ]
          [ y & x, f.call(f).call(y & ~x).call(x << 1) ]

For example:

^_^ (juli@beach:~)146% ruby s.rb 8 9 10 11 12 13 14 15
[0, [0, [0, [8, [0]]]]]
[1, [0, [0, [8, [0]]]]]
[0, [2, [0, [8, [0]]]]]
[1, [2, [0, [8, [0]]]]]
[0, [0, [4, [8, [0]]]]]
[1, [0, [4, [8, [0]]]]]
[0, [2, [4, [8, [0]]]]]
[1, [2, [4, [8, [0]]]]]

Current Mood: bored
Friday, April 1st, 2005
4:39 pm
Ruby code to process friends data from LiveJournal URLs ala http://www.livejournal.com/misc/fdata.bml?user=flata and tell you who lists you that you don't list, and vice-versa.

Ruby ahoy!Collapse )

For bonus points, look at the foldr using example below, and give an example of using foldr to create an array which can be used with .each to do the printing of the nand of the arrays.
Friday, March 11th, 2005
12:53 pm
overlap with one output and two input ranges
This code determines whether one output buffer overlaps safely with two input buffers. One likely use would be the implementation of a variable length xor routine.

bcopy processes backwards from the end when write-ahead overlap would occur. the only addition here is checking to see if processing backwards for one range leads to write-ahead in the other input range. In that fatal case, you'd probably have to move one of the input ranges into a shunt.

Licensed under the GPL, per its source libozia.

At 115 lines this is a little long, but a lot of it is testing/reporting overhead. Tested on FreeBSD & MacOSX.

code snippedCollapse )
Sunday, March 6th, 2005
7:00 pm
doing interface-based programming in C++.
In C++, I've wanted do do interface-based programming, and further, be able to wrap things at the interface level so that I could make locking part of the interface, or possibly do an asynchronous or remote function call without the caller having to know or do anything special. A few weeks ago I came up with a way to do this by stacking vtables. Note that this version is simple and uses two virtual methods. A more complex version uses a templated IBase to avoid one virtual method, which should be fairly obvious. Note that this is cumbersome, but I've written (and am using) a proof-of-concept interface generator to do this stuff for me, and I've already begun using it to make invariants and locking and whatnot a part of the exported interface/contract in my code.

Note that this is also a good interview question, if you're so inclined. I came up with this with a lot of help from arjache.

vtable stackingCollapse )
6:59 pm
Fun with recursion and the C++ type system and templates and and and. Get it?

apologies for the GNUismsCollapse )
6:44 pm
do not mix with word-palindromes
Ok, ok, it's another common interview question, but the answer that I like is ever so slightly unusual because it's more generic, and actually a bit easier to write out for the first time, because of how the logic is broken out.

i palindrome iCollapse )
Tuesday, March 1st, 2005
2:17 am
About LiveJournal.com