In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "similar function structure analysis in different Java.net languages". In daily operation, I believe that many people have doubts about similar function structure analysis in different Java.net languages. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "similar function structure analysis in different Java.net languages". Next, please follow the editor to study!
Filter
In a filter function, you can specify a Boolean condition (usually in the form of a higher-order function) and apply it to a collection. This function returns a subset of the collection with elements that match the condition. Filtering is closely related to the lookup function, which returns the first matching element in the collection.
Scala
Scala has several variants of filtering functions. In the simplest case, a list is filtered based on the conditions passed. In the first example, I create a list of numbers. Then you use the filter () function and pass a block of code that specifies the condition under which all elements are divisible by 3:
Val numbers = List.range (1,11) numbers filter (x = > x% 3 = = 0) / / List (3,6,9)
I can rely on implicit parameters to create a faster and more concise version of the code:
Numbers filter (_% 3 = = 0) / / List (3,6,9)
The second version is less verbose because in Scala, you can replace parameters with underscores. Both versions can get the same result.
Many examples of filtering operations use numbers, but filter () applies to any collection. This example applies filter () to a word list to determine 3-letter words:
Val words = List ("the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog") words filter (_ .length = = 3) / / List (the, fox, the, dog)
Another variant of the filtering function in Scala is the partition () function, which splits a collection into multiple parts. This split determines the separation condition based on the higher-order function you pass. Here, the partition () function returns two lists that are split based on which list members are divisible by 3:
Numbers partition (_% 3 = = 0) / / (List (3,6,9), List (1,2,4,5,7,8,10))
The filter () function returns a collection of matching elements, while find () returns only the first matching element:
Numbers find (_% 3 = = 0) / / Some (3)
However, the return value of find () is not the matching value itself, but a value wrapped in the Option class. There are two possible values for Option: Some or None. Like some other functional languages, Scala uses Option as a convention to avoid returning null if a value is missing. The Some () instance wraps the actual return value, which is 3 in the case of numbers find (_% 3 = = 0). If I try to find a value that does not exist, the return value will be None:
Numbers find (_
< 0)// None Scala 还包含多个函数,它们基于一个判定函数来处理一个集合并返回值或丢弃它们。takeWhile() 函数返回集合中满足判定函数的最大的值集: List(1, 2, 3, -4, 5, 6, 7, 8, 9, 10) takeWhile (_ >0) / / List (1,2,3)
The dropWhile () function skips the maximum number of elements that meet the decision condition:
Words dropWhile (_ startsWith "t") / / List (quick, brown, fox, jumped, over, the, lazy, dog)
Groovy
Groovy is not a functional language, but it contains many functional paradigms, some of which are named after scripting languages. For example, in functional languages, the function traditionally called filter () is the findAll () method in Groovy:
(1... 10). FindAll {it% 3 = = 0} / / [3,6,9]
Like Scala's filter function, Groovy handles all types, including strings:
Def words = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] words.findAll {it.length () = = 3} / / [The, fox, the, dog]
Groovy also has a function similar to partition (), called split ():
(1... 10). Split {it% 3} / [[1, 2, 4, 5, 7, 8, 10], [3, 6, 9]]
The return value of the split () method is a nested array, just like the nested list returned from partition () in Scala.
The find () method of Groovy returns the first matching element in the collection:
(1.. 10). Find {it% 3 = = 0} / / 3
Unlike Scala,Groovy, which follows the Java convention, it returns null when find () fails to find the element:
(1.. 10). Find {it
< 0}// null Groovy 还拥有 takeWhile() 和 dropWhile() 方法,它们具有与 Scala 的版本类似的语义: [1, 2, 3, -4, 5, 6, 7, 8, 9, 10].takeWhile {it >0} / / [1,2,3] words.dropWhile {it.startsWith ("t")} / / [quick, brown, fox, jumped, over, the, lazy, dog]
As in the Scala example, dropWhile is used as a special filter: it discards the maximum prefix that matches the decision condition, filtering only the first part of the list:
Def moreWords = ["the", "two", "ton"] + wordsmoreWords.dropWhile {it.startsWith ("t")} / / [quick, brown, fox, jumped, over, the, lazy, dog]
Clojure
Clojure has an astonishing number of collection operation routines. Because of the dynamic type of Clojure, many of these routines are generic. Many developers prefer to use Clojure because its collection libraries are very rich and flexible. Clojure uses traditional functional programming names, as shown in the (filter) function:
(def numbers (range 1 11)) (filter (fn [x] (= 0 (rem x 3) numbers); (3 69)
Like other languages, Clojure provides concise syntax for simple anonymous functions:
(filter # (zero? (rem% 3) numbers); (3 69)
And as in other languages, Clojure's functions apply to any type that applies, such as strings:
(def words ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy"dog"]) (filter # (= 3 (count%)) words); (the fox the dog)
The (filter) return type of Clojure is Seq, which is described by parentheses. Seq is the core abstraction of sequential collections in Clojure.
Mapping
The second major functional variant that is common in all Java next-generation languages is mapping. The mapping function takes a high-order function and a collection, then applies the passed function to each element and returns a collection. The returned collection (different from filtering) is the same size as the original collection, but the value is updated.
Scala
The map () function of Scala takes a block of code and returns a collection of transformations:
List (1,2,3,4,5) map (_ + 1) / / List (2,3,4,5,6)
The map () function applies to all applicable types, but it does not necessarily return a converted collection of collection elements. In this example, I return a size list of all elements in a string:
Words map (_ .length) / / List (3,5,5,3,6,4,3,3,3)
Nested lists are often generated in functional programming languages, so that it is common for nested lists to support libraries that are unnested (often called flattening). Here is an example of flattening a nested list:
List (List (1,2,3), List (4,5,6), List (7,8,9) flatMap (_ .toList) / / List (1,2,3,4,5,6,7,8,9)
The obtained List contains only elements, removing the additional infrastructure. The flatMap function also applies to data structures that may not be nested in the traditional way. For example, you can think of a string as a series of nested characters:
Words flatMap (_ .toList) / / List (t, h, e, Q, u, I, c, k, b, r, o, w, n, f, o, x,...
Groovy
Groovy also contains several mapping variants called collect (). The default variant accepts a code block so that it can be applied to each element of the collection:
(1. 5). Collect {it + = 1} / [2, 3, 4, 5, 6]
Like other languages, Groovy allows the use of abbreviations for simple anonymous high-order functions; it reserved words are used instead of individual parameters.
The collect () method applies to any set to which you can provide reasonable criteria, such as a list of strings:
Def words = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"] words.collect {it.length ()} / / [3,5,5,3,6,4,3,4,3]
Groovy also has a method of collapsing the inner structure similar to flatMap (), called flatten ():
[[1, 2, 3], [4, 5, 6], [7, 8, 9] .flatten () / [1, 2, 3, 4, 5, 6, 7, 8, 9]
The flatten () method also applies to collections that are less obvious, such as strings:
Flatten () / [t, h, e, Q, u, I, c, k, b, r, o, w, n, f, o, x, j,...
Clojure
Clojure contains a (map) function that accepts a higher-order function (which contains operators) and a collection:
(map inc numbers); (2 3 4 5 6 7 8 9 10 11)
The first argument to (map) can be any function that takes a single argument: a named function, an anonymous function, or an existing function, such as an inc that increments its parameters. The more typical anonymous syntax is demonstrated in this example, which generates a collection of word lengths in a string:
(map # (count%) words); (3 5 5 3 6 4 3 4 3 3)
The (flatten) function of Clojure is similar to Groovy's:
(flatten [[1 23] [4 56] [7 8 9]); (1 2 3 4 5 6 7 8 9)
Fold / shrink
Of the three Java next-generation languages, the third common function has the most variants and many subtle differences in name. FoldLeft and reduce are specific variants of the concept of list manipulation called catamorphism, which is a generalization of list folding. In this example, "collapse left" means:
Use a binary function or operator to combine the first element of the list with the second element to create a new first element. Repeat the first step until the list runs out and you get a single element.
Note that this is what you do when summing a set of numbers: start at 0, add the first element, add the result to the second element, and do so until the list element is used up.
Scala
Scala has the richest collection of folding operations because it somewhat simplifies many types of scenarios that are not found in dynamically typed Groovy and Clojure. Reduction functions are often used to perform summation:
List.range (1,10) reduceLeft ((a, b) = > a + b) / / 45
The function provided to reduce () is usually a function or operator that takes two arguments and returns a single result so that a list can be used. You can use Scala syntax sugar to shorten the function definition:
List.range (1,10) .reduceLeft (0) (_ + _) / / 45
The reduceLeft () function assumes that the first element is the left side of the operation. For addition operators, the position of the operands does not matter, but the placement order is important for division and other operations. If you want to reverse the order in which the transshipment operator is applied, you can use reduceRight ():
List.range (1,10) reduceRight (_-_) / / 5
Knowing when to use advanced abstractions such as reduction is a key to mastering functional programming. This example uses reduceLeft () to determine the most common words in the collection:
Words.reduceLeft ((a, b) = > if (a.length > b.length) an else b) / / jumped
Reduction and collapse operations have overlapping functions, and they are slightly different, but this is beyond the scope of this article. However, you can usually see a clear difference between them. In Scala, the signature reduceLeft [B >: a] (op: (B, A) = > B): B indicates that the only parameter you want is a function that combines elements. The initial value should be the first value in the collection. In contrast, the signature foldLeft [B] (Z B) (op: (B, A) = > B): B represents an initial seed value of the result, so you can return a type that is different from the list element type.
The following is an example of summing a collection using foldLeft:
List.range (1,10) .foldLeft (0) (_ + _) / / 45
Scala supports operator overlap, so the two common collapse operations, foldLeft and foldRight, have corresponding operators: /: and:\, respectively. Therefore, you can use foldLeft to create a concise version of sum:
(0 /: List.range (1,10)) (_ + _) / / 45
Similarly, to find the cascading difference of each element in a list (the reverse operation of the sum operation is admittedly rare), you can use the foldRight () function or the:\ operator:
(List.range (1,10):\ 0) (_-_) / / 5
Groovy
Groovy enters the reduction category by using overlap to support the same functionality as Scala's reduce () and foldLeft () options. A version of this function accepts an initial value. This example uses the inject () method to generate the sum of a collection:
(1. 10). Inject {a, b-> a + b} / / 55
The alternative form accepts an initial value:
(1. 10) .inject (0, {a, b-> a + b}) / / 55
Groovy has a much smaller library of functions than Scala or Clojure-it's not surprising to see that Groovy is a multi-paradigm programming that doesn't emphasize functional programming.
Clojure
Clojure is mainly a functional programming language, so it supports (reduce). The (reduce) function accepts an optional initial value to cover both the reduce () and foldLeft () cases handled by Scala. The (reduce) function didn't surprise the user. It accepts a function that requires two parameters and a collection:
(reduce + (range 1 11)); 55
Clojure includes advanced support for reduce-like features in a library called reducers, which will be covered in a later article.
At this point, the study of "similar function structure analysis in different Java.net languages" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.