Scala 安装命令行运行环境

    科技2022-08-20  116

    1.安装Java

    按照最全的步骤进行,JAVA_HOME, CLASSPATH,  path的设置,简记如下:

            (1)下载之后默认安装即可。注意:安装的时候记住你的安装路径。

                      例如我这里的安装路径是:C:\Program Files\Java\jdk1.8.0_171

            (2)新建JAVA_HOME系统变量                  变量名:JAVA_HOME ,变量值:C:\Program Files\Java\jdk1.8.0_171

            (3)新建CLASSPATH变量                  变量名:CLASSPATH , 变量值: .;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar

            (4)配置系统环境变量Path                  双击Path-->新建-->添加“%JAVA_HOME%\bin”-->将这一行变量上移到最顶端-->完成

            (5)应用所有环境变量配置完成之后,应用环境变量即可。

            (6)测试:win+R弹出运行窗口后,输入cmd,回车弹出命令行窗口,分别输入"java -version"、"javac"


    2.安装

    2.1 安装Scala,

            (1)下载网址https://www.scala-lang.org/download/

            (2)单击Download the Scala binaries for windows 保存下载二进制文件

                   Other ways to install Scala

                      Download the Scala binaries for windows

            (3)下载完毕后,双击安装,注意修改安装位置为D:\Scala,否则报错。

             (4)安装完毕后即可在cmd中输入scala启动命令行解释器。

     


    2.2 sbt的安装配置

    (1)安装

    如果使用sbt来编译scala项目,上面的安装scala可以忽略,sbt会自动下载scala所有相关内容,于手动安装的scala是独立的。

    除了按照这个安装步骤执行之外,在该步骤中间插入一个配置步骤:

    不要采用默认的安装路径(C:/D:\Program File...),而是假设sbt安装在了D:\sbt\路径

    在运行任何的sbt命令之前,

    https://docs.scala-lang.org/getting-started/sbt-track/getting-started-with-scala-and-sbt-on-the-command-line.html

     

    (2)配置 :增加一个文件,编辑一个文件。

    第一步:增加如下 D:/sbt/conf/repo.properties

    文件内容为:

    [repositories] local aliyun-central: https://maven.aliyun.com/repository/central aliyun-public: https://maven.aliyun.com/repository/public sbt-plugin: https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly sbt-plugin-releases2: https://dl.bintray.com/sbt/sbt-plugin-releases/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly sonatype: https://oss.sonatype.org/content/repositories/snapshots typesafe: https://repo.typesafe.com/typesafe/ivy-releases/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly typesafe2: https://repo.typesafe.com/typesafe/releases/ jcenter: https://jcenter.bintray.com/ repo1: https://repo1.maven.org/maven2/ store_2: https://repo2.maven.org/maven2/ aliyun-releases: https://maven.aliyun.com/repository/releases aliyun-jcenter: https://maven.aliyun.com/repository/jcenter

    第二步:编辑文件 D:/sbt/conf/sbtconfig.txt

    内容修改为:

    # sbt configuration file for Windows # Set the java args #-mem 1024 was added in sbt.bat as default -Xms1024m -Xmx1024m -Xss4M -XX:ReservedCodeCacheSize=128m # Set the extra sbt options -Dsbt.log.format=true -Dsbt.boot.directory=D:/sbt/boot/ -Dsbt.global.base=D:/sbt/.sbt -Dsbt.ivy.home=D:/sbt/.ivy2 -Dsbt.repository.config=D:/sbt/conf/repo.properties -Dsbt.override.build.repos=true

    倒数第二项的文件名跟第一步中添加的文件相同。

    其他部分不用预设,直接按照官方步骤开始运行含sbt的命令,比如sbt run之类的。第一次编译会现在很多文件,网路比较慢,系统会缓存下来,以后就快了。


    若使用IntelliJ Idea,可参考如下文章:

    https://blog.csdn.net/godenbird312/article/details/103787144


    3. 测试安装效果,

    《Scala编程》代码网址:

    https://www.cs.helsinki.fi/u/wikla/OTS/Sisalto/examples/index.html

     

    简单测试:

    以下都是直接使用Scala命令行工具直接编译运行的方式:

    在E:\的空闲目录保存如下内容至文件   functionValue_9_1.scala中:

     

    object FileMatcher{ private def filesHere = (new java.io.File(".")).listFiles private def filesMatching(query: String, matcher: (String, String)=> Boolean) = { for(file <- filesHere; if matcher(file.getName, query)) yield file } /* def filesEnding(query: String) = filesMatching(query, (x:String, y:String) => x.endsWith(y)) */ def filesEnding(query: String)= filesMatching( query, _.endsWith(_) ) /* def filesContaining(query: String) = filesMatching(query, (x:String, y:String) => x.contains(y)) */ def filesContaining(query: String)= filesMatching(query,_.contains(_)) /* def filesRegex(query: String) = filesMatching(query, (x:String, y:String) => x.matches(y)) */ def filesRegex(query: String) = filesMatching(query, _.matches(_)) } FileMatcher.filesEnding(".scala").foreach(println) //FileMatcher.filesContaining("Lines").foreach(println) //FileMatcher.filesRegex("(.*)Li(.*)").foreach(println)

     

    并在CMD Console 中cd至刚刚保存的Scala源文件目录中,并执行:

    scala   functionValue_9_1.scala

    应该打印出类似如下一行 

    .\functionValue_9_1.scala

     

    同样的功能,也可以使用下面这段,体现了闭包化简思路:

     

    object FileMatcher{ private def filesHere = (new java.io.File(".")).listFiles private def filesMatching( matcher: (String)=> Boolean) = { for(file <- filesHere; if matcher(file.getName)) yield file } /* def filesEnding(query: String) = filesMatching( (fileName:String) => fileName.endsWith(query)) */ def filesEnding(query: String) = filesMatching( _.endsWith(query)) /* def filesContaining(query: String) = filesMatching((fileName:String) => fileName.contains(query)) */ def filesContaining(query: String) = filesMatching(_.contains(query)) def filesRegex(query: String) = filesMatching( (fileName:String) => fileName.matches(query)) /* def filesRegex(query: String) = filesMatching(query, _.matches(_)) */ } //FileMatcher.filesEnding(".scala").foreach(println) //FileMatcher.filesContaining("Lines").foreach(println) FileMatcher.filesRegex("(.*)Li(.*)").foreach(println)

     


    柯里化的示例:

    import java.io.File import java.io.PrintWriter def withPrintWriter(file: File)(op: PrintWriter => Unit)={ val writer = new PrintWriter(file) try{ op(writer) }finally{ writer.close() } } withPrintWriter(new File("logL3.txt")){_.println("hello")}

     

    保存这段代码,并且运行:scala 文件名.scala

     

    object Element { private class ArrayElement( val contents: Array[String] ) extends Element private class LineElement(s: String) extends Element { val contents = Array(s) override def width = s.length override def height = 1 } private class UniformElement( ch: Char, override val width: Int, override val height: Int ) extends Element { private val line = ch.toString * width def contents = Array.fill(height)( line) } def elem(contents: Array[String]): Element = new ArrayElement(contents) def elem(chr: Char, width: Int, height: Int): Element = new UniformElement(chr, width, height) def elem(line: String): Element = new LineElement(line) } /// import Element.elem abstract class Element { def contents: Array[String] def width: Int = contents(0).length def height: Int = contents.length def above(that: Element): Element = { val this1 = this widen that.width val that1 = that widen this.width elem(this1.contents ++ that1.contents) } def beside(that: Element): Element = { val this1 = this heighten that.height val that1 = that heighten this.height elem( for ((line1, line2) <- this1.contents zip that1.contents) yield line1 + line2) } def widen(w: Int): Element = if (w <= width) this else { val left = elem(' ', (w - width) / 2, height) var right = elem(' ', w - width - left.width, height) left beside this beside right } def heighten(h: Int): Element = if (h <= height) this else { val top = elem(' ', width, (h - height) / 2) var bot = elem(' ', width, h - height - top.height) top above this above bot } override def toString = contents mkString "\n" } // //package org.stairwaybook.expr import Element.elem sealed abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(operator: String, left: Expr, right: Expr) extends Expr class ExprFormatter { // Contains operators in groups of increasing precedence private val opGroups = Array( Set("|", "||"), Set("&", "&&"), Set("^"), Set("==", "!="), Set("<", "<=", ">", ">="), Set("+", "-"), Set("*", "%") ) // A mapping from operators to their precedence private val precedence = { val assocs = for { i <- 0 until opGroups.length op <- opGroups(i) } yield op -> i Map() ++ assocs } private val unaryPrecedence = opGroups.length private val fractionPrecedence = -1 private def format(e: Expr, enclPrec: Int): Element = e match { case Var(name) => elem(name) case Number(num) => def stripDot(s: String) = if (s endsWith ".0") s.substring(0, s.length - 2) else s elem(stripDot(num.toString)) case UnOp(op, arg) => elem(op) beside format(arg, unaryPrecedence) case BinOp("/", left, right) => val top = format(left, fractionPrecedence) val bot = format(right, fractionPrecedence) val line = elem('-', top.width max bot.width, 1) val frac = top above line above bot if (enclPrec != fractionPrecedence) frac else elem(" ") beside frac beside elem(" ") case BinOp(op, left, right) => val opPrec = precedence(op) val l = format(left, opPrec) val r = format(right, opPrec + 1) val oper = l beside elem(" "+ op +" ") beside r if (enclPrec <= opPrec) oper else elem("(") beside oper beside elem(")") } def format(e: Expr): Element = format(e, 0) } / //import org.stairwaybook.expr._ object Express extends App { val f = new ExprFormatter val e1 = BinOp("*", BinOp("/", Number(1), Number(2)), BinOp("+", Var("x"), Number(1))) val e2 = BinOp("+", BinOp("/", Var("x"), Number(2)), BinOp("/", Number(1.5), Var("x"))) val e3 = BinOp("/", e1, e2) def show(e: Expr) = println(f.format(e)+ "\n\n") for ( e <- Array(e1, e2, e3)) show(e) }

     


    保存并运行这段递归插入排序法的代码:  scala   文件名.scala

    /* def isort(xs: List[Int]):List[Int] = if(xs.isEmpty) Nil else insert(xs.head, isort(xs.tail)) def insert(x: Int, xs: List[Int]): List[Int] = if(xs.isEmpty || x <= xs.head ) x::xs else xs.head:: insert(x, xs.tail) */ def isort(xs: List[Int]):List[Int] = xs match{ case List() => List() case x::xs1 => insert(x, isort(xs1)) } def insert(x: Int, xs: List[Int]): List[Int] = xs match{ case List() => x::List() case y::ys => if(x<=y) x::xs else y::insert(x, ys) } var lx=List(3,8,6,5,2,7) lx = isort(lx) println(lx)

     


    或者:

    def append[T](xs: List[T], ys: List[T]): List[T] = xs match{ case List() => ys case x::xs1 => if(xs1.isEmpty) x::ys//为何本行多余? else x::append(xs1, ys) } var lx=List(2,3,7,4,3) var ly=List(0,4,7,9) println(append[Int](lx, ly))

     

     

     

     

     

    Processed: 2.786, SQL: 9