Scala7

Working with Lists

  • 这一章主要介绍List的一些common operation, 还介绍一些 design principles for programs working on lists

  • Lists和数组很像,但是有两点不同: 1. lists是immutable而数组则是mutable,即不能对一个list中元素重新赋值而只能重新构造一个新的list。 2. lists是递归构建出来的,每一个list由一个head以及一个list类型的tail构造,而数组则是flat

  • 类似于数组,List也只能包含同类型的数据。list的类型在Scala中是 covariant,意思就是 for each pair of types S and T, if S is subtype of T, then List[S] is a subtype of List[T].

  • 可以使用::来构建List,::生成一个新的List,这个新List以左边元素作为新的head,右边的List作为tail

  • List的基本操作包括:

    1. head

    2. tail

    3. isEmpty

  • List也支持pattern matching. You can either match on all elements of a list using a pattern of the form List(…), or you take lists apart bit by bit using patterns composed from the :: operator and the Nil constant.

  • First-order methods on List 包括:

    1. :::(Concatenating lists) - Like cons, list concatenation associates to the right

    2. The Divide and Conquer principle

    3. Taking the length of a list: length

    4. Accessing the end of a list: init and last

    5. Reversing lists: reverse

    6. Prefixes and suffixes: drop, take and splitAt

    7. Element selection: apply - support random element selection , indices

    8. Zipping lists: zip

    9. Displaying lists: toString and mkString

    10. Converting lists: elements, toArray, copyToArray

  • List还支持 Higher-order methods,这些Higher-order methods包括了:

    1. Mapping over lists:mapflatMap,and foreachMap returns the list resulting from applying the function f to each list element in xs, but flatMap applies the function to each list element and returns the concatenation of all function results. Foreach takes a procedure whose result type Unit

    2. Filtering lists: filterpartitionfindtakeWhiledropWhile, and span – . The span method combines takeWhile and dropWhile in one operation

    3. Predicates over lists: forall and exists

    4. Folding lists: /: and :\

  • 上述method都是定义在List这个class中,同时Scala还定义了一些在在object List中的方法,这些一般都是factory method,以及一些operations that work on lists of some specific shape.

    1. Creating lists from their elements: List.apply

    2. Creating a range of numbers: List.range

    3. Creating uniform lists: List.fill - List.make has been depreacted

    4. List.unzip and List.flatten have been depreacted, instead they have be constructed as a method of class List

    5. Concatenating lists: List.concat

  • 这一章除了介绍List的一些基本操作之外,还额外介绍了Scala的 type inference algorithm。下面是一些有关type inference的笔记

  • Type inference in Scala is flow based. In a method application m(args), the inferencer first checks whether the method m has a known type. If it has, that type is used to infer the expected type of the arguments.更一般地情况可以参考下面:

  • Generally, when asked to infer the type parameters of a polymorphic method, the type inferencer consults the types of all value arguments in the first parameter list but no argument beyond that. 也就是说,当推导一个多态方法的类型参数时,类型推导器只会咨询参数列表的第一个参数,所以这里就有一个 library desing principle:

  • When designing a polymorphic method that takes some non-function arguments and a function argument, place the function argument last in a curried parameter list by its own. That way, the method’s correct instance type can be inferred from the non-function arguments, and that type can in turn be used to type check the function argument.

  • 事实上,对于 type system这一部分,我还真是了解不多,要找个时间把相关的资料看下

Collections

  • 上一章主要深入的介绍了List这一collection,那么这一章则主要是广泛介绍其他的collection

  • 首先上一张collection的总体继承关系图
    这里写图片描述

这里有三类collection, sequences(Seqs), sets and maps. Sequences are ordered collections. Sets contain at most one of each object. Map contain a collection of keys mapped to values.

  • 这里有一个易混淆的概念:IterableIterator. 与Iterable不同,Iterator是一个单独的Trait,继承 AnyRef。并且, trait Iterable represents types that can be iterated over(i.e., collection types), whereas trait Iterator is the mechanism used to perform an iteration. 这个从它们的名字也可以看出 able代表了一种能力,or则是一种事物。Although an Iterable can iterated over multiple times, an Iterator can be used just once.

  • Sequences包括有:

SeqsImmutable/Mutable?
ListsImmutable
ArraysMutable
ListBufferMutable
ArrayBufferMutable
QueueBoth
StackBoth
Strings(via RichString)Unknown
  • Sets和Maps都提供了immutable以及mutable,默认都是使用immutable,如果需要mutable,那么则需要显示的import。 Set的使用方法与ptyhon的Set类似,而Map则类似于python的字典

  • 对于mutable的Set和Map,都使用了HastSet、HashMap,而对于immutable,如果元素个数小于5,则返回Setn,为空则返回EmptySet。immutable.Map同理

  • Scala提供了TreeSet、TreeMap,它们分别实现了SortedSet、SortedMap,可以按照顺序组织内部的元素,而这个元素则是由Ordered这个trait定义的

  • Synchronized sets and maps从Scala 2.10就已经被废弃了,目前可以使用 java.util.concurrent 来代替,又或者可以使用Akka (actor也已经被废弃了)

  • 一般地,Scala推荐使用immutable。第一是因为安全,第二是底层实现时,对于small collection,the immutable versions are much more compact than the mutable ones. Scala也提供了很方便的机制,来switch from immutable to mutable。如提供了一种语法糖 +=(本来immutable不支持 +=这种操作),这种情况下可以定义一个var(任然使用immutable object)使用+=操作,那么接下来就会发生: First, a new collection will be created, and then the identifier will be reassigned to refer to the new collection. 那么在这一系列的操作之后,the origin variable will refer to a new immutable collection. 这种语法糖不仅适用于 +=,还适用任何以 = 结尾的方法

  • Scala之所以提供上述的语法糖,是为了减少从immutable到mutable的代价,使得我们一开始可以选择immutable,当需要转换到 mutable 那么只需要显示导入mutable object就行了。 By the way, this syntactic treatment works on any kind of value, not just collections

  • 可以给collection显示的提供类型来 initializing collections

  • 当要将immutable sets or maps转换成 mutable时,或者反之。这里提供了一种方法:比如你有一个mutable collection, 需要转换成a immutable one. 那么可以先创建 an empty immutable collection然后 add the elements of the mutable one via the ++ operator

  • Tuple可以包括不同类型的object,它没有继承 Iterable。一般,当函数需要返回多个值,可以包装成一个Tuple再返回。另外,Tuple也可以用来封装一些信息,当然有时候你需要在以一个Tuple封装还是以一个Class封装来权衡

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值