[Scala] [Coursera]
Week 1
Cheat Sheet
Evaluation Rules
- Call by value: evaluates the function arguments before calling the funtion
- Call by name: evaluates the function first, and then evaluates the arguments if need be
val example = 2 // evaluated immediately
def example = 2 //evaluated when called
laze val example = 2 // evaluated once when needed def square(x : Double) // call by value
def square(x: => Double) // call by name
def myFct(bindings: Int*) = { ... } // bindings is a sequence of int, containing a varying # of arguments
Higher order functions
- Higher order functions are functions that take a function as a paremeter or return functions.
// sum() returns a function that takes two integers and returns an integer
def sum(f: Int => Int): (Int, Int) => Int = {
def sumf(a: Int, b: int): Int = {...}
sumf
} // same as above. Its type is (Int => Int) => (Int, Int) => Int
def sum(f: Int => Int)(a: Int, b: Int): Int = {...} // called like this
sum((x: Int) => x * x * x) // Anonymous function, i.e. does not have a name
sum(x => x * x * x) // Same anonymous function with type inferred def cube(x: Int) = x * x * x
sum(x => x * x * x)(1, 10) // sum of cubes from 1 to 10
sum(cube)(1, 10) // same as above
Currying
- Curring is converting a function with multiple arguments into a function with a single argument that returns another function.
def f(a: Int, b: Int): Int // uncurried version(type is (Int, Int) => Int)
def f(a: Int)(b:Int): Int // curried version(type is Int => Int => Int)
Classes
class MyClass(x: Int, y: Int) {
require(y > 0, "y must be positive") // precondition, triggering an IllegalArgumentException if not met def this(x: Int) = {...} // auxiliary construtor def nb1 = x // public method computed every time it is called
def nb2 = y private def test(a: Int): Int = {...} val nb3 = x + y // computed only once
override def toString = member1 + "," + member2
} new MyClass(1, 2)
Class hierarchies
- to create an runnable application in scala
object Hello {
def main(args: Array[String]) = println("H")
} // or object Hello extends App {
println("H")
}
Class Organization
- Classes and objects are organized in pakages.
- Traits are similar to Java interfaces, except they can have non-abstract members:trait Planar { ... } class Square extends Shape with Planar.
- General object hierarchy:
- scala.Any is base type of all types. Has methods hashCode and toString that can be overridden.
- scala.AnyVal is base type of all primitive types, such as scala.Double, scala.Float, etc.
- scala.AnyRef is base type of all reference types. Alias of java.lang.Object, supertype of java.lang.String, scala.List, any user-defined class.
- scala.Null is a subtype of scala.AnyRef(null is the only instance of type Null), and scala.Nothing is a subtype of any other type without any instance.
Pattern Matching
- Pattern matching is used for decomposing data structures.
unknownObject match {
case MyClass(n) => ...
case MyClass2(a, b) => ...
} (someList: List[T]) match {
case Nil => ... // empty list
case x :: Nil => ... // list with only one element
case List(x) => ... // same as above
case x :: xs => ... // a list with at least one element. x is bound to the head, xs to the tail. xs could be Nil or some other list
case 1 :: 2 :: cs => ... // list that starts with 1 and then 2
case (x, y) :: ps) => ... // a list where the head element is a pair
case _ => ... // default case if none of the above matches
}
Options
- Pattern matching can also be used for Option values.
- Some functions (like map.get) return a value of type Option[T] which is either a value of the type Some[T] or the value None
val myMap = Map("a" -> 42, "b" -> 43)
def getMapValue(s: Stringf): String = {
myMap get s match {
case Some(nb) => "Value found: " + nb
case None => "None value found"
}
} getMapValue("a") // "Value found: 42"
getMapValue("c") // "No value found" - Most of the times when u write a pattern match on an option value, the same expression can be written more concisely using combinator methods of the Option class. Eg:
def getMapValue(s: String): String = myMap.get(s).map("Value found: " + _).getOrElse("No value found")
Pattern Matching in Anonymous Functions
val pairs: List[(Char, Int)] = ('a', 2) :: ('b', 3) :: Nil
val chars: List[Char] = pairs.map(p => p match {
case (ch, num) => ch
}) // or instead:
val chars: Lits[Char] = pairs map {
case (ch, num) => ch
}
Collections
- Scala defines several collection classess
Base Classes
- Iterable (collections u can iterate on)
- Seq (ordered sequences)
- Set
- Map
Immutable Collections
- List (linked list, provides fast sequential access)
- Stream (same as List, expect the tail is evaluated only on demand)
- Vector (array-like type, implemented as tree of blocks, provides fast random access)
- Range (ordered sequence of integers with equal spacing)
- String (Java type, implicitly converted to a character sequence, so you can treat every string like a Seq[Char])
- Map (collection that maps keys to values)
- Set (collection without duplicate elements)
Mutable Collections
- Array (Scala arrays are native JVM arrays at runtime, therefore they are very performant)
- Scala also has mutable maps and sets; these should only be used if there are performance issues with immutable types
- Demo Usage:
val fruitList = List("apples", "oranges", "pears")
// Alternative syntax for lists
val fruit = "apples" :: ("oranges" :: ("pears" :: Nil)) // :: is right-associative
fruit.head // "apples"
fruit.tail // List("oranges", "pears") val empty = List()
val emtpty = Nil val nums = Vector("louis", "frank", "hiromi")
nums(1) // element at index 1, returns "frank", O(logn) time
nums.updated(2, "helena") // new vector with a different string at index 2, complexity O(log(n)) val fruitSet = Set("apple", "banana", "pear", "banana")
fruitSet.size // returns 3 val r: Range = 1 until 5 // 1, 2, 3, 4
val s: Range = 1 to 5 // 1, 2, 3, 4, 5
1 to 10 by 3 // 1, 4, 7, 10 val s = (1 to 6).toSet
s map (_ + 2) // adds 2 to each element of the set val s = "Hello"
s filter(c => c.isUpper) // returns "H" // Operations on sequences
val xs = List(...)
xs.length
xs.last // last element (exception if xs is empty), O(n) time
xs.init // all elements of xs but the last (exception if xs is empty), O(n) time
xs take n // first n elements of xs
xs drop n // the rest of the collection after taking n elements
xs(n) // the nth element of xs, O(n) time
xs ++ ys // concatenation, complexity O(n)
xs zip ys // returns a list of pairs which groups elements with same index together
xs unzip // opposite of zip: returns a pair of two lists
xs.flatMap f // applies the function to all elements and concatenates the result
x +: xs // creates a new collection with leading element x
xs :+ x // creates a new collection with trailing element x
Pairs
val pair = ("answer", 42)
val (label, value) = pair
pair._1
pair._2
[Scala] [Coursera]的更多相关文章
- 【原】Scala学习资料
Scala是基于JVM的一种通用函数式也是面向对象编程语言,能和Java.C#等主流的编程语言无缝融合. 下面给大家推荐一些Scala的学习资料,序号靠前的重要性比较高. 1.Scala初学指南 (1 ...
- Scala 学习笔记(1)之入门篇
Scala is pronounced skah-lah. Scala 全称为 scalable language,是一种面向对象(object)- 函数式(functional)静态类型(stati ...
- Coursera公开课Functional Programming Principles in Scala习题解答:Week 2
引言 OK.时间非常快又过去了一周.第一周有五一假期所以感觉时间绰绰有余,这周中间没有假期仅仅能靠晚上加周末的时间来消化,事实上还是有点紧张呢! 后来发现每堂课的视频还有相应的课件(Slide).字幕 ...
- Coursera scala课程第一周答案
Exercise 1: Pascal's Triangle The following pattern of numbers is called Pascal's triangle. 1 1 1 1 ...
- Scala初探:新潮的函数式面向对象语言
Scala的基本概念 先讲讲Scala里头几个概念Classes, Traits, Objects and Packages. Class和Java中的很像,只不过Scala中Class不能有stat ...
- Scala 中的函数式编程基础(三)
主要来自 Scala 语言发明人 Martin Odersky 教授的 Coursera 课程 <Functional Programming Principles in Scala>. ...
- Scala 中的函数式编程基础(二)
主要来自 Scala 语言发明人 Martin Odersky 教授的 Coursera 课程 <Functional Programming Principles in Scala>. ...
- Scala 中的函数式编程基础(一)
主要来自 Scala 语言发明人 Martin Odersky 教授的 Coursera 课程 <Functional Programming Principles in Scala>. ...
- mac平台scala开发环境搭建
到scala官网,下载scala的sdk,地址:http://www.scala-lang.org/download/ adeMacBook-Pro:scala- apple$ wget http:/ ...
随机推荐
- web前端开发常用组件
web前端开发常用组件 1. 对话框(dialog):jbox(适合对话框等其它功能).colorbox(也很强大,可以弥补jbox图片轮播的落点), 这二者基本能搞定所有对话框的情况 2. ...
- nginx-负载均衡相关配置 第五章
一.负载均衡: 通过反向代理客户端的请求到一个服务器群组,通过某种算法,将客户端的请求按照自定义的有规律的一种调度调度给后端服务器. Nginx的负载均衡使用upstream定义服务器组,后面跟着组名 ...
- Docker Kubernetes 创建管理 Pod
Docker Kubernetes 容器扩容与缩容 环境: 系统:Centos 7.4 x64 Docker版本:18.09.0 Kubernetes版本:v1.8 管理节点:192.168.1.79 ...
- final修饰符与多态
知识点一.final 最终的可以修饰属性.方法.类1.final修饰的属性,表示常量,初始化以后值不能改变.final修饰引用数据类型的变量,引用地址不能改变.2.final修饰类,不能被继承.比如: ...
- 剑指offer(30)连续子数组和的最大值
题目描述 HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学.今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决.但是,如果向量 ...
- webpack 与 vue 打包体积优化
webpack 与 vue 在使用vue开发时,遇到打包后单个文件太大,因而需要分包,不然加载时间太久.虽然尽可能减少请求次数,但是单个包太大也不是好事 思路 组件按需加载 vue-router 的懒 ...
- MapReduce编程:单词去重
编程实现单词去重要用到NullWritable类型. NullWritable: NullWritable 是一种特殊的Writable 类型,由于它的序列化是零长度的,所以没有字节被写入流或从流中读 ...
- Qt打开文件对话框同时选中多个文件或单个文件
Qt中打开单个文件 //str_path为文件路径 QString str_path = QFileDialog::getOpenFileName(this, tr("选择转码文件" ...
- 【Python】【内置函数】
[fromkeys()] -- coding: utf-8 -- python 27 xiaodeng python之函数用法fromkeys() fromkeys() 说明:用于创建一个新字典,以序 ...
- react-native android/ios 根据配置文件编译时自动修改版本号
开发react-native时大都有过这个操作,当版本迭代时候要修改app版本号时,一般都这样做 Android: 的要修改build.gradle文件的versionName ios: 打开xcod ...