#2895 Enhanced For loop in Fantom?

Gary Sun 27 Aug 2023

Hi everyone, I'm learning Fantom. Does Fantom support enhanced for-loop (or foreach) syntax introduced in Java 5

// print array elements in Java

class Main {
  public static void main(String[] args) {

    int[] numbers = {3, 9, 5, -5};

    for (int number: numbers) {
      System.out.println(number);
    }
  }
}

Ok, I may have spoken to soon, it looks like Closures are the primary mechanism for iteration in Fantom :)

class Main {

    public static Void main() {

        numbers := [3, 9, 5, -5];
        numbers.each |Int val, Int index| { echo("$index = $val")}
    }
}

SlimerDude Sun 27 Aug 2023

Yep, you got it! :)

Gary Sun 27 Aug 2023

Thx @SlimerDude, I'm enjoying learning Fantom so far. As an intermediate-level programmer and as part of my learning process, I'm looking over the Fantom code examples on Rosetta code. I also attempt to translate from other languages as an exercise. Currently, I'm translating a Kotlin code example under the Determine if a string is numeric category. You can probably see why I was asking about the enhanced for loop.

// Kotlin
fun isNumeric(input: String): Boolean =
    try {
        input.toDouble()
        true
    } catch(e: NumberFormatException) {
        false
    }

fun main() {
    val inputs = arrayOf("152", "-3.141", "Foo123", "-0", "456bar", "1.0E10")
    for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}")
}

I realize a sample code already exists for Fantom in this category. But there seems to be room for another type of example. :)

class Main {

    static Void main() {
        inputs := ["152", "-3.141", "Foo123", "-0", "456bar", "1.0E10"]
        inputs.each |Str input| { echo("$input \tis " + (isNumeric(input) ? "numeric" : "not numeric"))}
    }

    static Bool isNumeric(Str input) {
        try {
            input.toFloat
            return true
        }
        catch(Err e) {
            return false
        }
    }
}

Output:

152     is numeric
-3.141  is numeric
Foo123  is not numeric
-0      is numeric
456bar  is not numeric
1.0E10  is numeric

SlimerDude Sun 27 Aug 2023

Hi @chikega,

Indeed your isNumeric() method translates very well to other languages.

Although I find the use of the checked argument (where available) to be very idiomatic Fantom, and usually cuts down the amount of code you need to write.

For example, isNumeric() could be written like this:

static Bool isNumeric(Str input) {
    input.toFloat(false) != null
}

Gary Sun 27 Aug 2023

Hi @SlimerDude, Thank you for the comment and thank you for the code snippet! I just read something in Jeff Szuhay's Learn C Programming book that really reminds me of your code snippet. He started off with this bit of code:

bool isEven( int num )  {
  bool isEven = false;  // Initialize with assumption that 
                        // it's not false.
  if( (num % 2) == 0 )
    isEven = true;
  return isEven;
}

Then he whittled it down to this:

bool isEven ( int num)  {
  if( num % 2 ) 
    return false;
  return true;
}

Then he finally whittled it down to its most condensed form which reminds me of what you posted. That's so awesome! :D

bool isEven ( int num)  {
  return !(num % 2 ) 
}

Gary Mon 9 Oct 2023

I asked Athropic Claude for an explanation of the code snippet:

static Bool isNumeric(Str input) {
        input.toFloat(false) != null
    }

Explanation for those that are learning Fantom:

The isNumeric method is checking if a string can be converted to a float number. Here is a breakdown of what it is doing:

- input.toFloat(false) tries to convert the input string to a float. 
- The false parameter means it will not throw an exception if the conversion fails.
- Instead, it will return null if the conversion fails.
- So if input.toFloat(false) returns a non-null value, the conversion succeeded and the string is numeric.
- If it returns null, the conversion failed and the string is not numeric.
- Therefore, we check if the result is != null to determine if the string is numeric or not.
- If input.toFloat(false) != null evaluates to true, the string is numeric. 
- If it evaluates to false, the string is not numeric.

So in summary, this is a concise way in Fantom to check if a string can be converted to a float without needing try/catch blocks. 
We try the conversion, check for null instead of exceptions, and use that to determine if the input string is numeric.

SlimerDude Mon 16 Oct 2023

Interesting, I hadn't come across Anthropic before.

Gary Fri 1 Dec 2023

I like it better than ChaptGPT .. so far. :->

Login or Signup to reply.