Why should recursion be preferred over iteration?

Iteration is more performant than recursion, right? Not necessarily. This conception comes from many C-like languages, where calling a function, recursive or not, had a large overhead and created a new stackframe for every call. For many languages this is not the case, and recursion is equally or more performant than an iterative version. These … Read more

getattr and setattr on nested subobjects / chained properties?

You could use functools.reduce: import functools def rsetattr(obj, attr, val): pre, _, post = attr.rpartition(‘.’) return setattr(rgetattr(obj, pre) if pre else obj, post, val) # using wonder’s beautiful simplification: https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects/31174427?noredirect=1#comment86638618_31174427 def rgetattr(obj, attr, *args): def _getattr(obj, attr): return getattr(obj, attr, *args) return functools.reduce(_getattr, [obj] + attr.split(‘.’)) rgetattr and rsetattr are drop-in replacements for getattr and … Read more

How do I replace while loops with a functional programming alternative without tail call optimization?

An example in JavaScript Here’s an example using JavaScript. Currently, most browsers do not support tail call optimisation and therefore the following snippet will fail const repeat = n => f => x => n === 0 ? x : repeat (n – 1) (f) (f(x)) console.log(repeat(1e3) (x => x + 1) (0)) // 1000 … Read more

Python: maximum recursion depth exceeded while calling a Python object

Python don’t have a great support for recursion because of it’s lack of TRE (Tail Recursion Elimination). This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you … Read more

Recursive lambda expression to traverse a tree in C#

Ok, I found some free time finally. Here we go: class TreeNode { public string Value { get; set;} public List<TreeNode> Nodes { get; set;} public TreeNode() { Nodes = new List<TreeNode>(); } } Action<TreeNode> traverse = null; traverse = (n) => { Console.WriteLine(n.Value); n.Nodes.ForEach(traverse);}; var root = new TreeNode { Value = “Root” }; … Read more