in reply to Re^4: Recursion problem
in thread Recursion problem

Hm. A mathemeatically correct degenerate case I suppose, but given that the list can contain negative numbers, which makes a zero target a legitimate non-degenerate possibility, I can't see a useful case for returning an empty list and calling it success.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^6: Recursion problem
by moritz (Cardinal) on May 25, 2008 at 11:41 UTC
    I think you can argue both ways.

    My point was just that sometimes the base case for a recursion sometimes is much simpler than it seems. Your original code does roughly for both base case and recursive case (it iterates over the list and returns true if some condition holds), which is usually a sign that the base case could be chosen simpler.

    I frequently fell into that trap, resulting in longer and error-prone code, so I'd thought it's best to point out.

    Usually I'd handle such a case like that:

    sub sumTo { return 0 if $_[0] == 0 && @_ > 1; _sumTo(@_); # or &_sumTo if you want to be cryptic } sub _sumTo { my ($target, @list) = @_; return 1 if $target == 0; return 0 if @list == 0; # here goes the recursive call to _sumTo }

    If you don't like wrapper functions you can use caller to determine if the current call is recursive.

      I think you can argue both ways.

      Okay, Here's my argument for my way :)

      If I'm auditing a set of books and need to understand the absence of a cheque to a customer-supplier one month, and go looking for a combination of debits and credits that sum to zero (hence no cheque needed raising), I would not be best pleased if my algorithm came back and told me that "this (empty) set of no credits and no debits could account for that possibility".

      Your original code does roughly for both base case and recursive case ...

      Actually, that is very deliberate. I try very hard to reduce the number of special cases in recursive algorithms. Recursive nirvana is no special cases, but that is exceptionally rare. In real life even many of the cases that mathematicians treat as having no special cases, eg. succ(n), actually have machine limits.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.