1,375 questions
1
vote
0
answers
70
views
Tail recursive MergeSort for Tuples in Scala
so im trying to make a mergesort for list with tuples, but no matter what i look at i dont see anything wrong with the implementation im doing. But still @tailrec is not being detected by Scala for ...
1
vote
2
answers
138
views
Will this be a tail call or not?
Is the recursive call in my code a tail call or is it just ordinary recursion?
void sum(const int values[], size_t count,int* result){
if(count <= 0) return;
*result += values[0];
sum(values +...
0
votes
3
answers
124
views
Tail-Recursive Binomial Coefficient Function in Java
I'm looking to implement a tail-recursive function to calculate the binomial coefficient of two numbers n and k. If k > n then 0 should be returned. Similarly if n == k or k == 0 it should return 1....
3
votes
2
answers
114
views
F# foldBack conversion to tail recursive function
For learning purposes I've emulated List.foldBack. The emulated version is head-recursive.
Is there an elegant way to convert it to the tail-recursive version?
let li : int list = [1;2;3]
let rec ...
1
vote
1
answer
70
views
Do tail-recursive functions reuse a single environment in Scheme?
I'm currently taking an undergraduate course in functional programming, and we just learned about environments in Scheme. From what I understand, an environment is the context in which a function is ...
2
votes
1
answer
118
views
How can I avoid recursion in this JavaScript function that uses Promises?
I have a JavaScript function that generates an endless slideshow. The code works, but I'm concerned about each iteration ending in a recursive call to itself. Using developer tools, it appears that ...
2
votes
1
answer
124
views
What is the exact compiler optimization applied here expect for tail recursion elimination?
I'm compiling a simple C program, implementing an inorder tree traversal function:
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(...
14
votes
1
answer
631
views
Optimization of tail recursion in R
Since version 4.4.0, R supports tail recursion through the Tailcall function. I automatically assumed that it means an improvement for codes that use tail recursion.
However, consider the following ...
1
vote
0
answers
79
views
Why doesn't F# inline this inner function?
I have this active pattern:
[<return: Struct>]
let (|Integer|_|) self =
let rec loop acc (isNegative: bool) self =
match self with
| C(digit, tail) when (...
-2
votes
1
answer
77
views
Why Does Stack Size Vary By Function (V8 Engine)?
I was just experimenting to see the max call stack size on my machine, and I discovered something very peculiar. I had the following two functions:
function fact(o) {
if (o == 0) return 1;
...
-1
votes
1
answer
101
views
What is the difference between head and tail recursion when reversing a linked list?
I am learning about different recursive approaches for reversing a linked list in C++. I have implemented both head and tail recursion methods, but I'm unsure about their differences and which one is ...
0
votes
2
answers
155
views
Is there a difference in Haskell, regarding tail-recursion, between using guards that return boolean values and using (||) operators? [closed]
Let's use the following function as an example:
findWord :: [[Char]] -> [(Int, Int)] -> (Int, Int) -> String -> Bool
findWord _ _ _ [] = True -- Word was found
...
0
votes
0
answers
38
views
When combining iteration and recursion, how do I express the recursion via tail calls?
I am working on a practice problem and I have found a recursive solution. However, I can't figure out how to express the solution as tail recursion.
I think that the issue that I am having can be ...
0
votes
1
answer
108
views
can someone help me understand how to solve the following tail recursion optimization problem?
Apply tail recursion optimization to the following function and write the target code generated by the optimizing compiler:
int foo(int n, int m) {
if(n<1)
return m+1;
else
...
3
votes
1
answer
113
views
Array and List recursion performance
I solving the problem of "Best-time-to-buy-and-sell-stock" at leetcode https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ with 2 approaches:
With first, I ...
0
votes
0
answers
58
views
TailRec optimisation and export
What's wrong with the following code?
class A {
val m = new scala.collection.concurrent.TrieMap[Int, Int]()
export m.clear
}
The compilation error (Scala 3.4.0):
"TailRec optimisation not ...
2
votes
1
answer
129
views
Is `Pair` a valid instance of `MonadRec`?
In the paper Stack Safety for Free, Phil Freeman defines the MonadRec type class as follows.
class (Monad m) <= MonadRec m where
tailRecM :: forall a b. (a -> m (Either a b)) -> a -> m b
...
1
vote
2
answers
140
views
Improving efficiency in Stirling numbers calculation
I've been trying to explore the possibilities of recursion in Haskell, but I don't know much about improving efficiency when facing large recursions. Today, I wanted to make a function that calculates ...
0
votes
1
answer
234
views
How can I create a tail recursive merge method in Scala on a self-referential tree structure (or is it even possible)?
UPDATE 2024.03.16: Provided code that produces the correct output, but is still not tail-recursive.
How can I create a tail recursive merge method in Scala on a self-referential tree structure (or is ...
-1
votes
3
answers
167
views
How to optimize this algorithm using tail recursion?
I want to optimize this dfs with tail recursion,but i don't konw how to realize it, could any help me?
My first solution is the following code, i want modify it with tail recursion to get test case ...
0
votes
0
answers
85
views
XSLT recursion crashes after 1000 calls - how to transform it to DVC style?
Here is my function:
<func:function name="entry-check">
<xsl:param name="bunch"/>
<xsl:param name="history"/>
<xsl:param name="index&...
1
vote
2
answers
150
views
Stack overflow when composing functions in F#
Basically, my problem is that I'm trying to compose a very large number of functions, so I'm creating a deep chain of composed functions. Here is my code:
let rec fn (f : (State -> State option) -&...
2
votes
3
answers
122
views
How are my recursive calls not tail calls here?
In the following code, all calls to retry get the warning "Recursive call is not a tail call":
private tailrec suspend fun <T> retry(numberOfRetries: Int, block: suspend () -> T): ...
1
vote
1
answer
84
views
How to collect maximal non-overlapping ascending/descending prefixes of a random sequence of numbers
Let S = [x1, x2, ..., xn] be a random sequence of distinct numbers. We can define a run of S as:
a sequence [x1, x2, ..., xi], for 1 ≤ i ≤ n, such that x1 < x2 < ... < xi, and i = n or xi &...
0
votes
1
answer
55
views
Append a list on to another in oCaml
I need a tail recursive function that appends a list1 infront of list2.
I tried it this way
let rec append lst1 lst2 acc =
match lst1 with
| [] -> acc @ lst2
| hd::tl -> append lst1 tl (...
-3
votes
1
answer
115
views
Recursion in a tailored map function - don't understand the program flow
I am learning tail recursion and don't understand the flow of this example.
I am using VSCode debugger and don't understand why when the program reaches return[f(arg), *result] it goes to result = ...
0
votes
1
answer
99
views
Confused about how tail recursion works?
I'm using an example of adding two linked lists together from leetcode. The lists are in reverse order and the resulting list must be reversed as well. My code is recursive and it's only faster than ...
1
vote
2
answers
815
views
Tail call optimization in Clojure
I have the following function.
(defn get-all-str
"Get a list of all strings of length n,
consisting of characters from the alphabet list
and not containing two identical ...
3
votes
0
answers
196
views
Performance of deep recursion versus tail recursion
I have an algorithm using deep recursion (20 seconds). Perl complains and I shut it up with "no warnings 'recursion'". I change it to tail recursion (32 seconds) in the hope that it will be ...
0
votes
0
answers
42
views
Identifying Tail-Recursion [duplicate]
Using Racket, I have written the following function, poly-eval, to compute the value of a polynomial given the coefficients and an integer:
(define (poly-eval coeffs x)
(letrec ([helper (lambda (...
1
vote
1
answer
68
views
Is an iterative process that returns a list with size that increases by iteration any different from an one that returns a scalar?
This actually comes from me initially misreading the text of Exercise 1.12.
The request is indeed to
Write a procedure that computes elements of Pascal's triangle by means of a recursive process.
I ...
2
votes
1
answer
71
views
Why does adding tailrec make a incorrect kotlin corecursion work?
I came across this interesting problem while reading Joy of Kotlin book. In chapter 4, while explaining tail recursion author provides an implementation for adding two numbers as below.
tailrec fun ...
-1
votes
2
answers
82
views
Recursion method is invoked even after loop condition is met
public int removeMin(Integer[] arr, int count) {
Integer[] tempArr = new Integer[arr.length -1];
int index = 0;
for (int i = 1; i<arr.length; i++) {
tempArr[index] = arr[i] ...
1
vote
0
answers
79
views
MailboxProcessor memory usage
I was testing early-returning in F# async and noticed some strange memory usage behaviour with MailboxProcessor. Consider this program:
let mp = MailboxProcessor<bool>.Start (fun inbox ->
...
0
votes
2
answers
98
views
stack variable disappears at the last action of a function?
The advantage of tail recursion is that we call the function (recursion) again in the last action of the code, so the stack variables doesn't need to be saved.
So here do this will act the same? and I ...
-1
votes
1
answer
82
views
If python don't have tail recursion in it, then why my code on leetcode is working differently for different recursions?
As per the link tail recursion is not present in python. I was working on leetcode problem where two inputs are given, number and its power. The power can be negative also. I need to find out exponent ...
1
vote
3
answers
83
views
Recursive iteration of an array
I have an array of classes:
const transferClasses = [
{
id: "c5d91430-aaab-ed11-8daf-85953743f5cc",
name: "Class1",
isTransfer: false,
children: [],
},
{
...
-2
votes
1
answer
46
views
Why does it not work ? Can Someone please explain Memory Allocation, static/non static, global/local variables/ deepcopy used in stack
It is a simple recursive function to print array elements in reverse.
When I call the function above the print statement, it gives me index -1 outOfBoundException.
When I print before calling the ...
0
votes
1
answer
143
views
Is tail call (including tail recursion) compiler/implementation dependent?
Searching tail recursion on the internet I stumbled on How does compiler know whether the recursion is a tail recursion or not and how does it optimize tail recursion. If I understand correctly then ...
-1
votes
1
answer
79
views
How to change this nested recursion to linear recursion?
I want to change this function of nested recursion to linear recursion or optimally is tail recursion.
long long x(int n) {
if (n == 0) return 1;
int ret = 0;
for (int i = 0; i < n; ++i)...
1
vote
1
answer
113
views
How to write a recursion function using 2 accumulators?
I'm new to Python and recursion is a foreign thing to me. For my assignment I have functions that involve tail recursion, a while loop, or a generator as specified by _t, _w, or _g if the function ...
0
votes
1
answer
96
views
Trying to optimize the code using @tailrec but failing
I want to use @tailrec in Scala to convert the code to tail recursive but I get an error saying the function is not in the tail position but I disagree with the conclusion of the compiler. I ...
1
vote
0
answers
75
views
gcc can't optimize tail recursion of a std::vector<int>, exit with code 139?
I have this program:
#include <iostream>
#include <vector>
int foo(std::vector<int> bar) {
if (bar[0] == 0)
return bar[0];
else
{
bar[0] -= 1;
...
0
votes
3
answers
118
views
Idiomatic Scala way to traverse Iterator-like data structure
Given a class from a legacy library that behaves like an Iterator such that you can traverse it's content with hasNext and next but it does not implement the Iterator interface:
class LegacyIterator[T]...
0
votes
1
answer
270
views
How to remove last node of a linked list (Python)
The goal is to remove the last node of a linked list. (Python) The code that I have written only added to the list instead of taking the tail away. I'm not sure if the error is coming from this part ...
2
votes
2
answers
161
views
Stack overflow or tail recursion?
I'm trying to find out if the following code piece is good or bad practice. It's about a html query string that should be parsed by my API. It's very convenient to use recursion to trim an arbitrary ...
1
vote
2
answers
509
views
tail recursion to add element to end of list in Haskell
I wrote this simple function to append an element to the end of a list recursively:
--takes arguments x and lst and appends x to the end of list
append1::a->[a]->[a]
append1 x [] = x:[]
append1 ...
1
vote
1
answer
137
views
Converting a simple recursive haskell function to be tail recursive
2 weeks new to haskell and functional programming. In the process of covering foldl and foldr in class, I found that I was quite new to tail recursion and never actually tried writing a tail recursive ...
4
votes
2
answers
320
views
Automatically detect whether a Haskell function is tail recursive
I'm currently writing an auto-grader for a Haskell course. For the section on "tail-recursion", I need a way to automatically and safely detect whether a given Haskell function is tail-...
2
votes
1
answer
175
views
Tail-recursive string splitting in Haskell
I'm considering the problem of splitting a string s at a character c.
This is expressed as
break (c ==) s
where the Haskell library definition of break (c ==) close enough to
br [] = ([],[])
br ...