标签: tail-recursion

尾递归与 重构

我有这个方法

  private def getAddresses(data: List[Int], count: Int, len: Int): Tuple2[List[Address], List[Int]] = {
    if (count == len) {
      (List.empty, List.empty)
    } else {
      val byteAddress = data.takeWhile(_ != 0)
      val newData = data.dropWhile(_ != 0).tail
      val newCount = count + 1
      val newPosition = byteAddress.length + 1
      val destFlag = byteAddress.head
      if (destFlag == SMEAddressFlag) {
        (SMEAddress().fromBytes(byteAddress) :: getAddresses(newData, newCount, len)._1, newPosition :: getAddresses(newData, newCount, len)._2)
      } else {
        (DistributionList().fromBytes(byteAddress) :: getAddresses(newData, newCount, len)._1, newPosition :: getAddresses(newData, newCount, len)._2)
      } …
Run Code Online (Sandbox Code Playgroud)

recursion scala tail-recursion

1
推荐指数
1
解决办法
483
查看次数

返回列表中位置x的项目

在F#中阅读这篇文章的时候还是Tail Recursion,什么时候用?有几个人说,做事的"功能方式"是使用map/folds和高阶函数而不是递归和循环.

我有这个函数返回列表中位置x的项目:

let rec getPos l c =  if c = 0 then List.head l else getPos (List.tail l) (c - 1)
Run Code Online (Sandbox Code Playgroud)

如何将其转换为更具功能性?

f# tail-recursion

1
推荐指数
1
解决办法
1242
查看次数

在python中将递归函数转换为尾递归函数

作为练习,我使用python中的递归实现了map函数,如下所示:

#map function that applies the function f on every element of list l and returns the new list 
def map(l,f):
    if l == []:
        return []
    else:
        return [f(l[0])] + map(l[1:],f)
Run Code Online (Sandbox Code Playgroud)

我知道python不支持尾递归优化这一事实,但我如何以尾递归方式编写相同的函数?

请帮助谢谢

python recursion tail-recursion

1
推荐指数
1
解决办法
2141
查看次数

为什么递归更改结果?

我正在检查doctest并将factorial示例复制到我的编辑器中.由于使用递归感觉更多的函数式编程,我觉得像这样更改示例;

def factorial(n):
    # ... omitted
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")

    if n == 0:
        return 1
    else:
        return factorial(n  - 1) * n
Run Code Online (Sandbox Code Playgroud)

在此更改后,其中一个测试失败;

Failed example:
    factorial(30.0)
Expected:
    265252859812191058636308480000000L
Got:
    2.6525285981219103e+32
Run Code Online (Sandbox Code Playgroud)

这种差异的原因是什么?

python doctest tail-recursion

1
推荐指数
1
解决办法
79
查看次数

可以严格指导递归吗?

假设我们在Haskell中有一个简单的树创建算法:

data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)

makeTree :: Tree Int -> Tree Int
makeTree (Node 0 l r) = Node 0 EmptyTree EmptyTree
makeTree (Node n l r) = Node n (makeTree $ newTree (n - 1))
                               (makeTree $ newTree (n - 1))
  where
    newTree n = Node n EmptyTree EmptyTree
Run Code Online (Sandbox Code Playgroud)

对于非常大的数字,我们希望此算法失败并出现"堆栈大小溢出"错误.这是因为算法是二进制递归,而不是尾递归.我可以用爆炸模式(对得到的左子树"(makeTree $ NEWTREE(N - 1))"),引导二进制递归到尾递归,因为递归现在应该由于严格定向?

编辑:

事实证明,真正的问题不是树的创建,而是消耗树的功能.还有另一个用于展平树的函数,其实例如下:

import qualified Data.Foldable as F

instance F.Foldable Tree where
    foldMap f …
Run Code Online (Sandbox Code Playgroud)

recursion haskell tail-recursion

1
推荐指数
1
解决办法
132
查看次数

为什么这个尾递归函数变得更加复杂?

所以,我正在摆弄一些基本的数学,我想要一个函数来在基数之间进行转换.

我写了这个函数:

(define (convert-base from to n)
  (let f ([n n])
    (if (zero? n)
        n
        (+ (modulo n to) (* from (f (quotient n to)))))))
Run Code Online (Sandbox Code Playgroud)

这适用于我的所有个人测试<基础10,并且就我所能想象的功能完全正常的测试>基数10,如果我只是添加了对其他数字的支持.

令我感到困惑的是,当我试图使函数尾递归时,我最终得到了这个混乱(我为SO的好处添加了一些间距,因为我的代码通常不清晰或漂亮):

;e.g. 10 2 10 should output 1010, 10 8 64 should output 100 etc.

(define (convert-base-tail from to n)
  (let f ([n n]
          [acc 0]
          [zeros 0])

    (begin (printf "n is ~a. acc is ~a. zeros are ~a.\n" n acc zeros)

    (cond [(zero? n) (let exp 
                       ([x acc]
                        [shft zeros])
                       (if (zero? shft) …
Run Code Online (Sandbox Code Playgroud)

recursion tail-recursion racket

1
推荐指数
1
解决办法
92
查看次数

尾递归和迭代SML

这是我的任务.

(http://prnt.sc/aa3gwd)

我一直在和导师一起工作,这是我们迄今为止所提出的.

fun mult(a,b) =
  let
    val product = 0
in
    if (a = 0) then 
0
   else
     while a > 0 do
     (                  
       product := product + b;  
       if (a = 1) then 
  product
else
          a:= a -1
     );       
end;
; //the function did not run at end;, so we added these two semicolons below
;
Run Code Online (Sandbox Code Playgroud)

输出是:

stdIn:102.11-103.6 Error: syntax error: deleting  SEMICOLON END SEMICOLON
Run Code Online (Sandbox Code Playgroud)

在过去的两周里我才被介绍给SML而且我无法理解它.很感谢任何形式的帮助.

iteration translation tail-recursion sml translate

1
推荐指数
1
解决办法
208
查看次数

Clojure,总结一个向量列表,记录沿途的位置

说我有一个向量列表

([0 0] [1 0] [1 0] [1 0])
Run Code Online (Sandbox Code Playgroud)

我希望能够将矢量列表添加到一起并记录每个独特的位置.

                [0 0]
[0 0] + [1 0] = [1 0]
[1 0] + [1 0] = [2 0]
[2 0] + [1 0] = [3 0]
Run Code Online (Sandbox Code Playgroud)

提供4个独特的职位.

([0 0] [1 0] [2 0] [3 0]) 
Run Code Online (Sandbox Code Playgroud)

知道如何在Clojure中实现这一目标吗?

我尝试了以下代码,但它溢出了大量的向量:(

(defn add-vectors [vectors]
  (let [[a b] vectors]
    (vec(map + a b))))

(defn get-positions [dirs positions]
  (if (empty? (rest dirs))
    (set positions)
    (do
      (let [next-pos (add-vectors (take 2 dirs))]
        (get-directions (conj (rest (rest dirs)) …
Run Code Online (Sandbox Code Playgroud)

lisp recursion tail-recursion vector clojure

1
推荐指数
1
解决办法
333
查看次数

Kotlin - 为什么这个函数不符合尾递归的条件?

send()以下示例中的函数以递归方式调用自身:

internal inner class RouteSender(
        val features: List<Feature>,
        val exchange: GrpcUniExchange<Point, RouteSummary>
) {
    var result: AsyncResult<RouteSummary>? = null // Set in stub for recordRoute.

    fun send(numPoints: Int) {
        result?.let {
            // RPC completed or err'd before sending completed.
            // Sending further requests won't error, but they will be thrown away.
            return
        }

        val index = random.nextInt(features.size)
        val point = features[index].location
        println("Visiting point ${RouteGuideUtil.getLatitude(point)}, " +
                "${RouteGuideUtil.getLongitude(point)}")
        exchange.write(point)
        if (numPoints > 0) {
            vertx.setTimer(random.nextInt(1000) + 500L) { _ -> …
Run Code Online (Sandbox Code Playgroud)

tail-recursion kotlin

1
推荐指数
1
解决办法
488
查看次数

尾递归,跟随片段尾递归吗?

我正在学习尾递归,在解决这个问题之前,我想对代码片段是否尾递归进行是/否的回答。

int fib_in(int n, int current, int prev) {
    if (n == 1 || n == 2) { // n = 1 or 2 both gives fib number 1
        return current;
    }
    return fib_in(n - 1, current + prev, current); // recursive call, current gets updated and new prev is the current, so were going backwards if that makes sense
}

int fib(int n) {
   return fib_in(n, 1, 1); // 1 and 1 is the 2 first fib numbers so …
Run Code Online (Sandbox Code Playgroud)

c recursion tail-recursion

1
推荐指数
1
解决办法
45
查看次数