ラベル scala の投稿を表示しています。 すべての投稿を表示
ラベル scala の投稿を表示しています。 すべての投稿を表示

2014/12/19

scala study memo

・Predef is a great place to start to understand the Scala Library
==>Predefに定義された関数は、すべてのScalaのソースにおいて自動でimportされている
printやprintlnはPredefで定義されている。JavaのようにSystem.out.printlnという長い記述をしなくても、printlnのみで標準出力ができるのは、これのお陰。

・Array===>scala.collection.mutable.ArrayLike

scala myfirstScript.scala my first script
==>args...引数のこと  args.foreach(println);


追加:
    var oldList=List(1,2)
    val newList=3 :: oldList
    ==>newList 3:2:1
    var theList= newList : +3

the :: method. The job of the :: method is to create a new List with all the existing
elements plus the new element added at the front of the List. To add at the end of
the List, invoke the :+ method:


val afterDelete = newList.filterNot(_ == 3)
==>filterNot(_ == 3)


_  An underscore has a special meaning in Scala, and in this context it’s a placeholder
for a parameter; in your case, use two underscores
==> evenNumbers.foldLeft(0) { _ + _ }

val hasUpperCase = name.exists(_.isUpper)

==>temporary value,variablesだよね。。。



・def breakable(op: => Unit) { ... }
What’s this op: => Unit? The special right arrow (=>) lets Scala know that the
breakable function expects a function as a parameter
The right side of the => defines the return type of the function

def foldLeft(initialValue: Int, operator: (Int, Int) => Int)= { ... }
==>the funuction paramater with two its own paramters!



val files = new java.io.File(".").listFiles
   for(file <- files) {
   val filename = file.getName
   if(fileName.endsWith(".scala")) println(file)
}
 <- In Scala this is called a generator, and the job of a generator is to iterate
through a collection.


for { a <- aList; b <- bList } println(a + b)
for { a <- aList; b <- bList } yield(a + b)
==>yield 新たなListが作成された。。。


mkString(",")
==>java splitだよね。。。


def ordinal(number:Int) = number match{
  case 1 => println("1st")
  case 2 => println("2st")
  case 3 => println("3st")
  case 4 => println("4st")
  case 5 => println("5st")
  case _ =>
}


java.util.Arrays.asList(scalaList.toArray:_*)
====》
:_*
tells the Scala compiler to send the result of toArray as a variable argument to the
Arrays.asList method;


class MongoClient(val host:String, val port:Int)
val client = new MongoClient("127.0.0.1", 123)
==>Scala also uses the new keyword for creating instances of a class. But
wait a minute?where’s the body of the MongoClient class? In Scala that’s optional

private
==>so that the Scale will not create get ,set methord automiclly



class MyScript(host:String) {
    require(host != null, "Have to provide host name")
    if(host == "127.0.0.1") println("host = localhost")
    else println("host = " + host)
}
==>require!


・package is a special object to grouping classes
package com {
  package mongo {
    import ....
    class
  }
}


import java.sql.{Date => SqlDate}
val sqlDate = new SqlDate(now.getTime)

import java.sql.{Date => _ }
==>The Date class from the java.sql package is no longer visible for use.


:load nnnn.scala
:l nnn.scala


object RichConsole {
def p(x: Any) = println(x)
}
Here RichConsole is a singleton object. The object declaration is similar to a class declaration
except instead of class you’re using the object keyword. To invoke the new
p method,


object DB {
def apply(underlying: MongDB) = new DB(underlying)
}
====>factory in scala

Class UpdatableCollection
extends DBCollection(collection(name)) with Updatable
==>with .... trait



class Outer {
    class Inner {
        private[Outer] def f() = "This is f"
        private[innerpkg] def g() = "This is g"
        private[outerpkg] def h() = "This is h"
}
}
==>Outer,innerpkg,outerpkg



final」はクラスやメンバーに対して設定できる修飾詞です。
   finalが設定されたクラスは継承できません。
   finalが設定されたメンバーはオーバーライドできません。
