help rewriting in functional style

后端 未结 5 2145
再見小時候
再見小時候 2021-02-10 10:46

I\'m learning Scala as my first functional-ish language. As one of the problems, I was trying to find a functional way of generating the sequence S up to n places. S is defined

5条回答
  •  故里飘歌
    2021-02-10 11:03

    Here is a translation of your code to a more functional style:

    def genSequence(numItems: Int): List[Int] = {
      genSequenceR(numItems, 2, 2, 0, 1, List[Int](1))
    }
    
    
    def genSequenceR(numItems: Int, seq_no: Int, no:Int, no_nos: Int, numMade: Int, list: List[Int]): List[Int] = {
     if(numMade < numItems){
       if(no_nos < seq_no){
         genSequenceR(numItems, seq_no, no, no_nos + 1, numMade + 1, list :+ no)
       }else if(no % 2 == 0){
         genSequenceR(numItems, seq_no, no + 1, 0, numMade, list)
       }else{
         genSequenceR(numItems, seq_no + 1, no + 1, 0, numMade, list)
       }
      }else{
        list
      }
    }
    

    The genSequenceR is the recursive function that accumulates values in the list and calls the function with new values based on the conditions. Like the while loop, it terminates, when numMade is less than numItems and returns the list to genSequence.

    This is a fairly rudimentary functional translation of your code. It can be improved and there are better approaches typically used. I'd recommend trying to improve it with pattern matching and then work towards the other solutions that use Stream here.

提交回复
热议问题