首页 > 代码库 > Scala初探(三)

Scala初探(三)

11. curry化

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>def inject(arr:Array[Int],initial:Int)(operation: (Int,Int) => Int): Int ={
	var carryOver = initial
	arr.foreach(element => carryOver = operation(carryOver,element))

	carryOver
}

val array = Array(2,3,5,1,6,4)
val sum = inject(array,0){
	(carryOver,elem) => carryOver + elem
}

println(sum)</strong></span>

curry化就是函数可以接受多个参数列表,比如上面的例子中就可以接受两个参数列表,而之前的例子都只有一个参数列表。如果要用同样的一组实参多次调用同一个函数,可以用curry化来减少噪音。

11.  set

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>val color = Set("red","blue","green")
var colors = color

println(colors)

colors += "black"
println(colors)

val filterColors = color.filter(_ contains "red")
//mkString为Set的每个元素创建了其字符串表示,然后用逗号链接起来
println(filterColors.mkString(", "))

//两个集合合并使用 ++ 
//交集 **</strong></span>

12. 匹配

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>def activity(day: String){
	day match{
		case "Sunday" => print("Eat,sleep,repeat...")
		case "Saturday" => print("Hangout with friends...")
		case "Monday" => print("...code for fun...")
		case "Friday" => print("...read a good book...")
	}
}

List("Monday","Sunday","Saturday").foreach{activity}</strong></span>

由于正则表达式在语言中区别不大,这里没有使用正则表达式的例子,直接使用字面匹配。

13. 文件读写

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>import java.io._
import scala.io.Source

val writer = new PrintWriter(new File("data.txt"))
writer write "APPL\r"
writer.write("1234")
writer.close()

println("""The content of the file you read is:""" )
Source.fromFile("data.txt").foreach{print}</strong></span>
这里使用了java的io包


14. 网页读取

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>import scala.io.Source
import java.net.URL

val source = Source.fromURL(new URL("http://www.scala-lang.org/docu/files/api/index.html"))

println(source.getLine(3))

val content = source.mkString
println(content)</strong></span>
15. XML

<span style="font-family:KaiTi_GB2312;font-size:18px;"><strong>//xml解析
val xmlFragment = 
<symbols>
	<symbol ticker = "AAPL">
	<units>200</units></symbol>
	<symbol ticker = "IBM">
	<units>215</units></symbol>
</symbols>

//println(xmlFragment)
println(xmlFragment.getClass())

//这里是XML元素的\()方法,让它找出所有symbol元素,只能找出目标元素直接后代的元素
//val symbolNodes = xmlFragment.\("symbol")
val symbolNodes = xmlFragment \ "symbol"

//\\()可以找出目标元素结构里面的所有层次的元素
val unitsNodes = xmlFragment \\ "units"
println(unitsNodes(0).text)

println(symbolNodes.mkString("\n"))
//当成员函数没有参数时,括号可以去掉,下面两种方法都可以
println(symbolNodes.getClass)
println(symbolNodes.getClass())  

//use XML
println("Ticker\nUnits")
xmlFragment match {
	//使用_*把<symbols>和</symbols>之间所有的内容都读到占位符变量symbolNodes里
	case <symbols>{symbolNodes @ _*}</symbols> => for(symbolNode @ <symbol>{_*}</symbol> <- symbolNodes){
		println("%-7s%s".format(
			symbolNode \ "@ticker",(symbolNode \ "units").text))
	}
}

//解析xml文件
import scala.xml._

val stocksAndUnits = XML.load("stocks.xml")
println(stocksAndUnits.getClass())
println("Load file has " + (stocksAndUnits \\ "symbol").size + " symbol elements")

//写xml文件
import scala.xml._

val stocksAndUnits = XML.load("stocks.xml")
val stockAndUnitsMap = 
(Map[String,Int]() /: (stocksAndUnits \ "symbol")){
	(map,symbolNode) => val ticker = (symbolNode \ "@ticker").toString
						val units = (symbolNode \ "units").text.toInt
						map(ticker) = units
						//creates and returns a new Map
}

val updatedStocksAndUnitsXML = 
<symbols>
	{
		stockAndUnitsMap.map{
			updatedStocksAndUnitsXML
		}
	}
</symbols>

def updatedStocksAndCreateXML(element: (String,Int)) ={
	val (ticker,units) = element
	<symbols ticker = {ticker}>
		<units>{units + 1}</units>
	</symbols>
}

XML save ("stocks2.xml",updatedStocksAndUnitsXML)
println("The saved file contains " + (XML.load("stocks2.xml") \\ "symbols").size + " symbol elements")
</strong></span>

XML也是Scala的一等公民,所以不用“”,直接在代码中定义。
 

Scala初探(三)