Skip to content

Instantly share code, notes, and snippets.

@guersam
Created April 28, 2016 08:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guersam/c5a14519dfb73597f096e75834b2c011 to your computer and use it in GitHub Desktop.
Save guersam/c5a14519dfb73597f096e75834b2c011 to your computer and use it in GitHub Desktop.
스칼라 우왕
import shapeless._
// Shapeless를 이용한 Generic Programming
// https://github.com/milessabin/shapeless/blob/shapeless-2.3.0/examples/src/main/scala/shapeless/examples/sybclass.scala
// 재귀적으로 정의된 이진 트리
sealed trait Tree[T]
case class Leaf[T](t: T) extends Tree[T]
case class Node[T](left: Tree[T], right: Tree[T]) extends Tree[T]
// 정수를 리프 노드의 값으로 하는 예제 트리
val tree: Tree[Int] =
Node(
Node(
Node(
Leaf(1),
Node(
Leaf(2),
Leaf(3)
)
),
Leaf(4)
),
Node(
Leaf(5),
Leaf(6)
)
)
// 정수형에만 적용할 polymorphic function
object inc extends ->((i: Int) => i+1)
// 트리 전체에 한 번에 적용
val result = everywhere(inc)(tree)
// 하면
println(result)
// 짜잔
val expected: Tree[Int] =
Node(
Node(
Node(
Leaf(2),
Node(
Leaf(3),
Leaf(4)
)
),
Leaf(5)
),
Node(
Leaf(6),
Leaf(7)
)
)
// 확인
assert(expected == result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment