ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

学习chisel(1): 介绍scala

2022-04-22 12:33:40  阅读:156  来源: 互联网

标签:10 val scala Int max chisel 学习 list


------------------------------------ 一、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.

 

标签:10,val,scala,Int,max,chisel,学习,list
来源: https://www.cnblogs.com/yinhuachen/p/16178355.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有