Scala 函数式编程(By examples)

来源:互联网 发布:淘宝商品上架下架时间 编辑:程序博客网 时间:2024/06/08 18:21

1. 函数式编程思想(functional programming)

In computer science,functional programming is a programming paradigm–a style of building the structure and elements of computer programs–that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.
在计算机科学领域,函数式编程是一种编程范式,它是一种构建计算机程序结构的方法和风格,它把程序当做数学函数的求值过程并且避免了改变状态和可变的数据。

2. 函数式编程的重要概念:

纯函数(Pure Function),或函数的纯粹性(Purity),没有副作用(Side Effect)。
副作用是状态的变化(mutation):例子:修改全局变量,抛出异常,IO读写,调用有副作用的函数。
引用透明(Referential Transparency):对于相同的输入,总是得到相同的输出。

3. 环境配置参考这篇博文

eclipse环境搭建之五:Scala - 细雨潜行 - CSDN博客

http://blog.csdn.net/yuanguangyu1221/article/details/50889522

4.cmd测试

scala> print("hello word")hello wordscala> val x1 = 1x1: Int = 1scala> :quit

eclipse测试

object Helloword { println("Welcome to the Scala worksheet")                              //> Welcome to the Scala worksheet  val x = 1                                       //> x  : Int = 1  println(x)                                      //> 1}

5.Scala类型体系

三种变量修饰符

  • val 定义 immutable variable(常量)
  • var 定义 mutable variable(变量)
  • lazy val (定义惰性求值的常量)

这里写图片描述

1.Numeric Types有以下几种:

注:低精度数值类型向高精度数值类型赋值时不需要类型转换。反之则出现错误。

scala> val a:Byte= 10a: Byte = 10scala> val b:Short = 20b: Short = 20scala> val c:Int= 30c: Int = 30scala> val d:Long = 40d: Long = 40scala> val e:float=50scala> val e:Float= 50e: Float = 50.0scala> val f : Double = 80.7865f: Double = 80.7865

2.Boolean Types:

scala> val m = truem: Boolean = truescala> val n =falsen: Boolean = false

3.Char Unit Types:

scala> val q = 'q: Char = Xscala> val u:Uniu: Unit = ()/* Unit相当于java里面的void,相当于一个空的返回值 */scala> val p=()p: Unit = ()

4 .Nothing(Scala中使用Nothing) Null Types

Null:引用类型值为空,与java中使用一样
Nothing:程序异常终止一般(Scala中使用Nothing)

scala> def foo() = throw new Exception("error occured")foo: ()Nothing

5.String Types

String:构建于Java的String之上
新增了字符串插值(interpolation)的特性

scala> val name="xiaoming"name: String = xiaoming                                      scala> s"my name is ${name}" //给字符串中插入一个值res3: String = my name is xiaoming

6.代码块(Block)

block结构:
第一种具有多个表达式用分号隔开:
{exp1;exp2;exp3}
第二种只有一个表达式:
{
exp
exp
}
Block也是一个表达式,其最终求得的值是最后一个表达式的值。

7.函数

函数定义:

def funcName(paranName:paramType):returnType={//function body:expressions}
object function {  def hello(name:String):String = {  s"Hello,${name}"  }                                               //> hello: (name: String)String  hello("xiaoming")                               //> res0: String = Hello,xiaoming  def hello2(name:String)={    s"Hello,${name}"  }                                               //> hello2: (name: String)String  hello2("xiaohong")                              //> res1: String = Hello,xiaohong  def add(x:Int,y:Int)= x + y                     //> add: (x: Int, y: Int)Int  /* 这里的花括号可以省略 */  add(1,2)                                        //> res2: Int = 3}

8.if,for表达式

注:if在这里是表达式不是语句

这里写图片描述

for 表达式:实现循环

for{    x<-xs    y=x + 1    if(y>0)}yield y

eg:

object forexamples {  val l = List("Jack","Peter","Lucy")             //> l  : List[String] = List(Jack, Peter, Lucy)  for(  s <- l //generator  /*循环遍历List赋给s*/  )println(s)                                     //> Jack                                                  //| Peter                                                  //| Lucy for(  s <- l  if(s.length>3) //filter  )println(s)                                     //> Jack                                                  //| Peter  val result_for = for{  s <- l  s1=s.toUpperCase() //variable binding  if(s1 != "")  }yield (s1)                                     //> result_for  : List[String] = List(JACK, PETER, LI)}                                                  

9.try{} catch{} finally{}

这里写图片描述

这里写图片描述

eg:

object examples {   val result_try = try {        Integer.parseInt("dog")    }catch{    case _ => 0    }finally{    println("always be printed")  //> always be printed    }                            //| result_try  : Int = 0 val code = 1                           //> code  : Int = 1 val result_match = code match{ case 1 => "one" case 2 =>  "two" case _ => "others"  }                      //> result_match  : String = one }
原创粉丝点击