Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Scala script

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Xiaobian to share with you the Scala script sample analysis, I believe most people do not know how, so share this article for your reference, I hope you read this article after a lot of gains, let us go to understand it!

Processing trivial, day-to-day work scripts often requires processing files. In this section, you will create a script that reads line records from a file, prepending the number of characters in each line, and prints them out. *** Version is shown in code 3.10:

import scala.io.Source if (args.length > 0) { for (line 0) { 1 50 for (line 0) { 1 | 50 | for (line b.length) a else b ) val widths = lines.map(widthOfLength)

The reduceLeft method applies the passed method to the first two elements of lines, then to the result of the *** application and the next element of lines, and so on, up to the entire list. Each time this is applied, the result will be the longest line encountered, because the incoming function,(a, b) => if (a.length > b.length) a else b, returns the longest of the two incoming strings. reduceLeft returns the result of a single application of ***, which is the longest string contained in lines in this example.

With this result, you can calculate the width of *** by passing the longest line to widthOfLength:

val maxWidth = widthOfLength(longestLine)

*** All that remains is to print out these lines in a suitable format. You can do this:

for (line 0) { val lines = Source.fromFile(args(0)).getLines.toList val longestLine = lines.reduceLeft( (a, b) => if (a.length > b.length) a else b ) val maxWidth = widthOfLength(longestLine) for (line

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report