Skip to content

Instantly share code, notes, and snippets.

@hyunjun
Last active February 1, 2017 08:39
Show Gist options
  • Save hyunjun/ccf149468a9d87857d0ce673e0127eb1 to your computer and use it in GitHub Desktop.
Save hyunjun/ccf149468a9d87857d0ce673e0127eb1 to your computer and use it in GitHub Desktop.
scala for comprehension
  • code

    scala> def bitmap(n: Int) =
       | for { i <- 1 until Math.pow(2, n).toInt
       |       bitmap = (0 to n).map(j => (i >> j) & 0x1)
       |     } yield bitmap

bitmap: (n: Int)scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[Int]]

scala> bitmap(3) res39: scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[Int]] = Vector(Vector(1, 0, 0, 0), Vector(0, 1, 0, 0), Vector(1, 1, 0, 0), Vector(0, 0, 1, 0), Vector(1, 0, 1, 0), Vector(0, 1, 1, 0), Vector(1, 1, 1, 0))

* code for bitmap indices

```scala
scala> def bitmapIndex(n: Int) =
   | for { i <- 1 until Math.pow(2, n).toInt
   |       bitmap = (0 to n).map(j => (i >>j) & 0x1)
   |       index = bitmap zip (0 to n) filter (_._1 == 1) map (_._2)
   |     } yield index
bitmapIndex: (n: Int)scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[Int]]

scala> bitmapIndex(3)
res48: scala.collection.immutable.IndexedSeq[scala.collection.immutable.IndexedSeq[Int]] = Vector(Vector(0), Vector(1), Vector(0, 1), Vector(2), Vector(0, 2), Vector(1, 2), Vector(0, 1, 2))
  • 주의해서 볼 부분

    • for comprehension 사용법. yield를 사용하기 위해 중간 과정은 for { ... }으로
    • for comprehension의 결과를 flatten만 하면 Seq[List[Char]]라서 return type mismatch가 발생하기 때문에 toList를 사용
  • code

scala> def permutation(acc: List[List[Char]], prev: List[Char], cur: List[Char]): List[List[Char]] = cur match { | case Nil => prev :: acc | case _ => ((for { i <- 1 to cur.length | (f, s) = cur splitAt i | result = permutation(acc, f.last :: prev, f.init ++ s) | } yield result) flatten) toList | } warning: there were two feature warnings; re-run with -feature for details permutation: (acc: List[List[Char]], prev: List[Char], cur: List[Char])List[List[Char]]

scala> val result = permutation(ListList[Char], ListChar, List('a', 'e', 't')) result: List[List[Char]] = List(List(t, e, a), List(e, t, a), List(t, a, e), List(a, t, e), List(e, a, t), List(a, e, t))

scala> result res99: List[List[Char]] = List(List(t, e, a), List(e, t, a), List(t, a, e), List(a, t, e), List(e, a, t), List(a, e, t))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment