[swift-evolution] C-style For Loops

Ray Fix rayfix at gmail.com
Mon Dec 7 17:58:53 CST 2015


Hi Reviewers,

Since it looks like Nate has already done that analysis for the standard library, let’s analyze Dmitri's semi-obfuscated prime signature for fun.  

Starting with:

main(i,j){for(i=2;;i++){for(j=2;j<i;j++){if(!(i%j)){j=0;break;}}if
(j){printf("%d\n",i);}}} /*Dmitri Gribenko <gribozavr at gmail.com>*/

First transform into Swift.  (Using += 1 instead of ++ since we know those are going.)

var j: Int
for var i=2; ; i+=1 {
  for j=2; j<i; j+=1 {
    if i%j == 0 {
      j = 0
      break
    }
  }
  if j != 0 {
    print(i)
  }
} // Dmitri Gribenko <gribozavr at gmail.com>


Next get rid of those for loops.  


for i in 2 ..< Int.max {
  var j = 2
  while j < i {
    if i%j == 0 {
      j = 0
      break
    }
    j += 1
  }
  if j != 0 {
    print(i)
  }
} // Dmitri Gribenko <gribozavr at gmail.com>

There is an improvement in that it forced us to avoid integer overflow by specifying the end game (although the heat death of the universe might happen first if you run this in a playground).  Since j escapes the scope of it’s loop we couldn’t use a for statement variable.  I think this is actually a good thing because it makes this wrinkle more apparent.

For-in almost always looks better. If things get too complicated you can always fall back to a different control structure like while or repeat.    BTW, looking at Doug’s implementation of the Sieve of Eratosthenes from his WWDC Value-Types talk, it uses  for-in-stride.  He explicitly preferred that to a traditional C-style even though it would have been easy to go either way.  It just looks better.  Fewer semicolons, it must be good.

Here is my review:

1. I endorse the proposal
2. I think it is worthwhile as it will force people to adopt good practices early and break bad habits.
3. I believe the change goes along well with the removal of ++ and — operator.  Reducing the surface area of the language is a good thing.
4. It will cause the “Swift is not stable!” crowd to go a little more crazy but I am okay with that.
5. I thought about this pretty hard, checked my usage of for loops in a non-trivial code base.  I feel even more comfortable after Nate’s analysis of the standard library.

PS:  I do not recommend any changes to Dmitri's signature. :)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151207/59528703/attachment.html>


More information about the swift-evolution mailing list