Subscribed unsubscribe Subscribe Subscribe

Scalaでtrコマンドっぽいの

Scala

trコマンドみたいなことやりたかったんだけど、そのものズバリ的なものないですかね。

def transform[A](dict: List[(A, A)], xs: List[A]): List[A] = {

  def replace(t: (A, A), xs: List[A]): List[A] = xs.map {
    case x if x == t._1 => t._2
    case x => x
  }

  dict match {
    case Nil => xs
    case head :: rest => transform(rest, replace(head, xs))
  }

}

def zenkakuToHankaku(s: String): String = {
  val dict = "1234567890".toList.zip("1234567890".toList)
  transform(dict, s.toList).mkString
}

zenkakuToHankaku("1234512345")


/*
scala> :load ./zenkaku_hankaku.scala
Loading ./zenkaku_hankaku.scala...
transform: [A](dict: List[(A, A)], xs: List[A])List[A]
zenkakuToHankaku: (s: String)String
res0: String = 1234512345
*/