Scala:函数式编程之下划线underscore
http://blog.csdn.net/pipisorry/article/details/52913548
python参考[python函数式编程:apply, map, lambda和偏函数]
Scala 中下划线的用法
1、存在性类型:Existential types
def foo(l: List[Option[_]]) = ...
2、高阶类型参数:Higher kinded type parameters
case class A[K[_],T](a: K[T])
3、临时变量:Ignored variables
val _ = 5
4、临时参数:Ignored parameters
List(1, 2, 3) foreach { _ => println("Hi") }
5、通配模式:Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }
match {
     case List(1,_,_) => " a list with three element and the first element is 1"
     case List(_*)  => " a list with zero or more elements "
     case Map[_,_] => " matches a map with any key type and any value type "
     case _ =>
 }
val (a, _) = (1, 2)
for (_ <- 1 to 10)
6、通配导入:Wildcard imports
import java.util._
7、隐藏导入:Hiding imports
// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }
// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }
8、连接字母和标点符号:Joining letters to punctuation
def bang_!(x: Int) = 5
9、占位符语法:Placeholder syntax
List(1, 2, 3) map (_ + 2)
_ + _   
( (_: Int) + (_: Int) )(2,3)
val nums = List(1,2,3,4,5,6,7,8,9,10)
nums map (_ + 2)
nums sortWith(_>_)
nums filter (_ % 2 == 0)
nums reduceLeft(_+_)
nums reduce (_ + _)
nums reduceLeft(_ max _)
nums.exists(_ > 5)
nums.takeWhile(_ < 8)
10、偏应用函数:Partially applied functions
def fun = {
    // Some code
}
val funLike = fun _
List(1, 2, 3) foreach println _
1 to 5 map (10 * _)
//List("foo", "bar", "baz").map(_.toUpperCase())
List("foo", "bar", "baz").map(n => n.toUpperCase())
11、初始化默认值:default value
var i: Int = _
12、作为参数名:
//访问map
var m3 = Map((1,100), (2,200))
for(e<-m3) println(e._1 + ": " + e._2)
m3 filter (e=>e._1>1)
m3 filterKeys (_>1)
m3.map(e=>(e._1*10, e._2))
m3 map (e=>e._2)
指代一个集合中的每个元素
例如我们要在一个Array a中筛出偶数,并乘以2:a.filter(_%2==0).map(2*_)。
又如要对缓冲数组ArrayBuffer b排序,可以这样:val bSorted = b.sorted(_)
在元组中,可以用方法_1, _2, _3访问组员。如(1,2)._2。其中句点可以用空格替代。
Note: 改成python语法的话就要使用lambda表达式了,或者直接使用列表解析。
13、参数序列:parameters Sequence 
_*作为一个整体,告诉编译器你希望将某个参数当作参数序列处理。例如val s = sum(1 to 5:_*)就是将1 to 5当作参数序列处理。
//Range转换为List
List(1 to 5:_*)
//Range转换为Vector
Vector(1 to 5: _*)
//可变参数中
def capitalizeAll(args: String*) = {
  args.map { arg =>
    arg.capitalize
  }
}
val arr = Array("what's", "up", "doc?")
capitalizeAll(arr: _*)
这里需要注意的是,以下两种写法实现的是完全不一样的功能:
foo _               // Eta expansion of method into method value
foo(_)              // Partial function application
Example showing why foo(_) and foo _ are different:
trait PlaceholderExample {
  def process[A](f: A => Unit)
  val set: Set[_ => Unit]
  set.foreach(process _) // Error 
  set.foreach(process(_)) // No Error
}
In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).
In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.
This may well be the trickiest gotcha in Scala I have ever encountered.
from: http://blog.csdn.net/pipisorry/article/details/52913548
ref:
Scala:函数式编程之下划线underscore的更多相关文章
- 9、scala函数式编程-集合操作
		一.集合操作1 1.Scala的集合体系结构 // Scala中的集合体系主要包括:Iterable.Seq.Set.Map.其中Iterable是所有集合trait的根trai.这个结构与Java的 ... 
- scala 函数式编程之集合操作
		Scala的集合体系结构 // Scala中的集合体系主要包括:Iterable.Seq.Set.Map.其中Iterable是所有集合trait的根trai.这个结构与Java的集合体系非常相似. ... 