sealed」はクラスに設定できる修飾詞です。
   sealedとされたクラスは、同一ファイル内のクラスからは継承できますが、別ファイル内で定義されたクラスでは継承できません。
   ただし、sealedクラスを継承したクラスは、別ファイルのクラスからも継承できます。



・class Stack[+A] {
class Stack[-A] {
=>Scalaのコレクションクラス(List, Seqなど)は、List[+A]と型名の前に+を付けてcovariant(共変)な型を許すように定義されています。covariantとは、Aのクラスを拡張したクラスBがあれば、List[B]はList[A]として代入できることを意味します
関数側で型パラメーターに縛りが必要ない場合は_を使えばOKだった。
共変はサブクラスを許容する場合に使う


・値クラス (value class) は実行時のオブジェクトの割り当てを回避するための Scala の新しい機構だ
は新たに定義付けされる AnyVal のサブクラスによって実現される
=>    class Wrapper(val underlying: Int) extends AnyVal


・case class VS class
パターンマッチを使う場合にはcase class、
それ以外は普通のclass、と使い分けています
==>case classはcase classを継承することができない



hierarchy

.git
==>index file
The index records
and retains those changes, keeping them safe until you are ready to commit them.


=>content-addressable storage system
location-addressed disk storage with built-in search capability. The search logic was incorporated into the disk controller
First, Git’s object store is based on the hashed computation of the contents of its objects,
not on the file or directory names from the user’s original file layout.
If two separate files have exactly the same content, whether in the same or different
directories, Git stores a single copy of that content as a blob within the object store.

★It’s important to see Git as something more than a VCS: Git is a content tracking system.


★What if you only add, say,one line to a file, doesn’t Git store the complete content of both versions?
Luckily, the answer is “No, not really!”
Instead, Git uses a more efficient storage mechanism called a pack file.

Instead, Git uses a more efficient storage mechanism called a pack file. To create a
packed file, Git first locates files whose content is very similar and stores the complete
content for one of them. It then computes the differences, or deltas, between similar
files and stores just the differences. For example, if you were to just change or add one
line to a file, Git might store the complete, newer version and then take note of the one
line change as a delta and store that in the pack too.



★blod <- tree <- commit <- tag(branch)

2014/06/13

Scala 試し

★IDE:
http://scala-ide.org/download/current.html

==>うわさは、、こいつはうまくいかない。。。。


★Scala imlicit value
Scala には implicit parameter という機能があります。
どういう機能かと言うと、引数に implicit という修飾子をつけると、関数呼び出しの際にその引数を省略することが可能になるというものです。
省略?で、JVMの値とか、OSから取れる値とか、コンパイラが適切なものを選択して解決してくれます
コンパイラが適切な値を選択できなかった場合、コンパイルエラーになります。


★scala scalac
scalac HelloWord.scala
==>HelloWorld.class
scala  HelloWord
scala -cp . HelloWorld

Scalaでは、scalaコマンドによってクラスを実行する他に、対話型インタープリターとしてコマンドを入力して実行することが出来る。
==>REPL(Read Eval Print Loop)(Read=コマンド読み込み、Eval=解釈・実行、Print=結果表示、Loop=それらを繰り返す)

★trait===>こいつはinterfaceと理解する

trait Ord{
 def < (that:Any):Boolean
 def <= (that:Any):Boolean = (this<that) || (this==that)
 def > (that:Any):Boolean= !(this <= that)
 def >= (that:Any):Boolean= !(this < that)
}
==>maya...これは、抽象的に演算ね。。これはこの言語の特長?


42
=>The Scala interpreter reads the input 42, evaluates it
as an integer literal, creates an Int type object representing the number 42,res0 is the name of the variable created by the Scala interpreter

Int =42
res0
Int =42

・println is a function defined in scala.Console, which in turn
uses System.out.println to print messages to the console. Scala Predef
(part of the standard library) maps println to Console.println for you so
you don’t have to prefix it with Console when using it.

・val myList=new java.util.ArrayList[String]()
myList.
=>利用するメソッドの一覧が出る

・val var
A val is a single assignment variable, sometimes
called value. Once initialized a val can’t be changed or reassigned to some
other value。var is reassignable

・val first :: rest =list(1,2,3)
=> first: Int =1
   rest: List[Int] = list(2,3)
  
・lazy val forLater = someTimeConsumingOperation()
==>時間かかる操作

・function==>戻り値は必須ではない。。自動判断である
You don’t have to specify the return keyword to return anything from the function. It will
return the value of the last expression.


★fuctionの定義
def toList[A](value:A) = List(value)
def max(a: Int, b: Int) = if(a > b) a else b
def myFirstMethod = "exciting times ahead"
def myFirstMethod(){ "exciting times ahead" }
def myFirstMethod() = { "exciting times ahead" }


val array= new Array[String](3)
array.foreach(println)

val oldList=List(1,2)
val newList=3::oldList
=>3.2,1

val myList = "This" :: "is" :: "immutable" :: Nil



for(file <- files) {
for(File file: files) {
for { a <- aList; b <- bList } println(a + b)


他は使う時、調べて良いと思う。。。





df.format(now)
=>df format now 
就是下面的个冗的表达式的简洁写法  df.format(now) 
看起来是一个细节,但是它致一个重要的后果,我将在下一节进明。
??????何??あの辺?

了解释为什么吧函数当作值进行操作是十分有用的,我来考一个计时器函数。个函数的目的是每隔一段时间行某些操作。那么如何吧我要做的 操作计时器呢?于是我想吧他当作一个函数。种目前的函数行用界面程的程序是最熟悉的:注册一个回函数以便在事件生后得到 通知。

def main(args: Array[String]) {
    oncePerSecond(() => println("time files like an arrow"));
  }
=>匿名函数使用了一个箭=>)吧他的参数列表和代分开。在里参数列表是空的,所以我在右箭的左写上了一空括号

Scala中的可以有参数,这样就可以得出我下面关于复数Complex)的定  
class Complex(real: Double, imaginary: Double) { 
      def re() = real 
      def im() = imaginary 
}
==>all is class,fuciton も、だから、みんなは一緒で、大きな差がない。
看看上面的定义,跟一个函数没有什么在的区别吗!

val c = new Complex(1.2, 3.4)
println("imaginary part:" + c.im);

defè関数、クラス
val 変数

Traits. トレイト。トレイツ。BlackSchärli らが提唱し、Squeak Smalltalk で実装を試み、その実効性を確かめた多重継承機構。

Scala中的所有承一个父,当没有示声明父类时(就像上面定Complex),它的父类隐形指定scala.AnyRef
override def toString() = "" + re + im
=>在子中覆盖父的成是可能的。但是你需要通override示指定成的覆盖

def eval(t: Tree, env: Environment): Int = t match {       
case Sum(l, r) => eval(l, env) + eval(r, env)       
case Var(n)     => env(n)       
case Const(v)   => v 
==>模式匹配的基本思想就是试图对一个值进行多种模式的匹配,并且在匹配的同将匹配拆分成若干子,最后匹配与其子项执行某些代
==>物と操作の関係、どちをメインにする?
1. 当你使用成函数,你可以通过继Tree从而很容易的添加新的型,但是另外一方面,添加新的操作也是很繁的工作,因你不得不修改Tree的所有子  
2. 当你使用模式匹配是,形正好逆转过来,添加新的型要求你修改所有的对树使用模式匹配的函数,但是另一方面,添加一个新的操作只需要再添加一个模式匹配函数就可以了

class Reference[T] { 
   private var contents: T = _ 
   def set(value: T) { contents = value }
def get: T = contents 
}
 ======>はデフォルト値の意味!!

def welcome(name: String) :String = {"Exciting times ahead" + name}
The return type of a Scala function is optional because Scala infers the return type of a function automatically.

def max(a: Int, b: Int) = if(a > b) a else b
def myFirstMethod = "exciting times ahead"