Statically Typed

because Hindley-Milner rocks

Pragmatic Programmer: Immutable C++ Script, take 2


So not only have I been looking at some things in Scala and playing around with them in what little time I can get away with at home but I’ve also been having fun with some more functional flavored code at work.  Mostly these past few days have been spent building a few scripts to do some analysis work on datasets we’ve produced exploring new algorithms.  Can I say that I love generators and reduce?

def CreateImmutable( _className, _typePairs ):
    print "class " + _className.capitalize()
    print "{"
    print "public:"
    print "\t" + _className.capitalize() + "(" + reduce( lambda x,y: x + ", " + y, (value + " " + key for key, value in _typePairs.iteritems() ) ) + ") :"
    print reduce( lambda x,y: x + ",\n" + y, ("\t\tm_" + key + "(_" + key + ")" for key in _typePairs.keys() ) ) + "{}"
    print reduce( lambda x,y: x + "\n" + y, ("\t" + value + "\tGet" + key + "() const { return m_" + key + "; }" for key, value in _typePairs.iteritems() ) )
    print "protected:"
    print "private:"
    print reduce( lambda x,y: x + "\n" + y, ("\tconst " + value + "\tm_" + key + ";" for key, value in _typePairs.iteritems() ) )
    print "};"

Clearly I could have gone farther and used “map” instead of a generator but I didn’t feel like typing all those lambda’s.  Comparing the two the first iteration was 17 lines and required some hand editing afterwards while this one is 11 lines but requires no hand editing.  That’s a big plus.  Now all I have to do is finalize the string formatting to preserve the Pascal Case and I’m done.

Advertisements

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

Information

This entry was posted on February 7, 2010 by in Pragmatic Programmer.
%d bloggers like this: