Functional Programming Fundamentals in Scala (iii)

Source: Internet
Author: User
Tags traits

Mainly from the Coursera course "functional programming Principles in Scala"by Professor Martin Odersky, the inventor of the Scala language.

3. Data and Abstraction3.1 Class hierarchies

This set of subtitles is out -,- of sync, listening to a little effort!

The concept of a class is similar to that of other languages, such as base class, subclass, and parent class. In Scala, all user-defined classes are subclasses of another class, and if the parent class is not explicitly given, the Java default inheritance Java.lang,scala inside is Object. Regardless of whether the methods in the base class have been implemented specifically, can the subclasses be override redefined and recalled the powerful before toString ?

Give an example of a binary tree:

Package Week3object insets {val t1 = new nonempty (3, Empty, empty)//> t1:week3.  nonempty = {. 3.} Val t2 = T1 incl 4//> t2:week3.  Intset = {. 3{.4.}} val t3 = new nonempty (5, empty, empty)//> t3:week3.  nonempty = {. 5.} T2 Union T3//> res0:week3. Intset = {{. {. 3.} 4.}5.}} Abstract class Intset {//Abstracts as base class, cannot be instantiated, defines three interfaces def contains (x:int): Boolean//Find contains x def incl (x:int): Intset// If x does not exist, put X into the binary Tree Def Union (x:intset): Intset//Two tree Fusion}object empty extends Intset {//Empty is Intset subclass, ' Object ' represents a singleton pattern, and all empty nodes can represent def contains (X:int) with an object: Boolean = False def incl (x:int): Intset = new nonempty (x, Empty, EMPTY) def Union (other:intset): Intset = other override def toString = "."//Empty node print "."} Class nonempty (Elem:int, Left:intset, Right:intset) extends Intset {def contains (x:int): Boolean = if (x < ele m) left contains x else if (x > Elem) rIght contains x else true def incl (x:int): Intset =//actually creates a new tree, the new tree and the old tree share the unchanged subtree//This is called persistent data structur E, is one of the keys to extending functional programming to collections.//Anyway, that's what he said. '-,-' if (x < elem) New nonempty (Elem, left incl X, right)//one heavy-weight copy section Point else if (X > Elem) New nonempty (Elem, left, right incl X) Else this def Union (other:intset): Intset = ((le FT Union right) union other) incl Elem//override def toString = ' {' + left + elem + right + '} '//powerful recursion}
3.2 How Classes is organized

Never learned Java, the estimate is the same as the package management in Java.

At the top of the source code package week3 , the object or class that represents the file belongs to this package. To use a certain class, the full name can be used in the source code, week3.classA or like Python at the beginning of import, the middle of the source code with the class name:

    • Import Week3.classa: Importing class ClassA
    • Import Week3. {ClassA, ClassB}: Import of two classes
    • Import week3._: Importing package All (wildcard import method)

In addition to importing from a package, you can import from an object. All Scala programs import some entities by default, such as Object,scala in Int,java.lang in Scala. Assertions in Predef, and so on. More information can be found in Scala's standard library.

In Java and Scala, a class can have only one parent class (single inheritance), how to implement multiple inheritance, and Scala uses traits. Trait like Java interface, partial abstraction, but more powerful, can contain field and concrete method, but cannot have the value parameter. Subclasses can inherit only one parent class, but can inherit any number of traits, for example: class Square extends Shape with Planar with Moveble .

Scala types are structured as follows, solid lines represent inheritance, and dashed lines represent implicit conversions.

    • Anyis the basic class of all types, including the following methods: ' = = ', '! = ', ' equals ', ' hashcode ', ' toString '
    • AnyValis the base class for numeric types.
    • AnyRefis the base class for all reference types and is also an alias for Java.lang.Object.
    • Nothingis a subtype of all classes. The main function is an empty element in the exception class and collection.
    • Nullis a subtype of all classes. However, it is incompatible with anyval subtypes.

Q: if (true) 1 else False What is the return type?
A:int and Boolean type, returning the parent class Anyval.

3.3 Polymorphism

Polymorphism means that functions can appear in multiple types. A PPT summary polymorphism:

Suppose we want to create a list class that may contain different data types (integers, booleans, list types, etc.), as in the following example:

This is a generic type to represent. Create a new package called WEEK4, where you create a new trait. Its two ' subclasses ' are Cons and Nil, respectively, representing the node containing the element and the empty node.

package week4// [T] 是类型参数,比如int,double之类。是泛型编程的基础trait List[T] {  def isEmpty: Boolean  def head: T  def tail: List[T]}class Cons[T](val head: T, val tail: List[T]) extends List[T] {  def isEmpty = false  // head 和 tail 已经在初始化中实现}class Nil[T] extends List[T] {  def isEmpty = true  def head: Nothing = throw new NoSuchElementException("Nil.head")  // Nothing 是任何类型的子类,所以也是 T 的子类  def tail: Nothing = throw new NoSuchElementException("Nil.tail")}

Create a new Scala worksheet in Week4 and test the code above:

package week4import week4._object nth {  // 创建一个含有一个元素的 list  def singleton[T](elem: T) = new Cons(elem, new Nil)        //> singleton: [T](elem: T)week4.Cons[T]  singleton[Int](3)         //> res0: week4.Cons[Int] = [email protected]  singleton(3) // 编译器可以从 3 推到出 T 是 Int   // 寻找 list 中的第 n 个元素  def nth[T](n: Int, xs: List[T]): T =    if (xs.isEmpty) throw new IndexOutOfBoundsException    else if (n == 0) xs.head    else nth(n - 1, xs.tail)        //> nth: [T](n: Int, xs: week4.List[T])T  // 创建一个 list  = [1, 2, 3]  val list = new Cons(1, new Cons(2, new Cons(3, new Nil)))  nth(2, list)         //> res2: Int = 3}
Xiao Kee

Here is the approximate content of the first four times of the course, because the initial lesson is to teach you how to install, so the actual content only three classes, followed by four classes. Generally speaking, functional programming gives a lot of inspiration, but if it is not really needed, it is not appropriate to take up too much time to learn. Summer vacation to internship, and so on after the next semester to learn it.

Functional Programming Fundamentals in Scala (iii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.