scala 실행

scala 2016. 3. 16. 09:33

  hello.scala 내용:  println(" Hello world")


1. hello.scala와 같은 script 작성 후  


$ scala hello.scala 로 실행 .



2. class나 object .scala작성후


$scalac co.scala

$scala co   

하면 되는데


scalac 보다 빠른 fsc (fast scala compiler)가 존재한다.

차이점은 fsc는 항상 메모리에 띄워 놓고, scalac은 JVM을 그 때 그때 띄우게 되는데..

따라서 fsc를 죽이고 싶다면 

$ fsc co.scala

$ scala co 

$ fsc - shutdown  으로 죽이면 된다.

Posted by yongary
,

class

- java의 class와 동일하다고 보면 되나, primary 생성자는 없다.

- primary 생성자는 class Dog(legs:Int, name:String){ } 로 정의에서 끝난다.

=> legs,name은 val로 자동생성된다.

- primary생성자의 body는 class 안에 아무데나 쓰면 된다.

- overload 생성자는 def this(legs:Int)와 같은식으로 명시하면 된다.


object

- companion object와 stand_alone object 가 존재한다.

- companion object는 java의 static함수를 모아놓은 것이라고 생각하면 된다.
  동일한 이름의 class가 존재한다.

- stand alone object는 독립적으로 존재하는데 보통
  def main(args:Array[String]) {  } 을 포함하는 용도로 사용된다. 


trait

- java의 interface와 유사하다고 보면되나, implements 키워드 대신 항상 extends키워드를 쓴다.

- method를 구현할 수 있다. (java Interface도 원래는 abstract함수만 되나, 1.8부터 body구현 지원)

- 인스턴스 생성시에 with 키워드로 바로 적용이 가능하다. (복잡하겠군요.. 인스턴스마다 다른 특성을 지니겠네요)


- extends Trait  해서 함수 오버라이드 시에..  def 앞에 override 키워드 꼭 필요.




class 인스턴스의 접근성

- class Dog{ var sum=0 }  일 경우 val a = new Dog 이 안됨.  단 var a일 경우.. a.sum+=1 은 됨.  

- class Dog{ private sum=0} 일 경우 val a = new Dog이 됨. s.sum +=1 이 안됨.

  

def의 접근성. =이 type을 의미함.

scala> def h = {"hello"}    h는 hello String 리턴.

scala> def g {"hello"}    g는 리턴없음. 즉 Unit리턴.

scala> def f:Unit = "hello"    g와 동일. 

Posted by yongary
,

scala Collections

scala 2016. 3. 15. 17:16

Array: mutable이고  java와 달리, (0),(1)로 마치 함수호출 하듯이 element get함.


List : immutable이고 동일한 type을 보관

tuple: immutable이고 서로 다른 type의 데이타를 저장할 수 있다. 


HashSet, HashMapt: mutable   (Set,Map은 trait임)

예) val s = new HashSet[String] 

    s += "AA"

예) val m = new HashMap[Int, String]

    m += (1 -> "Go to Hell") 


<immutable Set/Map> - factory method방식으로 이용가능.

    예) val s = Set("A", "BB", "CC")            : compoiler transfers as Set.apply()

   예) val s = Map(1 -> "AA", 2->"BB")       : compoiler transfers as Map.apply()




요약하면 immutable List,Tuple,  Set,Map이 존재한다.



Posted by yongary
,

System.in 및 File IO

scala 2016. 3. 7. 11:13

1. io.Source.stdin 이용    REF-SITE

   for (ln <- io.Source.stdin.getLines) println(ln)  

   (참고: break나 return이 잘 안되서 study 중 )


  1.5 위에서 stdin = fromInputStream(System.in)으로 def(ine)되어 있다. 따라서 아래처럼 변형도 가능

    val input = Source.fromInputStream(System.in);

   val lines = input.getLines.collect


2. System.in 에서 읽기

=> readLine()함수가 system.in에서 바로 라인을 읽는다.

끝나면 null을 리턴하므로 체크 필요.

object SysteminTest {
  def main(args: Array[String]) {

var line = true
do {
var str = readLine() //depricated..
if (str!=null) println(str)

else line=false //need test..
} while ( line )

} }



2. File에서 읽기

Line을 읽어서 String으로 만드는데,  empty Line을 공백" " 으로 처리하는 방법.

val file = Source.fromFile(args(0)).getLines().filter(!_.isEmpty()).mkString(" ")

Posted by yongary
,

DB with anorm

scala 2016. 3. 2. 16:58

scala에서 DB를 연동할 때, JDBC를 직접 사용할 수도 있지만

Play Framework와 함께 할때는 Anorm을 사용하는 방법이 편리하다.


REF-SITE :play



사용모습을 보면 아래와 같다.



(예제: 출처 https://janhelwich.wordpress.com/tag/anorm/ )

object Post{
  val parser = {
      get[String]("title") ~
      get[Date]("posted") ~
      get[String]("content")~
      get[Pk[Int]]("authorId") map {
      case title ~ posted ~ content ~ author => Post(title,  posted, content, User.findBy(author))
    }
  }
 
  def findAll() = {
    DB.withConnection {
      implicit connection =>
        SQL("select * from posts").as(parser *)
    }
  }
 
  def create(post: Post): Unit = {
    DB.withConnection {
      implicit connection =>
        SQL("insert into posts(title, posted, content, authorId) values ({title}, {posted}, {content}, {authorId})").on(
          'title -> post.title,
          'posted -> post.posted,
          'content -> post.content,
          'authorId -> post.author.id
        ).executeUpdate()
    }
  }


Posted by yongary
,

Anonymous class

java core 2016. 2. 26. 21:50

java의 abstract class 나 interface가  instance 화가 될 수 있냐? 고 질문한다면

답은  1. 일반적으론 안된다.  

          2. 그렇지만 anonymous class 방식으로는 된다. REF(Runnable 참조)

       이렇게 둘 다 답하면 best 이다.

 

참고로 
 abstract class : 추상 method가 하나이상 존재--> 상속시 추상 method구현을 강제함.
 Interface : 추상 method만으로 이루어진 class   but jdk1.8에서는  구현된 method도 허용함.  

     REF-SITE:

Posted by yongary
,

[char array->String]

char cArr[] ;  

String s = String.valueOf(cArr);

 

 

 

 

1. Array에 특정한 Object가 있는지 Check:


Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


2. LinkedList 에서 삭제 및 data Set.

Size()가 변하는 loop안이라면 Iterator를 사용하여 삭제하는 게 안전.

아니면 뒤에서부터 앞으로 Loop돌면서 삭제. (테스트 필요)

 

Iterator<String> iter = list.iterator();
while (iter.hasNext()) {  
     String s = iter.next(); //꼭 next먼저 호출.
     if (s.equals("a"))  iter.remove();  //원래 remove는 가장최근 return()한 걸 삭제하는 이상한 함수임.
}


ListIterator의 경우에는 iter.set() 함수도 매우 쓸만하다. //이 역시, 가장 장최근 return()한 걸 치환.


3. LinkedList  에 특정위치에 data 넣고 싶을때?

    LikedList<String> list = new LinkedList<String>();

    list.add("a");list.add("c");


    <a,c사이에 b를 넣고 싶으면>

    list.add(1,"b");   // index를 이미 안다면,  방법을 쓰거나..

    list.add ( getIndex("a")+1, "b"); //모른다면.. 이방법. 근데이게 getIndex가 속도가 의심이 됨..  

     최상의 방법은? 뭘까요?  
     자가 List라면  node.next.next = node.next;  node.next = new Node(); 하면 되는데.. 
     

     이런방법 없을까요?


     

      

     

      

    

    


Posted by yongary
,

Java memory 사용량.

java core 2016. 2. 23. 23:50
public static void main(String[] args) {

    long used1 = memoryUsed();
    int[][] array = new int[200][2];

    long used2 = memoryUsed();
    int[][] array2 = new int[2][200];

    long used3 = memoryUsed();
    if (used1 == used2) {
        System.err.println("You need to turn off the TLAB with -XX:-UseTLAB");
    } else {
        System.out.printf("Space used by int[200][2] is " + (used2 - used1) + " bytes%n");
        System.out.printf("Space used by int[2][200] is " + (used3 - used2) + " bytes%n");
    }
}

public static long memoryUsed() {
    Runtime rt = Runtime.getRuntime();
    return rt.totalMemory() - rt.freeMemory();
}
출처: stackoverflow peter lawrey 


Posted by yongary
,

/*

usage: 

MyJson mj = new MyJson(aLineString);   // {"key1:value1","key2:value2"} 

        String offTime = mj.get("key1") ;

*/



class MyJson{

private HashMap<String, String> hm = new HashMap<String,String>();

public MyJson(String json){

String normal = json.replaceAll("[{\"}]", ""); //remove {,", }

System.out.println("(normal)"+normal);

String[] kvset = normal.split(",\\s*");  // comma + (*:space exist or not)

for( String s : kvset){

String kv[] = s.split(":");

if( kv.length==2)

hm.put(kv[0], kv[1]);

else{

System.err.println("Json Parse err(may have only key) "+s);

}

}

}

public String get(String key){

return hm.get(key);

}

}

Posted by yongary
,

=============My BucketSort. Example===================

 

import java.util.HashMap;
import java.util.LinkedList;
import java.util.ListIterator;



public class BucketSort {

private HashMap<Integer, LinkedList> hMap;
/*
input: unSorted Array, #bucket(number of Bucket)
process: bucket sorting Using #bucket
return: sorted Array.
*/
public Integer[] bucketSort(Integer data[], int numBucket){
Integer[] ret = new Integer[data.length];
hMap = new HashMap<Integer, LinkedList>();



for (int i: data) {
Integer key = numBucket * (i / numBucket); //분모가 maxInt 가 맞을듯.(16.6)

==> 그냥 i%numBucket가 맞을 듯한데.. 좀더 보자.(2017.10)

LinkedList<Integer> prevList;



//make new List and add to HashMap.. when there's no data
if ( (prevList = hMap.get(key)) == null ) {
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(i);
hMap.put(key,list);
}else{ //prevList traverse and add i to apporate position
ListIterator<Integer> it = prevList.listIterator();

boolean added = false; //added flag prevents Concurrent Modify Error.
while (it.hasNext()) { //at least 1 element. SO always on this loop.
if (it.next() > i ) { //Add to Proper position
prevList.add(it.previousIndex(),i);
added = true;
break;
}
}
if (!added)
prevList.add(i); //Add to End

}//else
} //for



//to array.
int k=0;
for (int j=0; j< numBucket; j++){
Integer key = numBucket*j;
LinkedList<Integer> list = hMap.get(key);

if (list!=null) {
ListIterator<Integer> it = list.listIterator();

while (it.hasNext())
ret[k++] = it.next();
}
}

return ret;
}

/////////MAIN /////////////////
public static Integer datas[]={77, 11, 22, 55, 44, 33, 99, 88, 21, 23, 37, 41, 81, 91, 74, 19, 30, 40 };

public static void main(String args[]){

BucketSort b = new BucketSort();
Integer[] data = b.bucketSort(datas, 10);

for ( int i : data)
System.out.print(i+",");
}
}


Posted by yongary
,