一、queue佇列是fifo(先進先出),queue分可變和不可變(immutable queue and mutable queue)
使用+=、++=、enqueue來新增元素import scala.collection.mutable.queue
var ints = queue[int]()
var fruits = queue[string]()
var q = queue[person]()
scala>val q = queue(1, 2, 3)q: scala.collection.mutable.queue[int] = queue(1, 2, 3)
scala> import scala.collection.mutable.queue
import scala.collection.mutable.queue
// create an empty queue
scala> var q = new queue[string]
q: scala.collection.mutable.queue[string] = queue()
// add elements to the queue in the usual ways
scala> var q = new queue[string]
q: scala.collection.mutable.queue[string] = queue()
scala> q += ("kiwi", "banana")
scala> q ++= list("cherry", "coconut")
// can also use enqueue
scala> q
使用dequeue來取出資料,因為是fifo所以取出的資料是從佇列的頭部開始, dequeuefirst, dequeueall可以根據條件取出資料
// take an element from the head of the queue
scala> val next = q.dequeue
scala> q
// take the next element
scala> val next = q.dequeue
next: string = kiwi
// 'kiwi' is removed from the queue
scala> q
二、stack 棧lifo(後進先出),這個和大多數語言一樣新增資料用push、取出資料pop,stack 也分可變和不可變(immutablestack and mutablestack )scala> q.dequeuefirst(_.startswith("b"))
res2: option[string] = some(banana)
scala> q
scala> q.dequeueall(_.length > 6)
11.29. using a queue | 373
scala> q
res5: scala.collection.mutable.queue[string] = queue(cherry)
import scala.collection.mutable.stack
var ints = stack[int]()
var fruits = stack[string]()
case class person(var name: string)
var people = stack[person]()
val ints = stack(1, 2, 3)
// create a stack
scala> var fruits = stack[string]()
fruits: scala.collection.mutable.stack[string] = stack()
// add one element at a time
scala> fruits.push("banana")
// add multiple elements
scala> val next = fruits.pop
scala> fruits
因為pop取資料會刪除掉stack中的資料,所以我們可以使用top來獲取資料
scala> fruits.top
res4: string = orange
// 'orange' is still on the top
scala> fruits
因為stack繼承seq,所以可以使用其中的方法
scala> fruits.size
res6: int = 4
scala> fruits.isempty
res7: boolean = false
//清空棧資料
scala> fruits.clear
scala> fruits
res8: scala.collection.mutable.stack[string] = stack()
scala學習筆記(十一) 高階函式
scala 作為函式式語言,函式自然是頭等公民 乙個接收函式作為引數的函式稱為高階函式 比如定義如下 defvalueatonequarter f double double f 0.25 這個函式接收乙個引數為 double 返回值為 double 的函式作為引數。高階函式還可以是返回乙個函式作為...
Scala學習筆記
scala學習筆記 一.scala中集合的常用方法 首先定義兩個陣列集合,用於測試 scala val arr1 array 1,2,3,4 arr1 array int array 1,2,3,4 scala val arr2 array 3,4,5,6 arr2 array int array ...
Scala學習筆記
1 閉包 var a 3 var addfun x int x a var b addfun 10 println b addfun 就是個和物件無關的函式,區域性變數,使用方法和函式一樣,但是好像不推薦這種寫法。2 類的建立,簡單使用abstract class bparent 構造函式引數會自動...