Statically Typed

because Hindley-Milner rocks

Let Me Reprise That


Why did I use template meta-programming in the last solution?  That solution would only have made sense had I been able to assume a Boost::Array wherein the function would have started

template<long Length> Pair<long> findFirstCount(const Array<long,Length> &_array, int _value){

and I should have used “const” pointers to emphasize that I did not intend to change the array.  Notice how I didn’t say stop future developers from changing the array?  You have your stories and I have mine.

No, a better solution and one I should have written uses a simple Map combined with a bunch of function pointers.  Much like so

typedef Pair<long> (*pair_function)(int*,long,long,long);
Pair<long> findFirstCount(const int *_array, long _length, int _value){
    Pair<long> interval = findValue( _array, 0, _length -1, _value );
    Map<long,pair_function> function_map;
        function_map.insert( make_pair( -1, &notFound ) );
        function_map.insert( make_pair( 0, &atFront ) );
        function_map.insert( make_pair( _length, &atBack ) );

    map<long,pair_function>::iterator function_iter = function_map.find( interval.first )
    if( function_iter == function_map.end() ){
        return inside( _array, interval.first, interval.second, _value );
    }

    return (*function_iter->second)( _array, interval.first, interval.second, _value );
}

and the other functions would wrap what was contained in the case statements of the last post.  There, my mood has improved but not enough to run it through a compiler to see if it works.  Shame on me.

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 March 15, 2010 by in C++, Intervew Questions.
%d bloggers like this: