The first blog post

// ip, scala, python

By: bill

Undestanding frog (by doing something else)

I will try to write a function to convert a bit-stream (in the form of a string) to its representation as an IPv4 address.

The catch is, the code must be as concise as possible.

Let’s try Scala!

Scala can be very concise and yet readable with some nicely written chains of operations. Let’s see it in action here:

  def toIp(str: String) =
     str.grouped(8)
        .map(el => Integer.parseInt(el, 2))
        .mkString(".")   

The grouped(n) method is defined for all the members of scala.collection.IterableLike which String is a member of. But let’s not get too involved.

What it does is given “123456” return an iterator with the contents grouped every nth character, i.e if n is 2 then we get ("12", "34", "56") which is perfect for this job.

All we have to do then, is map each one to its decimal representation and be done with it.

Now we can just say

  @ toIp("10000000000010100000001000011110")
  res1: String = "128.10.2.30"

Let’s try Python!

The best way I could come up with, without making and import, is this

  def to_ip(bitstr):
    lst = [bitstr[i:i+8] for i in range(0, len(bitstr), 8)]
    res = [str(int(i, 2)) for i in lst]
    return '.'.join(res)

and then you can simply call

  >>> print(to_ip("10000000000010100000001000011110"))
  128.10.2.30

But one would argue that python is no good without the imports. And I agree, so let’s try the same thing, but now with the help of an import.

  import re
  def to_ip2(bitstr):
    return '.'.join([str(int(i, 2)) for i in re.findall('........?', bitstr)])

so now we can call it again and get the expected results

  >>> print(to_ip2("10000000000010100000001000011110"))
  128.10.2.30

This is quite concise but it becomes difficult to read.

The classic readability/conciseness problem.

I would argue that it is much clearer in Scala, without giving way to less conciseness.