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]的更多相关文章

  1. 【原】Scala学习资料

    Scala是基于JVM的一种通用函数式也是面向对象编程语言,能和Java.C#等主流的编程语言无缝融合. 下面给大家推荐一些Scala的学习资料,序号靠前的重要性比较高. 1.Scala初学指南 (1 ...

  2. Scala 学习笔记(1)之入门篇

    Scala is pronounced skah-lah. Scala 全称为 scalable language,是一种面向对象(object)- 函数式(functional)静态类型(stati ...

  3. Coursera公开课Functional Programming Principles in Scala习题解答:Week 2

    引言 OK.时间非常快又过去了一周.第一周有五一假期所以感觉时间绰绰有余,这周中间没有假期仅仅能靠晚上加周末的时间来消化,事实上还是有点紧张呢! 后来发现每堂课的视频还有相应的课件(Slide).字幕 ...

  4. Coursera scala课程第一周答案

    Exercise 1: Pascal's Triangle The following pattern of numbers is called Pascal's triangle. 1 1 1 1 ...

  5. Scala初探:新潮的函数式面向对象语言

    Scala的基本概念 先讲讲Scala里头几个概念Classes, Traits, Objects and Packages. Class和Java中的很像,只不过Scala中Class不能有stat ...

  6. Scala 中的函数式编程基础(三)

    主要来自 Scala 语言发明人 Martin Odersky 教授的 Coursera 课程 <Functional Programming Principles in Scala>. ...

  7. Scala 中的函数式编程基础(二)

    主要来自 Scala 语言发明人 Martin Odersky 教授的 Coursera 课程 <Functional Programming Principles in Scala>. ...

  8. Scala 中的函数式编程基础(一)

    主要来自 Scala 语言发明人 Martin Odersky 教授的 Coursera 课程 <Functional Programming Principles in Scala>. ...

  9. mac平台scala开发环境搭建

    到scala官网,下载scala的sdk,地址:http://www.scala-lang.org/download/ adeMacBook-Pro:scala- apple$ wget http:/ ...

随机推荐

  1. Tensorflow serving with Kubernetes

    1.Build docker image 由于自己build镜像总是遇到问题,此处暂时借用dockerhub上的一个镜像 docker.io/mochin/tensorflow-serving 将此镜 ...

  2. 【awk】提取文件第一列

    生信数据文件一般是按列分开的,如果我们只想简单的提取一列而不是费尽周折写个程序提取哪一列的话,awk作为一个非常好用的文档处理工具,我们现在来简单看一下他的一些功能: awk '{print $1}' ...

  3. QComboBox列表项高度设置

    QComboBox列表项高度设置步骤: 1. 设置代理 QStyledItemDelegate *delegate = new QStyledItemDelegate(this); ui->co ...

  4. linux基础之正则表达式

    一.基本正则表达式 字符匹配 . : 匹配任意单个字符 [] : 匹配中括号中的任意单个字符 [^] : 匹配指定范围外的任意单个字符 空白字符:[:space:].数字:[:digit:].小写字母 ...

  5. 使用MyBatis Generator 1.3.7自动生成代码

    MyBatis Generator是一款mybatis自动代码生成工具,可以通过配置后自动生成文件. MyBatis Generator有几种方法可以生成代码,下面是其中一种.  一.官网下载 MyB ...

  6. 20175312 2018-2019-2 《Java程序设计》第2周学习总结

    20175312 2018-2019-2 <Java程序设计>第2周学习总结 教材学习内容总结 已依照蓝墨云班课的要求完成了第二.三章的学习,主要的学习渠道是视频,和书的课后习题. 总结如 ...

  7. java笔记 -- java运算

    运算符: 算术运算符: 加减乘除求余 + , - , * , / , % 当参与/运算的两个操作数都是整数时, 表示整数除法, 否则表示浮点除法. 例: 15 / 2 = 7; 15 % 2 = 1; ...

  8. Android View 阴影的总结

    关于 Android 阴影,大家肯定不陌生的.但是Android 中到底有多少种方式可以实现阴影效果以及各种方式之间有什么区别和优缺点,这就是我想总结的.下面我们一个一个来说: 一.各种实现阴影的方式 ...

  9. POJ 3984(DFS入门题 +stack储存路径)

    POJ 3984 Description 定义一个二维数组: int maze[5][5] = { 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, ...

  10. 第 8 章 容器网络 - 069 - Calico 的默认连通性

    相同calico 网络之间的连通性 测试一下 bbox1 与 bbox2 的连通性: ping 成功,数据包流向如下图所示. 1)根据 bbox1 的路由表,将数据包从 cal0 发出. 2)数据经过 ...