1. 程式人生 > 其它 >學習chisel(1): 介紹scala

學習chisel(1): 介紹scala

------------------------------------ 一、scala程式碼基本語法和概念------------------------------------------

1. var : 宣告變數  val : 宣告常量

var numberOfKittens = 6      // Int 型別
val kittensPerHouse = 101    // Int 型別
val alphabet = "abcdefghijklmnopqrstuvwxyz"  // String型別
var done = false      // 這個是boolean型別

 

2. println()  列印函式

 

3. if() {} else if() {} else {} 的用法跟C語言非常一致

 

4. 在scala中 if條件語句 是有返回值的,返回值是 “被選擇的那個枝條的最後一行”

eg:

val likelyCharactersSet = if (alphabet.length == 26)
    "english"
else 
    "not english"

println(likelyCharactersSet)  列印的值是“english”

 

5. 定義函式、方法

// Simple scaling function with an input argument, e.g., times2(3) returns 6
// Curly braces can be omitted for short one-line functions. def times2(x: Int): Int = 2 * x    // 定義了引數、和返回值,以及返回值的計算公式 // More complicated function def distance(x: Int, y: Int, returnPositive: Boolean): Int = {    // 花括號的值取決於最後一個語句 val xy = x * y if (returnPositive) xy.abs else -xy.abs }

 

6. scala支援函式過載

1 // Overloaded function
2 def times2(x: Int): Int = 2 * x
3 def times2(x: String): Int = 2 * x.toInt
4 
5 times2(5)
6 times2("7")

注意 x.toInt 可以把string轉換成整數

 

7. scala支援遞迴

 1 /** Prints a triangle made of "X"s
 2   * This is another style of comment
 3   */
 4 def asciiTriangle(rows: Int) {
 5     
 6     // This is cute: multiplying "X" makes a string with many copies of "X"
 7     def printRow(columns: Int): Unit = println("X" * columns)
 8     
 9     if(rows > 0) {
10         printRow(rows)
11         asciiTriangle(rows - 1) // Here is the recursive call
12     }
13 }
14 
15 // printRow(1) // This would not work, since we're calling printRow outside its scope
16 asciiTriangle(6)

由  "X" * columns  可以看到字串做乘法,能夠再得到字串

 

8. scala支援連結串列

 1 val x = 7
 2 val y = 14
 3 val list1 = List(1, 2, 3)
 4 val list2 = x :: y :: y :: Nil       // An alternate notation for assembling a list
 5 
 6 val list3 = list1 ++ list2           // Appends the second list to the first list
 7 val m = list2.length
 8 val s = list2.size
 9 
10 val headOfList = list1.head          // Gets the first element of the list
11 val restOfList = list1.tail          // Get a new list with first element removed
12 
13 val third = list1(2)                 // Gets the third element of a list (0-indexed)

 

9. 

1 for (i <- 0 to 7) { print(i + " ") } // 包括7
2 println()
3 
4 for (i <- 0 until 7) { print(i + " ") } // 不包括7
5 println()
6 
7 for(i <- 0 to 10 by 2) { print(i + " ") }  // 以2為單位
8 println()

 

10.

1 val randomList = List(scala.util.Random.nextInt(), scala.util.Random.nextInt(), scala.util.Random.nextInt(), scala.util.Random.nextInt())
2 var listSum = 0
3 for (value <- randomList) {  // 遍歷randomList
4   listSum += value
5 }
6 println("sum is " + listSum)

 

------------------------------------ 二、如何閱讀scala程式碼 ------------------------------------------

1. 

package mytools
class Tool1 { ... }

When externally referencing code defined in a file (引用外部的程式碼) containing the above lines, one should use:

import mytools.Tool1

Note: The package name should match the directory hierarchy. This is not mandatory, but failing to abide by this guideline can produce some unusual and difficult to diagnose problems. Package names by convention are lower case and do not contain separators like underscores. This sometimes makes good descriptive names difficult. One approach is to add a layer of hierarchy, e.g. package good.tools. Do your best. Chisel itself plays some games with the package names that do not conform to these rules.

As shown above, import statements inform the compiler that you are using some additional libraries. Some common imports you will use when programming in Chisel are:

import chisel3._    // 匯入chisel3包的所有類和方法
import chisel3.iotesters.{ChiselFlatSpec, Driver, PeekPokeTester}    // 從chisel3.iotesters包匯入一些特定的類

The first imports all the classes and methods in the chisel3 package; the underscore here works as a wildcard. The second imports specific classes from the chisel3.iotesters package.

 

2. 定義一個類,叫 WrapCounter

 1 // WrapCounter counts up to a max value based on a bit size
 2 class WrapCounter(counterBits: Int) {
 3 
 4   val max: Long = (1 << counterBits) - 1
 5   var counter = 0L  // 末尾的L表示這是一個long型別
 6     
 7   def inc(): Long = {
 8     counter = counter + 1
 9     if (counter > max) {
10         counter = 0
11     }
12     counter
13   }
14   println(s"counter created with max value $max")  // 頭部的s表示這是一個插入的字串  $max將會被max變數的值替換
15 }

 

3. 建立一個類的例項

 1 val x = new WrapCounter(2)
 2 
 3 x.inc() // Increments the counter
 4 
 5 // Member variables of the instance x are visible to the outside, unless they are declared private
 6 if(x.counter == x.max) {              
 7     println("counter is about to wrap")
 8 }
 9 
10 x inc() // Scala allows the dots to be omitted; this can be useful for making embedded DSL's look more natural    // scala允許忽略dot

 

4. List.map 方法,遍歷所有的int Member,把它們轉化為string,隨後變成一個新的List

1 val intList = List(1, 2, 3)
2 val stringList = intList.map { i =>
3   i.toString
4 }

 

5. 命名引數和預設引數

Named Parameters and Parameter Defaults

Consider the following method definition.

def myMethod(count: Int, wrap: Boolean, wrapValue: Int = 24): Unit = { ... }

When calling the method, you will often see the parameter names along with the passed-in values.

myMethod(count = 10, wrap = false, wrapValue = 23)

Using named parameters, you can even call the function with a different ordering. // 引數的順序可以打亂

myMethod(wrapValue = 23, wrap = false, count = 10)

For frequently called methods, the parameter ordering may be obvious. But for less common methods and, in particular, boolean arguments, including the names with calls can make your code a lot more readable. If methods have a long list of arguments of the same type, using names also decreases the chance of error. Parameters to class definitions also use this named argument scheme (they are actually just the parameters to the constructor method for the class).

When certain parameters have default values (that don't need to be overridden), callers only have to pass (by name) specific arguments that do not use defaults. Notice that the parameter wrapValue has a default value of 24. Therefore,

myMethod(wrap = false, count = 10)  // 由於在定義的時候,給了wrapValue 24的預設值,因此呼叫函式的時候可以直接省略

will work as if 24 had been passed in.