Skip to content

Commit

Permalink
Added documentation for TailRec, removed empty lines from tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Tritlo committed Dec 23, 2014
1 parent ed01286 commit f4526d0
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 5 deletions.
69 changes: 69 additions & 0 deletions docs/contrib/future.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
==========
__future__ features
==========

.. versionadded:: 0.10.2

Importing from ``__future__`` allows you to add features to
Hy that are not yet in the main language, due to slowing or
being harder to debug.


.. _tailrec:


``TailRec``
===========

The ``(import [__future__ [TailRec]])`` command
gives programmers a simple way to use tail-call optimization
(TCO) in their Hy code, even for mutually recursive functions.

A tail call is a subroutine call that happens inside another
procedure as its final action; it may produce a return value which
is then immediately returned by the calling procedure. If any call
that a subroutine performs, such that it might eventually lead to
this same subroutine being called again down the call chain, is in
tail position, such a subroutine is said to be tail-recursive,
which is a special case of recursion. Tail calls are significant
because they can be implemented without adding a new stack frame
to the call stack. Most of the frame of the current procedure is
not needed any more, and it can be replaced by the frame of the
tail call. The program can then jump to the called
subroutine. Producing such code instead of a standard call
sequence is called tail call elimination, or tail call
optimization. Tail call elimination allows procedure calls in tail
position to be implemented as efficiently as goto statements, thus
allowing efficient structured programming.

-- Wikipedia (http://en.wikipedia.org/wiki/Tail_call)

Example:

.. code-block:: hy
(import [__future__ [TailRec]])
(defn fact [n]
(defn facthelper [n acc]
(if (= n 0)
acc
(facthelper (- n 1) (* n acc))))
(do
(print "Using fact!")
(facthelper n 1)))
(print (fact 10000))
(defn odd [n]
(if (= n 0)
False
(even (- n 1))))
(defn even [n]
(if (= n 0)
True
(odd (- n 1))))
(print (even 1000))
1 change: 1 addition & 0 deletions docs/contrib/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ Contents:
anaphoric
loop
multi
future
5 changes: 0 additions & 5 deletions tests/native_tests/tailrec.hy
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,3 @@
(facthelper (- n 1) (* n acc))))
(facthelper n 1))
(assert (< 0 (fact 1000)))))





0 comments on commit f4526d0

Please sign in to comment.