Friday, August 30, 2013

Breakable loops in Scala

Overview
Contrary to C++ and Java, Scala does not allow developer to exit an iterative execution prematurely using a syntax equivalent to break.

var sum = 0

for( i <- 0 until 100) {
  sum += i
  if( sum > 400) 
    break   // won't compile!                                  
}

Scala purists tend to stay away from this type of constructs and use higher order collection methods such as
   exists( p: (T) => Boolean)
   find( p: (T) => Boolean)
   takeWhile( p: (T) => Boolean)
However these methods are not available outside collections. There are cases where a `break` construct may be a simpler solution.
This post review the different options to 'break' from a loop according to a predefined condition.

Breakable control
Although breaking out of a loop may not be appealing to "pure" functional developer, the Scala language provides former Java and C++ developer with the option to use break and continue statements. The breakable statement define the scope for which break is valid.

import scala.util.control.Breaks._                            

var sum = 0
breakable { 
  for (i <- 0 until 100 ) {
    sum += i
    if( sum > 55) 
      break
  }
}

Any experienced developer would be quite reluctant to use such an idiom: beside the fact that the accumulator is defined as a variable, the implementation is unnecessary convoluted adding a wrapper around the loop. Let's try to find a more functional like approach to breaking out of any loop

scan & fold to the rescue
Luckily, Scala provides collections with functional traversal patterns that can be used and chained to break, elegantly from a loop. The following code snippets introduce applies some of those traversal patterns to an array and a associative map to illustrate the overall "functional" approach to iteration.
Let's consider the problem of extracting the elements of an array or map before a predefined condition is met for an element. For instance, let's extract the elements of an array or a hash map until one element has the value 0. The Scala programming language provide us with the takeWhile method (lines 7 & 10) that allows to to end traversing a collection and return a elements of the collection visited when a condition is met.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
val values = Array[Int](9, 45, 11, 0, 67, 33)

val mappedValues = Map[String, Int](
  "A"->2, "B"->45, "C"->67, "D"->0, "E"->56
)
 // Extract a subarray of values until the condition is met
values takeWhile( _ != 0) // -> Array(9, 45, 11)
 
  // Extract a submap until the condition is met
mappedValues takeWhile( _._2 != 0) 
  // -> Map(E -> 56, A -> 2, B -> 45, C -> 67)

The second case consists in accumulating values until a condition on the accumulator is met. Contrary to fold and reduce methods which apply a function (i.e summation) to all the elements of a collection to return a single value, scan, scanLeft and scanRight methods return a collection of values processed by the function.

In the following example, the invocation of the higher order method scanLeft (lines 4 generates an array and a hash map with the cumulative values. The takeWhile method i(lines 5 & 8) s then applied to the resulting array or map to return a collection of cumulative values until the accumulator exceeds 56. The same invocation can be used to return the element which push the accumulator beyond the threshold.

1
2
3
4
5
6
7
8
9
values.scanLeft(0)(_ + _).takeWhile (_ < 56) 
   //-> Array(0, 9, 54)
 
mappedValues.scanLeft(0) (_ + _._2)
   .takeWhile( _ < 56)
 
val indexTargetEl = values.scanLeft(0)(_ + _)
      .takeWhile (_ < 56).size -1            
val targetEl = values(indexTargetEl)



Tail recursion
A third and elegant alternative to exit from a loop is using the tail recursion which is supported natively in the Scala language. The first method, findValue exits the loop when a condition on the value is reached (line 5). The second method, findCummulative, is implemented as a closure and exits when the sum of elements exceeds a predefined value (line 15).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
val values = Array[Int](9, 45, 11, 0, 67, 33)
 
@scala.annotation.tailrec
def findValue(values: Array[Int], index: Int) : Int = {
   if( values(index) == 0 || index >= values.size)
     index
   else
     findValue(values, index + 1)
}
val newValues = values.slice(0, findValue(values, 0))   

val MAX_VALUE :Int = 86

@scala.annotation.tailrec
def findCumulative(sum: Int, index: Int): Int = {
   if( index >= values.size ||sum >= MAX_VALUE)
     index -1
   else
     findCumulative(sum + values(index), index + 1)
}

val newValues2 = values.slice(0, findCumulative(0, 0))

This concludes our review of three different Scala constructs available to developer to exit prematurely from a loop
  • breakable construct
  • Higher order method such as exists, find, takeWhile....
  • tail recursion

References
github.com/prnicolas
Programming in Scala M. Odersky, L. Spoon, B. Venners - Artima 2010

47 comments:

  1. Hi, JAVA is not at all difficult all you need is to clear your concepts mainly because the concepts of JAVA programming have been taken from day to day life examples.J2EE Training in Chennai | JAVA Training in Chennai

    ReplyDelete
    Replies
    1. Hi There,

      You’ve trimmed my dim. I feel as bright and fresh as your prolific website and blogs!
      I have 1 or 2 arrays to call in a config file in a sheet called Array. Is there a way to call and assign these arrays from the object?
      For example:
      Column A: Column B:
      Array1 {“Dan”, “Bob”, “Steve”, “Karen”}
      I want to pull this Array1 from the config sheet “Array” and use this Array of String in a options property in an Input Dialogue activity. How do I do this?
      To your screenshot:
      Is JArray a variable? What type if it is?
      Use the Automation Anywhere Object Recorder to manage and execute Windows controls as a background process.
      Appreciate your effort for making such useful blogs and helping the community.

      Thanks,
      Kevin

      Delete
  2. Replies
    1. Hi Patrick,

      What a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this Automation anywhere tutorial

      The “scroll” option in SendHotkey activity simulates pressing the “Scroll lock” button on the keyboard. Enable or disable this option is best seen within an Excel sheet: when enabled, if you press any of the arrow keys it will result in the screen moving in that direction, but the selected cell will not change. It has nothing to do with the actual scrolling.
      In my opinion, the best way to scroll whitin a list or page is with SendHotkey -> arrow up/down OR pg up/down.

      Once again thanks for your tutorial.

      Cheers,
      Kevin

      Delete
  3. Sas Training Institute in Noida-Webtrackker is the best sas training institute in noida. SAS has taken the lead role for a long time, where most companies have standard software. While you have this certification under your belt, give big rewards to the IT industry, it can also serve as an important payer on the business side of the economy. SAS can read data files created by other statistical packages. Therefore, for experienced users of these statistical packages, SAS does not threaten to create data files created by these packages in a SAS file format.
    Sap Training Institute in Noida
    PHP Training Institute in Noida
    Hadoop Training Institute in Noida
    Oracle Training Institute in Noida
    Linux Training Institute in Noida
    Dot net Training Institute in Noida
    Salesforce training institute in noida
    Java training institute in noida

    ReplyDelete
  4. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    https://www.besanttechnologies.com/training-courses/java-training

    ReplyDelete
  5. Aws online training in india – Webtrackker is the best AWS stands for Amazon Web Services, the name given to the cloud computing facilities of the Amazon group. It has a comprehensive training program based on solutions that should be known to those who aspire to develop their skills in cloud computing. Applicants can receive a high quality AWS training experience from experts from reputable training institutes. Many different skills are taught to applicants in AWS. Candidates are exposed to the main functionalities of the main Webtrackker is the best AWS services in India, key concepts, applications, security and architectural patterns.
    Company address:
    Webtrackker Technology
    C-67, sector-63
    noida-201301
    Phone: 0120-4330760, 8802820025
    Web: www.webtrackker.com
    E-mail: info@webtrackker.com
    Website: http://webtrackker.com/amazon-web-services-aws-online-training-in-india.php


    ReplyDelete
  6. http://webtrackker.com/Salesforce-online-training-classes-in-india.php

    ReplyDelete
  7. Webtrackker Indirapuram offers an inclusive software testing training in Indirapuram. The extensive practical training provided by the Software Testing training institute in Indirapuram, equips live projects and simulations.
    software testing institute in Indirapuram

    ReplyDelete

  8. Webtrackker Indirapuram offers an inclusive software testing training in Indirapuram. The extensive practical training provided by the Software Testing training institute in Indirapuram, equips live projects and simulations.
    software testing institute in Indirapuram

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Sirkus System Bangalore Reviews- Sirkus System IT Services Pvt Ltd a logo name specialized in product improvement & answers for mobile environment and other platforms Sirkus device Bangalore critiques- Quality development, dedicated work approach and professional attitude are some of the traits which outline Sirkus Systems IT Services Pvt Ltd.

    Sirkus system
    sirkus system
    Sirkus Systems
    sirkus system review
    Sirkus System
    Sirkus System Reviews
    Sirkus System
    Sirkus System Review

    ReplyDelete
  13. Java training in indirapuram- There are multiple structures and streams for developing a product or utility. When we talk of technology and programming languages, Java is the maximum desired platform. It is used to expand a whole lot of programs for the systems and embedded devices like cellular telephones, drugs, laptops, and many others.

    Java training in indirapuram

    Hadoop training in indirapuram

    sas training in indirapuram

    sap training in indirapuram

    linux training in indirapuram

    sap fico training in indirapuram

    web design training in indirapuram

    php training in indirapuram

    ReplyDelete

  14. I am glad to read this. Thank you for this beautiful content, Keep it up. Techavera is the best
    <a href='http://www.techaveranoida.in/best-ms-exchange-server-training-in-noida.php"><b> EXCHANGE SERVER training center in noida .</b></a>
    Visit us For Quality Learning.Thank you

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete




  16. I am glad to read this. Thank you for this beautiful content, Keep it up. Techavera is the best


    EXCHANGE SERVER training company in noida

    Visit us For Quality Learning.Thank you


    ReplyDelete
  17. I am glad to read this. Thank you for this beautiful content, Keep it up. Techavera is the best VMware training course in Noida. Visit us For Quality Learning.Thank you

    ReplyDelete
  18. I am glad to read this. Thank you for this beautiful content, Keep it up. Techavera is the best MCSA Windows Server training course in

    Noida.
    Visit us For Quality Learning.Thank you

    ReplyDelete
  19. Excellent post. I have read your blog it's very interesting and informative. Keep sharing.
    mobile website builder

    ReplyDelete
  20. Greetings Mate,

    Gratitude for putting up this prolific article! You truly make everything a cake walk. Genuinely good stuff, saving time and energy.

    Somebody could share the way how possible (or how it uses) to do the automation testing of a mobile app in combination: windows PC + iOS mobile phone.
    Many automation software platforms support only the combination - MAC pc + iOS phone.
    Is it possible to use the Windows PC + iOS phone at all?
    Thanks for the help.

    But nice Article Mate! Great Information! Keep up the good work!

    Cheers,

    ReplyDelete
  21. Bonjour,


    Muchas Gracias Mi Amigo! You make learning so effortless. Anyone can follow you and I would not mind following you to the moon coz I know you are like my north star.

    As you mentioned you need to scroll down to find the text . So make sure that text is visible when you execute click text .And you can set the position of click by setting offset X/Y in the property. Automation anywhere tutorial
    PS: if similar text exist more than one time on the screen then make use occurrence property of click text to find specific text .
    THANK YOU!! This saved my butt today, I’m immensely grateful.

    Gracias
    Irene Hynes

    ReplyDelete
  22. Thanks for this blog..Very good knowledge and very good information..Java Summer Courses in Chennai | Summer Courses in Chennai

    ReplyDelete
  23. Thank you for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. sap abap developer training

    ReplyDelete