Anonymous recursive function in Scala

前端 未结 6 1059
Happy的楠姐
Happy的楠姐 2020-12-12 19:32

Is there a way to write an anonymous function that is recursive in Scala? I\'m thinking of something like this:

((t: Tree) => {
    print(t.value);
    fo         


        
6条回答
  •  轮回少年
    2020-12-12 20:02

    Recursive calls on Scala. Let me take some of N numbers example for recursion

    var sumIt:(Int => Int) = (x: Int) => {if(x<=1) 1 else sumIt(x-1)+x}
    
    
     scala> sumIt(10) 
    val res141: Int = 55
    

    You can see the sumIt has its type with Int, Int as Input and the return value. The sumIt lambda function takes as argument which is an Integer and it does recursive call on sumIt.

    I just this example for easy understanding the recursion call. You can direct formula for this logic like...

    sumValue = (N*(N+1)) /2
    

提交回复
热议问题