Is there a way to explicitly write an elixir function for tail optimization?

In Clojure, for example, you can use a special recur form to express your intention to use non-recursive calls that do not require a stack and is checked by the compiler. As written in the Clojure docs :

"recur in a position other than the tail position is an error", "recur is functional and its use in the tail position is checked by the compiler"

In elixir, you can define a function as a series of sentences, with recursion calls between them. Is there a way to know for sure that a particular function will be optimized with a tail call?

+4
source share
1 answer

The compiler does not optimize the function . It optimizes the call for this function. It can be a call to the same function inside it, it can be a call to another function, it does not matter.

... this is not the case with Clojure, where it recurcan return execution only to the last "recursive point" (be it loopeither fn), which makes mutual recursion impossible without "outside help", for example trampoline . It looks more like a gang than a solution, but the problem is too big, and the right solution will require too much.

, , Elixir: tail call. .

, .

, .

Clojure , :

(defn x [] (x))     ; <- StackOverflowError if called
(defn x [] (recur)) ; <- hangs if called

, :

  • , e. . " TCO"
  • , e. . ,

, .

, .

+4

Source: https://habr.com/ru/post/1617830/


All Articles