Note: Examples from this article are from http://danielwestheide.com/blog/2012/12/12/ the-neophytes-guide-to-scala-part-4-pattern-matching-anonymous-functions.html, changed parts of the code according to his own understanding and recorded it. 1. Two-tuple sequences remove words that are too high or too low in Word frequency
Word count is the big data version of Hello World, and we have similar needs in actual projects. For example, the following sequence (I am lazy, I use the data in the example):
Val wordfrequencies:list[(String, Int)] = ("habitual", 6):: ("and", ""):: ("Consuetudinary", 2):: ("additionally", 27 ):: ("homely", 5):: ("society", +):: Nil
If we want to remove high-frequency words (greater than 25) with low-frequency words (less than 3), keep the If Word, and then output the word itself, you can use Filter+map:
Val res = wordfrequencies.filter (wf = wf._2 > 3 && wf._2 <). Map (_._1)
This will do what we are meant to do. But the bad thing about this is that the bunch of code that accesses the element doesn't look good. Especially _._1 this kind of code, the readability is very poor, lets the person not touch the mind. 2. Pattern matching anonymous function (pattern Matching Anonymous Functions)
If we can parse out those fields in the meta-ancestor, the code will be much more readable. Scala provides an alternative to defining anonymous functions: pattern matching an anonymous function is a block of code that consists of a number of cases as a function body, although the code block is preceded by the match keyword. We use pattern matching anonymous functions to implement the above functions:
def wordfrefilter (wordfrequencies:seq[(String, Int)]): seq[(string)] = {
Wordfrequencies.filter {case (_, f) = = F > 3 && F <}.map {case (W, _) = W}
}
It is important to note that the parameters inside must specify the data type. Because the Scala compiler does not have enough messages to infer that the pattern matches the type of the anonymous function. If we remove the trailing seq[(String, Int), the IDE will prompt you directly: Missing type annotation for parameter:wordfrequencies.
There are two anonymous functions above, and if we assign two of the two anonymous functions to constants, we will get their data type more clearly:
Val predicate: (String, Int) = = Boolean = {case (_, F) + F > 3 && F < +}
Val transformed: (Str ing, Int) = = String = {case (W, _) = = W}
Another thing to note is that you define similar anonymous functions and pass them on to other functions, as in our example, you have to make sure that for all possible inputs, you must have a case in your anonymous function that can be matched to and return a value, or the runtime might throw matcherror.