2 people like it.

Nested Recursive Loop

Nested recursive loop which has certain uses cases for loop optimization when you don't want to traverse across entire ranges but rather subsets incrementally and decrementally etc.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
open System

// Regular nested loop
let mutable sum = 0

for i in 1 .. 10 do
    for j in 1 .. 10 do
        for k in 1 .. 10 do
            sum <- sum + 1

printfn "%A" sum

// Nested recursive loop equivalent
let rec loop1 c sum = 
    if c >= 10 then
        sum
    else
        loop1 (c + 1) (sum + 1)

let rec loop2 c sum = 
    if c >= 9 then
        sum
    else
        loop2 (c + 1) (loop1 0 (sum + 1))

let rec loop3 c sum = 
    if c >= 10 then
        sum
    else
        loop3 (c + 1) (loop2 0 (sum + 1))

loop3 0 0
namespace System
val mutable sum : int
val i : int32
val j : int32
val k : int32
val printfn : format:Printf.TextWriterFormat<'T> -> 'T
val loop1 : c:int -> sum:int -> int
val c : int
val sum : int
val loop2 : c:int -> sum:int -> int
val loop3 : c:int -> sum:int -> int
Raw view New version

More information

Link:http://fssnip.net/80A
Posted:1 month ago
Author:Martin Lockstrom
Tags: #nested loops , #recursion