First off, I would have rewritten you example a little, to this: (define (vector->list-iter v) (let loop ((i (- (vector-length v) 1)) (acc '())) (if (< i 0) acc (loop (- i 1) (cons (vector-ref v i) acc))))) And to see the difference lets make the non tail-recursive version: (define...

Okay, here's what's wrong with your code. I've already commented about replacing pivot with k, but after looking at the code more closely I found a few more errors. @AnderBiguri already identified a couple of problems, and I'll mention those here as well for completeness. function []=Quickselect(A,k); As Ander mentioned,...

The reason why i is decreasing with each call is that i is used to determine when we've reached the end of the vector. The idea is that when we call the helper function initially, we set i to be the length of the vector (minus 2), and then in...

scala,recursion,concurrency,playframework,tail-recursion

The issue you linked (was in a comment, not the question or answer) refers to a memory leak that occurred with flatMap. Your code doesn't use flatMap, so I don't think you wouldn't run into any problems, as you're just conditionally executing another Future via a callback, and not caring...

I believe you need a stack to do such a traversal, just as in imperative programming, there would be no natural way to write that without a recursive method. Of course, you can always manage the stack yourself, which moves it into the heap, and prevents stack overflows. Here is...

javascript,recursion,tail-recursion

The example you provided does not have any tail recursion. Consider: (function loop(i) { setTimeout(function main() { alert("Hello World!"); if (i > 1) loop(i - 1); }, 3000); }(3)); I've given the inner function the name main and the outer function the name loop. The loop function is immediately invoked...

erlang,mergesort,tail-recursion

Your merge-sort is not tail recursive because the last function called in mergesort/3 is merge/3. You call mergesort as arguments of merge so stack has to grow - upper called mergesort/3 is not yet finished and its stack frame can't be reused. To write it in TR approach you need...

haskell,memory,recursion,ghc,tail-recursion

I was putting the seq in the wrong place. It needs to be: n `seq` qr `seq` sr `seq` doChoose (n-1) (k-1) (qn * qr `rem` modulus * inv qk `rem` modulus, sn + sr - sk) Otherwise the call to seq isn't evaluated until reaching the base-case and a...

compiler-construction,ocaml,tail-recursion,short-circuiting

Many others are wiser than I am about OCaml internals, but for simple functions it's pretty easy to see tail recursion in the generated assembly code of ocamlopt: $ cat tailrec.ml let rec f a x = if x <= 1 then a else f (a * x) (x -...

algorithm,recursion,scheme,racket,tail-recursion

As it was already correctly stated and explained in the other answer, there's no advantage of using tail recursion on this. But, as you were interested in the way it would be done, here it is a deep-map function I have implemented once. The code is cleaner if you're satisfied...

performance,recursion,clojure,tail-recursion

Clojure (or rather the combination of the compiler and the JVM) is indeed smart enough not to allocate constants repeatedly when looping and recurring so there is little risk of running into problems on that account. If you have an expensive function to initialize the rules and put it inside...

This will return a set of all detonated cells including the one that started the chain reaction. module Location = type T = {Row: int; Column: int } let subtract l1 l2 = {Row=l1.Row - l2.Row;Column=l1.Column-l2.Colum let detonate (field:Field.T) (start:Cell.T) = let rec inner cells m acc = match cells...

javascript,node.js,recursion,stack-overflow,tail-recursion

If you had a function that called itself synchronously, say, 200k times, the code will exit with error due to the stack being too deeply nested. process.nextTick avoids that similar to the way setTimeout(fn,0) will by clearing the callstack on each iteration. It simply defers the execution of the passed...

Using CPS, as mentioned by M. Shaw. show' :: Tree -> String show' = \tree -> go tree id where go (Node left right) c = go left (\l -> go right (\r -> c ("(Node " ++ l ++ " " ++ r ++ ")"))) go Leaf c =...

java,recursion,matrix,tail-recursion

If I understand your question correctly, you want to propagate the needed value to neighbors with equal value to origin. the point here, is to make each node in the grid acts like a automaton, to pass the value to the neighbor if itself gets changed. following is the code,...

scala,f#,functional-programming,tail-recursion,continuation-passing

The second call to go on line 4 is not in tail position, it is wrapped inside an anonymous function. (It is in tail position for that function, but not for go itself.) For continuation passing style you need Proper Tail Calls, which Scala unfortunately doesn't have. (In order to...

recursion,groovy,tail-recursion

Based on the tip user2864740 gave, here's the tail recursive implementation. It should be as efficient as the non-tail-recursive one I posted in the question. @TailRecursive Node append(Node prevTail = this, Node tail = this?.next, Node right) { if (!right) return left if (!prevTail) return right if (!tail) prevTail.next =...

python,python-3.x,recursion,python-idle,tail-recursion

First of all, in this part, the first line is unnecessary since xCalc will be immediately overwritten with xStart: xCalc = 0 xCalc = xStart Secondly, if you observe the code carefully, you see that if xCalc ever reaches 1 it will just loop forever: def collatzCalc(xStart,calcs): ... xCalc =...

algorithm,scala,recursion,tail-recursion

Some things just are not tail recursive, and any attempt to transform them will end up building the stack manually. In this case, however, we can accumulate (untested, don't have scala): def countSteps(n: Int): Int = { if (n < 0) return 0 countStepsAux(n, 0, 1, 0, 0) } def...

c,haskell,recursion,tail-recursion

The linked page explains how to solve the problem with a two-finger solution; it's a bit surprising that they don't simply write the recursive version, which would be simple and clear. (In my experience, you don't succeed at interviews by providing tricky and obscure code when there is a simple...

Your function is: (define (tstFunc lst1 lst2) ; 0 (define (tstFunc-helper ; helper function 1 ls1 ; its 1st argument <-----------------\ 2 ls2 ; 2nd argument <--------------\ | 3 result ) ; 3rd argument | | 4 ; | | 5 (if (or (null? ls1) (null? ls2)) ; | |...

python,recursion,tail-recursion

def wrapper(n,k): list=[] for i in range(1,n+1): list.append(str(i)) rec_seq(list,k,0,'') def rec_seq(list,k,i,prefix): #base case if k==0: print prefix return else: for c in list[i:None]: if prefix=='': newPrefix=prefix+c rec_seq(list,k-1,i+1,newPrefix) else: if int(c)>int(prefix[-1]): newPrefix=prefix+c rec_seq(list,k-1,i+1,newPrefix) return if __name__=='__main__': wrapper (5,3) ...

Adding an accumulator can be done with a standard process: counter( T , List , X ) :- counter( T , List , 0 , X ) . counter( _ , [] , Acc , Acc ) . counter( T , [T|D] , SoFar , Result ) :- Updated is...

java,algorithm,time-complexity,tail-recursion

The matrix has very simple structure (I draw only top right half, bottom left is the same, mirrored) 0 1 2 3 4 5 ... . 0 1 2 3 4 ... . . 0 1 2 3 ... . . . 0 1 2 ... . . . ....

Just remove the parenthesis when the function calls itself: let my_map ff list = let rec mapAcc ff_inner list_inner acc = match list_inner with | [] -> acc | front::rest -> mapAcc ff_inner rest (ff_inner(front) :: acc) mapAcc ff list [] otherwise everything contained there is interpreted as a single...

javascript,tail-recursion,ecmascript-6

This is probably something that was added for completeness more than anything else. After all, new isn't much more than a function call on a new object. There are a few examples that are not entirely contrived, such as this singly LinkedList: function LinkedList(list, next = null) { this.next =...

recursion,scheme,racket,tail-recursion

Here's the correct way to call the recursion: (define (sumof a b q r) (define (sum q) (+ (* (expt q 2) a) b)) (if (= q r) 0 (+ (sum q) (sumof a b (+ q 1) r)))) You should pass along the parameter that changes at each iteration,...

algorithm,tail-recursion,tail-call-optimization

That's going to be implementation dependent, and compiler dependent - but the fact is, it could be used for any tail call, not only recursive one. Inlining a method can be easily done for any recursive call, even if it's not the method itself. A special benefit for it would...

scala,recursion,compiler-optimization,tail-recursion

As per the scaladoc: A method annotation which verifies that the method will be compiled with tail call optimization. If it is present, the compiler will issue an error if the method cannot be optimized into a loop. This is a verification to trigger an error if you thought you...

haskell,recursion,tail-recursion

removeFirst p xs = [] This always returns the empty list and it matches all arguments. I think you mean this. removeFirst _ [] = [] ...

haskell,recursion,tail-recursion,binomial-coefficients

Yes. There is a standard trick of using an accumulator to achieve tail recursion. In your case, you'll need two of them (or accumulate one rational number): binom :: Int -> Int -> Int binom = loop 1 1 where loop rn rd _ 0 = rn `div` rd loop...

functional-programming,scheme,tail-recursion,callstack

Racket allows you to store values in the call stack. You can use this to keep track of the depth. Here is how I would do it: #lang racket ;;; This module holds the tools for keeping track of ;;; the current depth. (module depth racket (provide (rename-out [depth-app #%app])...

algorithm,logic,tail-recursion,eiffel

By substituting all flow-of-control constructs with gotos, (essentially turning the code from Eiffel into pseudocode,) and allowing if statements to execute only gotos, it can be shown that both functions end up consisting of the exact same set of instructions. Let me begin by copying the original tail_rec here for...

ruby,recursion,jruby,tail-recursion

Tail recursion is not the difference here. In fact, Ruby does not do anything to optimize tail calls. The difference is that the naive algorithm recursively calls itself twice each time it's called, giving O(2n) performance, which means the runtime goes up exponentially as N increases. The tail-call version runs...

The usual way to use CPS is to pass the result to the given continuation: let rec calcLength x k = match x with | Circle (_,r) -> k (System.Math.PI * r * 2.) | Ellipse (_,r1,r2) -> k (System.Math.PI * 2. * sqrt( (r1 * r1 ) + (r2...

python,dictionary,tail-recursion

dict.copy is a shallow copy, not a deep copy. That means, the list in the dictionary is not copied, but shared between the copies. Use copy.deepcopy from the copy-module instead.

c++,c,recursion,tail-recursion

The trick is that if the compiler notices the tail recursion, it can compile a goto instead. It will generate something like the following code: int fun_optimized(int n, int sofar) { start: if(n == 0) return sofar; sofar = sofar*n; n = n-1; goto start; } And as you can...

There are a couple of erroneous () surrounding the last function call, and the formatting can be improved. Remember, in Scheme a pair of () means "function application" (that explains the error message attempt to call a non-procedure), so you have to be careful where you put them. Try this...

From your question it's not entirely clear what is the purpose of making your function tail-recusrive. If you are trying to reduce cpu/memory usage, then you should use memoization (mentioned in the Guvante's answer). Meanwhile, there is a way to make almost any function tail-recursive, known as continuation-passing style. Your...

Ah I found your problem. You must only return the empty string if n == 0. Returning str will return that extra last letter a second time as the call repeatFront(Ch, 1) and repeatFront(C, 0) both return C. Fix by changing the return on n==0 to return ""; : if(n==0)...

scala,recursion,tail-recursion

It happens because the return in your first snippet is a non-local one (it's nested inside a lambda). Scala uses exceptions to compile non-local return expressions, so the code gets transformed by the compiler from this: @annotation.tailrec def listSize(l : Seq[Any], s: Int = 0): Int = { if (l.isEmpty)...

recursion,racket,tail-recursion

It isn't, really: (define (convert-base from to n) (let f ([n n] [mul 1] [res 0]) (if (zero? n) res (f (quotient n to) (* mul from) (+ res (* mul (modulo n to))))))) Testing > (convert-base-y 10 2 10) 1010 > (convert-base-y 10 8 64) 100 ...

javascript,recursion,tail-recursion,tail-call-optimization

Tail call optimisation is supported in JavaScript. No browsers implement it yet but it's coming as the specification (ES2015) is finalized and all environments will have to implement it. Transpilers like BabelJS that translate new JavaScript to old JavaScript already support it and you can use it today. The translation...