recursion - How does (co)recursive definition work in Haskell? -


i'm playing around language start learning , puzzled beyond wits how recursive definition works.

for example, let's take sequence of triangular numbers (tn n = sum [1..n])

the solution provided was:

triangularnumbers = scanl1 (+) [1..] 

so far, good.

but solution did come was:

triangularnumbers = zipwith (+) [1..] $ 0 : triangularnumbers 

which correct.

now question is: how translate lower level implementation? happens behind scene when such recursive definition met?

here simple recursive function gives nth triangular number:

triag 0 = 0 triag n = n + triag (n-1) 

your solution triag' = zipwith (+) [1..] $ 0 : triag' more fancy: it's corecursive (click, click). instead of calculating nth number reducing value of smaller inputs, define whole infinite sequence of triangular numbers recursively specifying next value, given initial segment.

how haskell handle such corecursion? when encounters definition, no calculation performed, deferred until results needed further computations. when access particular element of list triag', haskell starts computing elements of list based on definition, element gets accessed. more detail, found this article on lazy evaluation helpful. in summary, lazy evaluation great have, unless need predict memory usage.

here similar question, step-by step explanation of evaluation of fibs = 0 : 1 : zipwith (+) fibs (tail fibs), corecursive definition of fibonacci sequence.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -