上のScalaバージョン
object Main {
def main(_args: Array[String]) = {
solve(5) |> (s => println(s))
}
def repeat[A](x : A) : Stream[A] = x #:: repeat(x)
def permutation[A](xs : List[A], n : Int) : List[List[A]] = {
repeat(xs).take(n).toList |> ListMonad.sequence
}
def solve(n : Int) : List[String] = {
permutation(List('A', 'C', 'G', 'T'), n).map(_.mkString).filter(_.contains("AAG"))
}
trait Monad[M[_]] {
def mbind[A,B](m : M[A])(f : A => M[B]): M[B]
def mret[A](x : A): M[A]
def sequence[A](ms : List[M[A]]) : M[List[A]] =
ms match {
case Nil => mret(Nil)
case m::ms =>
mbind(m) {
x => mbind(sequence(ms)) {
xs => mret(x::xs)
}
}
}
}
object ListMonad extends Monad[List] {
override def mbind[A,B](m:List[A])(f: A => List[B]) = m.flatMap(f)
override def mret[A](x : A) = List(x)
}
implicit def AofT[T](x: T) : {def |>[S](f:T=>S): S} = new { def |>[S] (f: T => S): S = f(x) }
}