- Scala函数式编程进阶
		package com.dtspark.scala.basics /** * 函数式编程进阶: * 1,函数和变量一样作为Scala语言的一等公民,函数可以直接赋值给变量: * 2, 函数更长用的方式 ... 
- Scala函数式编程——近半年的痛并快乐着
		从9月初啃完那本让人痛不欲生却又欲罢不能的<七周七并发模型>,我差不多销声匿迹了整整4个月.这几个月里,除了忙着讨食,便是继续啃另一本"锯著"--<Scala函数 ... 
- Scala实战高手****第5课:零基础实战Scala函数式编程及Spark源码解析
		Scala函数式编程 ----------------------------------------------------------------------------------------- ... 
- Scala函数式编程(三) scala集合和函数
		前情提要: scala函数式编程(二) scala基础语法介绍 scala函数式编程(二) scala基础语法介绍 前面已经稍微介绍了scala的常用语法以及面向对象的一些简要知识,这次是补充上一章的 ... 
- Scala函数式编程(四)函数式的数据结构  上
		这次来说说函数式的数据结构是什么样子的,本章会先用一个list来举例子说明,最后给出一个Tree数据结构的练习,放在公众号里面,练习里面给出了基本的结构,但代码是空缺的需要补上,此外还有预留的test ... 
- Scala函数式编程(四)函数式的数据结构  下
		前情提要 Scala函数式编程指南(一) 函数式思想介绍 scala函数式编程(二) scala基础语法介绍 Scala函数式编程(三) scala集合和函数 Scala函数式编程(四)函数式的数据结 ... 
- 大数据笔记(二十五)——Scala函数式编程
		===================== Scala函数式编程 ======================== 一.Scala中的函数 (*) 函数是Scala中的头等公民,就和数字一样,可以在变 ... 
随机推荐
- C# WinForm 富文本编辑器 用kindeditor实现本地图片只选取不上传到编辑器
			以下资料有参考网上其它童鞋作品,原作者看到务喷!!!! 以下资料有参考网上其它童鞋作品,原作者看到务喷!!!! 重要的事只要说两遍... 网上找了几天关于WinForm富文本编辑效果都不理想,各种坑, ... 
- 0308-标签的用法(a,ul/ol,table)
			标签分为: 一般标签:<div> <span> <br/> <hr/> 功能标签:<a> <img> 实体标签:≶ > s ... 
- [LeetCode] Max Chunks To Make Sorted 可排序的最大块数
			Given an array arr that is a permutation of [0, 1, ..., arr.length - 1], we split the array into som ... 
- 机器学习技法:12 Neural Network
			Roadmap Motivation Neural Network Hypothesis Neural Network Learning Optimization and Regularization ... 
- Android ART、Dalvik在multidex上的差异、关联
			为提升应用运行性能,谷歌官方从5.0(api level:21)版本开始,将虚拟机运行环境默认为ART, 此处主要研究ART.Dalvik在multidex处理上的差异和关联,做了一个简单的手绘,如下 ... 
- EventBus InMemory 的实践基于eShopOnContainers (二)
			前言 最近在工作中遇到了一个需求,会用到EventBus,正好看到eShopOnContainers上有相关的实例,去研究了研究.下面来分享一下用EventBus 来改造一下我们上篇Event发布与实 ... 
- [HNOI2016]大数
			题目描述 小 B 有一个很大的数 S,长度达到了 N 位:这个数可以看成是一个串,它可能有前导 0,例如00009312345.小B还有一个素数P.现在,小 B 提出了 M 个询问,每个询问求 S 的 ... 
- Linux设备树语法详解【转】
			转自:http://www.cnblogs.com/xiaojiang1025/p/6131381.html 概念 Linux内核从3.x开始引入设备树的概念,用于实现驱动代码与设备信息相分离.在设备 ... 
- Linked List Cycle II--寻找单链表中环的起始点
			题目要求 Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. ... 
- 《Java技术》第一次作业——Java语言基础
			学习总结 Scanner类实现基本数据输入的方法 Scanner 使用分隔符模式将其输入分解为标记,默认情况下该分隔符模式与空白匹配.然后可以使用不同的 next 方法将得到的标记转换为不同类型的值. ... 
