Statically Typed

because Hindley-Milner rocks

First Coding Challenge Continued


The problem with the ascii table is that the alphanumeric characters are not congruent.  Upper case letters start from 65 and end at 90, lower case letters start at 97 and end at 122 and numerals start at 48 and end at 57.  Writing some trivial little random string generator which has the desired properties from the last post isn’t so trivial after all.  In fact, it’s its own challenge and one that I’ll more than likely wimp out on.

I did promise that I’d show the Java code implemented in Scala.  For a first shot:

object CharGenerator {
    def produce(_number:Int, _length:Int): Unit = {
        if( _number < 1){
            return
        }

        val rand = new java.util.Random
        def make(_count:Int)(_acc:List[char]): List[char] = {
            if( _count < 1){
                _acc
            }

            make(_count - 1)( ( rand.nextInt(94) + 32).toChar :: _acc )
        }

        println( make( _length )( Nil ) toString )
        produce( _number - 1, _length )
    }
}

But this quickly blew the stack  even for small integers.  Obviously a straight translation from Java to Scala is not the answer.  Besides, we’re not even taking advantage of the power of Scala.  Here’s an improved version:

object CharGenerator {
    def produce(_number:Int, _length:Int): Unit ={
        if( _number < 1){
            return
        }

        val rand = new java.util.Random
        def gen: List[char] = for(i <- List.range(1, _length) ) yield (rand.nextInt(94) + 32).toChar
        def make = gen.foldLeft("")( (a,b) => a + b)

        println( make )
        produce( _number - 1, _length )
    }
}

This solution leverages a for comprehension combined with a foldLeft (think map, reduce.)

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 10, 2010 by in Java, Scala.
%d bloggers like this: