티스토리 뷰

Scala

[Scala] List 그리고 cons operator

스트레스리스맨 2017. 7. 25. 17:03

Scala 99 problems 의 첫 문제를 보다 (난 정말 스칼라를 제대로 공부할 필요가 있구나... 자료형 조차...) "::" 라는 녀석을 보고 대 혼란에 빠짐.


일반적으로 :: 는 cons operator 라 부르며 ML 에서 기인되었다고 하는데 간단히 이해하자면 List data type 의 left hand side 에 element 를 추가하는 연산자이다. 양키 아이들이 설명하길 :: 는 right side 에 있는 variable 을 '취한다' 라고 표현한다.


예를 들어, 빈 리스트에 0 이라는 Int 를 하나 추가하려고 한다면 



scala> var l:List[Int] = List()
l: List[Int] = List()

scala> 0::l
res4: List[Int] = List(0)

scala> 1::l
res5: List[Int] = List(1)

scala> 1::2::l
res6: List[Int] = List(1, 2)

scala> 1::2::4::Nil
res7: List[Int] = List(1, 2, 4)


이런 형태로 작성할 수 있다. Nil 은 built-in 은 Term 이고 End of List 를 의미한다. 

문제는 pattern matching 할 때 cons operator 의 역할이며 이 글을 쓰는 현재까지도 나는 저게 대체 뭔지를 모르겠다.


그래서 방금 찾은 링크 


다시 문제를 봅시다


// P01 (*) Find the last element of a list.

//     Example:
//     scala> last(List(1, 1, 2, 3, 5, 8))
//     res0: Int = 8

// The start of the definition of last should be
//     def last[A](l: List[A]): A = ...
// The `[A]` allows us to handle lists of any type.

object P01 {
  // There are several ways to solve this problem.  If we use builtins, it's very
  // easy.
  def lastBuiltin[A](ls: List[A]): A = ls.last

  // The standard functional approach is to recurse down the list until we hit
  // the end.  Scala's pattern matching makes this easy.
  def lastRecursive[A](ls: List[A]): A = ls match {
    case h :: Nil  => h
    case _ :: tail => lastRecursive(tail)
    case _         => throw new NoSuchElementException
  }
}

이 케이스에서 보면


  • case h :: Nil > case 가 존재하는데 (h 라는 element) 그 다음이 Nil 인 경우, 즉 h 가 last element 인 경우 >> 문제의 해답
  • case _ :: tail > case 뭐든간에 다른 element 와 결합된 경우 (비어있지 않고 마지막 element 가 아닌 경우)
결국 tail 과 결합된 element 제외하고 나머지를 recursive 하게 돌다가 마지막 element 만 남으면 반환 하면 된다.



'Scala' 카테고리의 다른 글

Slick 에서 Null 이 아닌 Default Values 를 적용하는 방법  (0) 2017.04.06
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함