Skip to content
Jonathan edited this page Mar 1, 2018 · 4 revisions

Loops are very simple.

Ranged loops

The only way to write a index based foreach is using ranges (..), you can also specify more than one range using lists.

// Prints from 0 to 9
for (i : 0..9) { // Single range
  println(i) 
}
// Prints from 0 to 5, and from 8 to 10
for (i : [0..5,8..10]) { // Multiple ranges
  println(i)   
}

Fun example

If you are familiar with functional languages, you will easily understand the code

// Prints: 0, 2, 4, 6, 10, 12, 14, 16, 18, 20
for (i : [_*2 | 0..3,5..10]) {
  println(i) 
}

Entry example

In Java, if you want to loop thorugh linked entries, you can do that:

for (Entry e = first; e.next() != null; e = e.next())

In Firefly, you can do it with while loop:

var e = first

while (e != null) {
  // Code
  e = e.next()
}

Or creating a list:

val list = [first] + [e.next().. | _?]
for (e : list)

// Or:

for (e : [first] + [e.next().. | _?])

e.next().. has it own section in wiki: Self-assign recursive call

There are other alternatives, but we will not list all

Next element please

A good name for a feature, this allows to forward inside foreach loops, but only for Array, Iterable and Iterator:

fun getOptions(input: String): List<String> {
  val list = MutableList.new()

  for(c : input.chars) {
    if (c == '-')
      list.add(for.next()) // Next element please
  }
}

Calling for.next() returns the next element of Iterator that foreach is exploring, but it also jumps the element, meaning that the foreach will not loop on it. for.next() is the same as calling Iterator.next().

But this is not perfect, imagine if I call getOptions with options -, an error will be throw, so, to fix that, we will change the code to:

fun getOptions(input: String): List<String> {
  val list = MutableList.new()

  for(c : input.chars) {
    if (c == '-')
      if (for.next()) { list.add(_) }
  }
}

Wow, what the **** is that? In this case, is a sugar syntax to if (for.hasNext()) { list.add(for.next()) }, but, in Firefly, you can test optional values in if expressions, returning true if value is present, or false if not, and then, assigning a variable to value. See more here

You can do this way too:

fun getOptions(input: String): List<String> {
  val list = MutableList.new()

  for(c : input.chars) {
    if (c == '-')
      for.next() ? { list.add(_) }
  }
}

Function

You may also use for function:

[0..9].for {
    println(_)
}
Clone this wiki locally