Print numbers from one to one million

后端 未结 1 1391
谎友^
谎友^ 2020-12-11 20:50

Assume you have a highly synthetic task to print numbers from 1 to 1.000.000 without appropriate input XML. Of course, straight-forward recursion will fail due to, ironic en

1条回答
  •  没有蜡笔的小新
    2020-12-11 21:20

    Here is a generic "iterate" template that performs an action on an initial input and then on its result, until a given condition is specified.

    This transformation is tail-recursive and works without stack overflow with an intelligent XSLT processor:

    
     
    
     
       1000000
     
    
     
    
     
      
       
       
      
     
    
     
       
       
    
       
           
             
               
             
           
    
           
    
           
             
             
           
       
     
    
     
      
    
      
       
      
     
    
    

    when this transformation is applied on any XML document (not used), an intelligent XSLT processor that optimizes tail recursion into iteration produces the wanted result without stack overflow. This is the case with Saxon 6.5.4, which I used to produce the result.

    Your problem is that not all XSLT processors recognize and optimize tail-recursion.

    For such processors, one can use DVC - style recursion:

    
     
    
     
      
        
        
      
     
    
     
      
      
    
      
       
        
          
          
    
        
        
          
          
           
           
          
          
           
           
          
        
       
      
     
    
    

    this transformation produces the correct result without any crash using MSXML4.

    With this DVC transformation the maximum recursion-depth is only Log2(N) -- in this case 19.

    I would recommend using the FXSL library. It provides DVC variants of commonly used higher-order functions, such as foldl() and map() making it possible to produce the DVC variant of almost any recursive algorithm.

    Of course, in XSLT2.0 one would simply write:

    
    

    0 讨论(0)
提交回复
热议问题