私はscalaパターンマッチングで遊んでいて、findNext関数を作ろうとしています:
findNext(1,List(1,2,3)) == 2
findNext(2,List(1,2,3)) == 3
findNext(3,List(1,2,3)) == 1
def findNext(needle : Int, haystack : List[Int]): Int = {
haystack match {
case Nil => /* handle it */
case needle::Nil => needle
case front::needle::back => back.head
case needle::back::Nil => back.head
}
}
些細なケースでのみ機能させることができます。
これはパターンマッチングを使用して行うことができますか? リストのメソッドを使用して動作させることができることはわかっていますが、これは単なるおもちゃのプログラムです。