zoukankan      html  css  js  c++  java
  • learning scala Function Recursive Tail Call

    可以使用scala库,可以从字面上看出是在调用 递归函数:

    code

    import scala.util.control.TailCalls._
    
    
    
    
      val arrayDonuts: Array[String] = Array("Vanilla Donut", "Strawberry Donut", "Plain Donut", "Glazed Donut")
    
    
      println("
    Step : How to define a tail recursive function using scala.util.control.TailCalls._")
      def tailSearch(donutName: String, donuts: Array[String], index: Int): TailRec[Option[Boolean]] = {
        if(donuts.length == index) {
          done(None) // NOTE: done is imported from scala.util.control.TailCalls._
        } else if(donuts(index) == donutName) {
          done(Some(true))
        } else {
          val nextIndex = index + 1
          tailcall(tailSearch(donutName, donuts, nextIndex)) // NOTE: tailcall is imported from scala.util.control.TailCalls._
        }
      }
    
    
    
      println("
    Step : How to call tail recursive function using scala.util.control.TailCalls._")
      val tailFound = tailcall(tailSearch("Glazed Donut", arrayDonuts, 0))
      println(s"Find Glazed Donut using TailCall = ${tailFound.result}") // NOTE: our returned value is wrapped so we need to get it by calling result
    
      val tailNotFound = tailcall(tailSearch("Chocolate Donut", arrayDonuts, 0))
      println(s"Find Chocolate Donut using TailCall = ${tailNotFound.result}")

    resule:

    Step : How to define a tail recursive function using scala.util.control.TailCalls._
    
    Step : How to call tail recursive function using scala.util.control.TailCalls._
    Find Glazed Donut using TailCall = Some(true)
    Find Chocolate Donut using TailCall = None
    

      

  • 相关阅读:
    转载:iOS开发的22个奇谲巧技
    解决pathForResource返回nil, 无法读取plist文件问题
    小项目三:登陆窗口
    小项目一: UIButton的使用
    转载:iOS 8 自适应 Cell
    转载:iOS 8 AutoLayout与Size Class自悟
    转载:总结iOS 8和Xcode 6的各种坑
    [转]Xcode6中如何添加pch文件
    UIButton和UIImageView的区别
    控件的属性
  • 原文地址:https://www.cnblogs.com/lianghong881018/p/11174361.html
Copyright © 2011-2022 走看看