tail-recursion

Scheme. Tail recursive ?

Hi guys, any tail-recursive version for the below mentioned pseudocode ? Thanks ! (define (min list) (cond ((null? list) '()) ((null? (cdr list)) (car list)) (#t (let ((a (car list)) (b (min (cdr list)))) (if (< b a) b a))))) ...

Clojure warning/error on tail call optimization failure

In Scala 2.8.x, a new annotation (@tailrec) has been added that gives a compile-time error if the compiler cannot perform a tail-call optimization on the annotated method. Is there some similar facility in Clojure with respect to loop/recur? EDIT: After reading the first answer to my question (thanks, Bozhidar Batsov) and further searc...

How do you make this Haskell power function tail recursive?

turboPower a 0 = 1 turboPower a b | even b = turboPower (a*a) (b `div` 2) | otherwise = a * turboPower a (b-1) THANKS! ...

How do I break out of a loop in Scala?

For Problem 4 of Project Euler How do I break out a loop? var largest=0 for(i<-999 to 1 by -1) { for (j<-i to 1 by -1) { val product=i*j if (largest>product) // I want to break out here else if(product.toString.equals(product.toString.reverse)) largest=largest max product } } And does anyone know how to turn nested for l...

Scheme accumulative recursion with lists

How can I pass a list as a parameter to a function adding elements to it recursively,and have it unmodified when it comes out of recursion? I want to use the list at each level of recursion with the list having the values added by deeper recursion levels. To be more specific I want to do a DFS search on a graph and I want to store in t...

Best Functional Approach

I have some mutable scala code that I am trying to rewrite in a more functional style. It is a fairly intricate piece of code, so I am trying to refactor it in pieces. My first thought was this: def iterate(count:Int,d:MyComplexType) = { //Generate next value n //Process n causing some side effects return iterate(count - 1, n) }...

How can I implement a tail-recursive list append?

A simple append function like this (in F#): let rec app s t = match s with | [] -> t | (x::ss) -> x :: (app ss t) will crash when s becomes big, since the function is not tail recursive. I noticed that F#'s standard append function does not crash with big lists, so it must be implemented differently. So I wondered: How ...

Why does s ++ t not lead to a stack overflow for large s?

I'm wondering why Prelude> head $ reverse $ [1..10000000] ++ [99] 99 does not lead to a stack overflow error. The ++ in the prelude seems straight forward and non-tail-recursive: (++) :: [a] -> [a] -> [a] (++) [] ys = ys (++) (x:xs) ys = x : xs ++ ys EDIT: Initially, I thought the issue has something to do with the way ++ is de...

Clojure: Avoiding stack overflow in Sieve of Erathosthene?

Here's my implementation of Sieve of Erathosthene in Clojure (based on SICP lesson on streams): (defn nats-from [n] (iterate inc n)) (defn divide? [p q] (zero? (rem q p))) (defn sieve [stream] (lazy-seq (cons (first stream) (sieve (remove #(divide? (first stream) %) (rest stream)))))) (def primes (si...

How to create a recursive data structure value in (functional) F#?

How can a value of type: type Tree = | Node of int * Tree list have a value that references itself generated in a functional way? The resulting value should be equal to x in the following Python code, for a suitable definition of Tree: x = Tree() x.tlist = [x] Edit: Obviously more explanation is necessary. I am trying to learn...

Recursive functions in computation expressions

Some background first. I am currently learning some stuff about monadic parser combinators. While I tried to transfer the 'chainl1' function from this paper (p. 16-17), I came up with this solution: let chainl1 p op = parser { let! x = p let rec chainl1' (acc : 'a) : Parser<'a> = let p' = parser { let! f = op ...

Recursive computation expressions

In a previous question I was told how to rewrite my computation expressions so it uses tail recursion. I rewrote my code but still got a StackOverflowException. To locate the problem I wrote some small code using a state monad (taken from this blog entry): type State<'a, 's> = State of ('s -> 'a * 's) let runState (State s) initialSta...

Recursive method in Java seems to just "goto" the first line of the method instead of actually go into the next call.

I am creating a factory that makes rooms, and it is passed an int of steps and a start room and it is supposed to do a step, build a room, and then call itself with one fewer step and the new room as the start room. The problem is that it never ends. In the debugger, I can see that it's calling itself, which creates another method call i...

Are tail-recursive functions ALWAYS to be avoided?

If I recall correctly, tail recursive functions always have an easy non-recursive equivalent. Since recursion involves unnecessary function call overhead, it's better to do it the non-recursive way. Is this assumption always true? Are there any other arguments for/against tail-recursion? ...

haskell - foldl vs foldr question

I wanted to test foldl vs foldr. From what I've seen you should use foldl over foldr when ever you can due to tail reccursion optimization. This makes sense. However, after running this test I am confused: foldr (takes 0.057s when using time command): a::a -> [a] -> [a] a x = ([x] ++ ) main = putStrLn(show ( sum (foldr a [] [0.. 1000...

Beginner question about heap and garbage in Clojure

I have a question about Clojure: I am trying to learn the language by going through Project Euler and I don't understand what is going on under the hood: The following code is designed to use return a list of all prime numbers up to lim. I would think that it should be O(n) in heap-space because I make a list of all the numbers up to li...

Combine memoization and tail-recursion

Is it possible to combine memoization and tail-recursion somehow? I'm learning F# at the moment and understand both concepts but can't seem to combine them. Suppose I have the following memoize function (from Real-World Functional Programming): let memoize f = let cache = new Dictionary<_, _>() (fun x -> match cache.Try...

Tail recursive copy of a seq to a list in F#

Hello, I am trying to build a list from a sequence by recursively appending the first element of the sequence to the list: open System let s = seq[for i in 2..4350 -> i,2*i] let rec copy s res = if (s|>Seq.isEmpty) then res else let (a,b) = s |> Seq.head Console.WriteLine(string a) l...

C tail call optimization

I often hear people say that C doesn't perform tail call elimination. Even though it's not guaranteed by the standard, isn't it performed in practice by any decent implementation anyhow? Assuming you're only targeting mature, well implemented compilers and don't care about absolute maximum portability to primitive compilers written for...

Are any Javascript engines tail call optimized?

I have a tail recursive pathfinding algorithm that I've implemented in Javascript and would like to know if any (all?) browsers would possibly get stack overflow exceptions. ...