Search Results

Search found 1553 results on 63 pages for 'tail recursion'.

Page 1/63 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Tail-recursive implementation of take-while

    - by Giorgio
    I am trying to write a tail-recursive implementation of the function take-while in Scheme (but this exercise can be done in another language as well). My first attempt was (define (take-while p xs) (if (or (null? xs) (not (p (car xs)))) '() (cons (car xs) (take-while p (cdr xs))))) which works correctly but is not tail-recursive. My next attempt was (define (take-while-tr p xs) (let loop ((acc '()) (ys xs)) (if (or (null? ys) (not (p (car ys)))) (reverse acc) (loop (cons (car ys) acc) (cdr ys))))) which is tail recursive but needs a call to reverse as a last step in order to return the result list in the proper order. I cannot come up with a solution that is tail-recursive, does not use reverse, only uses lists as data structure (using a functional data structure like a Haskell's sequence which allows to append elements is not an option), has complexity linear in the size of the prefix, or at least does not have quadratic complexity (thanks to delnan for pointing this out). Is there an alternative solution satisfying all the properties above? My intuition tells me that it is impossible to accumulate the prefix of a list in a tail-recursive fashion while maintaining the original order between the elements (i.e. without the need of using reverse to adjust the result) but I am not able to prove this. Note The solution using reverse satisfies conditions 1, 3, 4.

    Read the article

  • Tail recursion in C++

    - by Phenom
    Can someone show me a simple tail-recursive function in C++? Why is tail recursion better, if it even is? What other kinds of recursion are there besides tail recursion?

    Read the article

  • tail stops displaying in case of a log rotation

    - by Rudy Vissers
    I have to tail the log of a server (servicemix) and the log rotation is enabled. As soon as the rotation happens, tail stops displaying. I did some investigations and it is a bug in Debian : Debian Bug Report. The bug has been around for a long time ago. Does anyone knows if this bug in Ubuntu is to be fixed? I'm on Ubuntu 12.04 64 bit. I don't have to mention that this bug is total hell! Every time I have the problem, I have to interrupt the command tail and re-execute the command!

    Read the article

  • Functional Programming - Lots of emphasis on recursion, why?

    - by peakit
    I am getting introduced to Functional Programming [FP] (using Scala). One thing that is coming out from my initial learnings is that FPs rely heavily on recursion. And also it seems like, in pure FPs the only way to do iterative stuff is by writing recursive functions. And because of the heavy usage of recursion seems the next thing that FPs had to worry about were StackoverflowExceptions typically due to long winding recursive calls. This was tackled by introducing some optimizations (tail recursion related optimizations in maintenance of stackframes and @tailrec annotation from Scala v2.8 onwards) Can someone please enlighten me why recursion is so important to functional programming paradigm? Is there something in the specifications of functional programming languages which gets "violated" if we do stuff iteratively? If yes, then I am keen to know that as well. PS: Note that I am newbie to functional programming so feel free to point me to existing resources if they explain/answer my question. Also I do understand that Scala in particular provides support for doing iterative stuff as well.

    Read the article

  • Does MATLAB perform tail call optimization?

    - by Shea Levy
    I've recently learned Haskell, and am trying to carry the pure functional style over to my other code when possible. An important aspect of this is treating all variables as immutable, i.e. constants. In order to do so, many computations that would be implemented using loops in an imperative style have to be performed using recursion, which typically incurs a memory penalty due to the allocation a new stack frame for each function call. In the special case of a tail call (where the return value of a called function is immediately returned to the callee's caller), however, this penalty can be bypassed by a process called tail call optimization (in one method, this can be done by essentially replacing a call with a jmp after setting up the stack properly). Does MATLAB perform TCO by default, or is there a way to tell it to?

    Read the article

  • GUI for watching logs (tail and grep)

    - by Grzegorz Oledzki
    Could you recommend a GUI application with powerful log watching capabilities? Generally it would work as tail -f in GUI, but on top of that following features would be very useful: filtering out some lines based on (regular) expressions coloring some lines based on (regular) expressions interactive search saveable configuration easily applicable to different files notifications based on (regular) expressions A similar tool on Windows is BareTail and its paid version - BareTailPro

    Read the article

  • GUI for watching logs (tail and grep)

    - by Grzegorz Oledzki
    Could you recommend a GUI application with powerful log watching capabilities? Generally it would work as tail -f in GUI, but on top of that following features would be very useful: filtering out some lines based on (regular) expressions coloring some lines based on (regular) expressions interactive search saveable configuration easily applicable to different files notifications based on (regular) expressions A similar tool on Windows is BareTail and its paid version - BareTailPro

    Read the article

  • What's a nice explanation for recursion?

    - by Gulshan
    This question is inspired by What's a nice explanation for pointers? So, what can be a nice explanation of the recursion? Update: The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily? I expected some detailed answers. N.B. : Even I am going to post one answer. But to be fair, it will be few hours later.

    Read the article

  • Recursion VS memory allocation

    - by Vladimir Kishlaly
    Which approach is most popular in real-world examples: recursion or iteration? For example, simple tree preorder traversal with recursion: void preorderTraversal( Node root ){ if( root == null ) return; root.printValue(); preorderTraversal( root.getLeft() ); preorderTraversal( root.getRight() ); } and with iteration (using stack): Push the root node on the stack While the stack is not empty Pop a node Print its value If right child exists, push the node's right child If left child exists, push the node's left child In the first example we have recursive method calls, but in the second - new ancillary data structure. Complexity is similar in both cases - O(n). So, the main question is memory footprint requirement?

    Read the article

  • Performance: recursion vs. iteration in Javascript

    - by mastazi
    I have read recently some articles (e.g. http://dailyjs.com/2012/09/14/functional-programming/) about the functional aspects of Javascript and the relationship between Scheme and Javascript (the latter was influenced by the first, which is a functional language, while the O-O aspects are inherited from Self which is a prototyping-based language). However my question is more specific: I was wondering if there are metrics about the performance of recursion vs. iteration in Javascript. I know that in some languages (where by design iteration performs better) the difference is minimal because the interpreter / compiler converts recursion into iteration, however I guess that probably this is not the case of Javascript since it is, at least partially, a functional language.

    Read the article

  • Resources for improving your comprehension of recursion?

    - by Andrew M
    I know what recursion is (when a patten reoccurs within itself, typically a function that calls itself on one of its lines, after a breakout conditional... right?), and I can understand recursive functions if I study them closely. My problem is, when I see new examples, I'm always initially confused. If I see a loop, or a mapping, zipping, nesting, polymorphic calling, and so on, I know what's going just by looking at it. When I see recursive code, my thought process is usually 'wtf is this?' followed by 'oh it's recursive' followed by 'I guess it must work, if they say it does.' So do you have any tips/plans/resources for building up your skills in this area? Recursion is kind of a wierd concept so I'm thinking the way to tackle it may be equally wierd and inobvious.

    Read the article

  • XSLT multiple string replacement with recursion

    - by John Terry
    I have been attempting to perform multiple (different) string replacement with recursion and I have hit a roadblock. I have sucessfully gotten the first replacement to work, but the subsequent replacements never fire. I know this has to do with the recursion and how the with-param string is passed back into the call-template. I see my error and why the next xsl:when never fires, but I just cant seem to figure out exactly how to pass the complete modified string from the first xsl:when to the second xsl:when. Any help is greatly appreciated. <xsl:template name="replace"> <xsl:param name="string" select="." /> <xsl:choose> <xsl:when test="contains($string, '&#13;&#10;')"> <xsl:value-of select="substring-before($string, '&#13;&#10;')" /> <br/> <xsl:call-template name="replace"> <xsl:with-param name="string" select="substring-after($string, '&#13;&#10;')"/> </xsl:call-template> </xsl:when> <xsl:when test="contains($string, 'TXT')"> <xsl:value-of select="substring-before($string, '&#13;TXT')" /> <xsl:call-template name="replace"> <xsl:with-param name="string" select="substring-after($string, '&#13;')" /> </xsl:call-template> </xsl:when> <xsl:otherwise> <xsl:value-of select="$string"/> </xsl:otherwise> </xsl:choose> </xsl:template>

    Read the article

  • tail -f and then exit on matching string

    - by Patrick
    I am trying to configure a startup script which will startup tomcat, monitor the catalina.out for the string "Server startup", and then run another process. I have been trying various combinations of tail -f with grep and awk, but haven't got anything working yet. The main issue I am having seems to be with forcing the tail to die after grep or awk have matched the string. I have simplified to the following test case. test.sh is listed below: #!/bin/sh rm -f child.out ./child.sh > child.out & tail -f child.out | grep -q B child.sh is listed below: #!/bin/sh echo A sleep 20 echo B echo C sleep 40 echo D The behavior I am seeing is that grep exits after 20 seconds , however the tail will take a further 40 seconds to die. I understand why this is happening - tail will only notice that the pipe is gone when it writes to it which only happens when data gets appended to the file. This is compounded by the fact that tail is to be buffering the data and outputting the B and C characters as a single write (I confirmed this by strace). I have attempted to fix that with solutions I found elsewhere, such as using unbuffer command, but that didn't help. Anybody got any ideas for how to get this working how I expect it? Or ideas for waiting for successful Tomcat start (thinking about waiting for a TCP port to know it has started, but suspect that will become more complex that what I am trying to do now). I have managed to get it working with awk doing a "killall tail" on match, but I am not happy with that solution. Note I am trying to get this to work on RHEL4.

    Read the article

  • tail -f and then exit on matching string

    - by Patrick
    I am trying to configure a startup script which will startup tomcat, monitor the catalina.out for the string "Server startup", and then run another process. I have been trying various combinations of tail -f with grep and awk, but haven't got anything working yet. The main issue I am having seems to be with forcing the tail to die after grep or awk have matched the string. I have simplified to the following test case. test.sh is listed below: #!/bin/sh rm -f child.out ./child.sh > child.out & tail -f child.out | grep -q B child.sh is listed below: #!/bin/sh echo A sleep 20 echo B echo C sleep 40 echo D The behavior I am seeing is that grep exits after 20 seconds , however the tail will take a further 40 seconds to die. I understand why this is happening - tail will only notice that the pipe is gone when it writes to it which only happens when data gets appended to the file. This is compounded by the fact that tail is to be buffering the data and outputting the B and C characters as a single write (I confirmed this by strace). I have attempted to fix that with solutions I found elsewhere, such as using unbuffer command, but that didn't help. Anybody got any ideas for how to get this working how I expect it? Or ideas for waiting for successful Tomcat start (thinking about waiting for a TCP port to know it has started, but suspect that will become more complex that what I am trying to do now). I have managed to get it working with awk doing a "killall tail" on match, but I am not happy with that solution. Note I am trying to get this to work on RHEL4.

    Read the article

  • Are there advantages for using recursion over iteration - other than sometimes readability and elegance?

    - by Prog
    I am about to make two assumptions. Please correct me if they're wrong: There isn't a recursive algorithm without an iterative equivalent. Iteration is always cheaper performance-wise than recursion (at least in general purpose languages such as Java, C++, Python etc.). If it's true that recursion is always more costly than iteration, and that it can always be replaced with an iterative algorithm (in languages that allow it) - than I think that the two remaining reasons to use recursion are: elegance and readability. Some algorithms are expressed more elegantly with recursion. E.g. scanning a binary tree. However apart from that, are there any reasons to use recursion over iteration? Does recursion have advantages over iteration other than sometimes elegance and readability?

    Read the article

  • When there's no TCO, when to worry about blowing the stack?

    - by Cedric Martin
    Every single time there's a discussion about a new programming language targetting the JVM, there are inevitably people saying things like: "The JVM doesn't support tail-call optimization, so I predict lots of exploding stacks" There are thousands of variations on that theme. Now I know that some language, like Clojure for example, have a special recur construct that you can use. What I don't understand is: how serious is the lack of tail-call optimization? When should I worry about it? My main source of confusion probably comes from the fact that Java is one of the most succesful languages ever and quite a few of the JVM languages seems to be doing fairly well. How is that possible if the lack of TCO is really of any concern?

    Read the article

  • How is this recursion properly working when it is iterated through [on hold]

    - by Rakso Zrobin
    Here is my code right now: hasht= {"A":["B", "D", "E"], "B":["C"], "C":["D", "E"], "D":["C", "E"], "E":["B"]} paths=[] def recusive(start, finish, started=true): if start==finish and !started: return start else: for i in hasht[start]: path= start+ recusive(i,finish,false) paths.append(path) print (recusive("C","C",1)) print paths # [CDC, CDEBC, CEBC] I am trying to generate a table like the one on the bottom, but am running into the problem of the string and the array not being able to concatenate. When I just return however, it returns CDC and works, however, exiting the function as return is meant to do. I am wondering how I can improve my code here to (1) make it work, (2) why my logic was faulty. For example, I understand that it generates say [DC], but I am confused as to how to go around that. perhaps index the value returned?

    Read the article

  • Tail the filename, not the file

    - by Craig Walker
    In UNIX (OS X BSD to be precise), I have a "tail -f" command on a log file. From time to time I want to delete this log file so I can more easily review it in my text editor. I delete the file, and then my program recreates it after new activity. However, my tail command (and anything else that was watching the old log file) doesn't update; it's still watching the old, deleted log file. I think I understand why this is (file names simply being pointers to blocks of file data). I'd like to know how I can work around this. Ideally, my tail command (and anything else I point to the file) would be able to read the data from the new file when the file name has been deleted and recreated. How would I do this?

    Read the article

  • How to watch for count of new lines in tail

    - by fl00r
    I want to do something like this: watch tail -f | wc -l #=> 43 #=> 56 #=> 61 #=> 44 #=> ... It counts new lines of tail each second / Linux, CentOs To be more clear. I have got something like this: tail -f /var/log/my_process/*.log | grep error I am reading some error messages. And now I want to count them. How many ~ errors I have got in a second. So one line in a log is one error in a proccess.

    Read the article

  • Can someone describe through code a practical example of backtracking with iteration instead of recursion?

    - by chrisapotek
    Recursion makes backtracking easy as it guarantees that you won't go through the same path again. So all ramifications of your path are visited just once. I am trying to convert a backtracking tail-recursive (with accumulators) algorithm to iteration. I heard it is supposed to be easy to convert a perfectly tail-recursive algorithm to iteration. But I am stuck in the backtracking part. Can anyone provide a example through code so myself and others can visualize how backtracking is done? I would think that a STACK is not needed here because I have a perfectly tail-recursive algorithm using accumulators, but I can be wrong here.

    Read the article

  • tail -f updates slowly

    - by Cliff
    I'm not sure why, but on my Macbook Pro running lion I get slow updates when I issue "tail -f" on a log file that is being written to. I used to use this command all the time at my last company but that was typically on Linux machines. The only thing I can think of that would possibly slow the updates are buffering of output and/or maybe a different update interval on a Mac vs. Linux. I've tried with several commands all which write to stout relatively quickly but give slow updates to the tail command. Any ideas? Update I am merely running a python script with a bunch of prints in it and redirecting to a file vi " my output.log". I expect to see updates near real time but that doesn't seem to be the case.

    Read the article

  • Should not a tail-recursive function also be faster?

    - by Balint Erdi
    I have the following Clojure code to calculate a number with a certain "factorable" property. (what exactly the code does is secondary). (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (factor-9 (quot n 10)))))) Now, I'm into TCO and realize that Clojure can only provide tail-recursion if explicitly told so using the recur keyword. So I've rewritten the code to do that (replacing factor-9 with recur being the only difference): (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (recur (quot n 10)))))) To my knowledge, TCO has a double benefit. The first one is that it does not use the stack as heavily as a non tail-recursive call and thus does not blow it on larger recursions. The second, I think is that consequently it's faster since it can be converted to a loop. Now, I've made a very rough benchmark and have not seen any difference between the two implementations although. Am I wrong in my second assumption or does this have something to do with running on the JVM (which does not have automatic TCO) and recur using a trick to achieve it? Thank you.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >