Skip to content

Instantly share code, notes, and snippets.

@daiksy
Created November 1, 2012 16:05
Show Gist options
  • Save daiksy/3994596 to your computer and use it in GitHub Desktop.
Save daiksy/3994596 to your computer and use it in GitHub Desktop.
reverseを書いてみた
  def reverse[A](xs: List[A]): List[A] = {
    (List.empty[A] /: xs){(x, y) => y :: x}
  }

の方が読みやすい?

でも右畳込みの場合, この書き方だとWindowsでバックスラッシュが円記号になるから,直感的じゃなくなるんだよな…

/**
* reverseを畳み込みを使って実装してみた.
*/
object reverseApp extends App {
val l = List(1, 2, 3, 4, 5)
reverse(l) foreach println // 結果は 5, 4, 3, 2, 1
val l2 = List("a", "b", "c")
reverse(l2) foreach println // 結果は "c", "b", "a"
def reverse[A](xs: List[A]): List[A] = {
xs.foldLeft(List.empty[A]){(x, y) => y :: x}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment