Home > Community > Forums > Custom IC SKILL > Nested foreach loop

Email

* Required Fields

Recipients email * (separate multiple addresses with commas)

Your name *

Your email *

Message *

Contact Us

* Required Fields
First Name *

Last Name *

Email *

Company / Institution *

Comments: *

 Nested foreach loop 

Last post Thu, Feb 28 2013 1:13 AM by T Opperman. 7 replies.
Started by T Opperman 18 Feb 2013 12:12 AM. Topic has 7 replies and 1399 views
Page 1 of 1 (8 items)
Sort Posts:
  • Mon, Feb 18 2013 12:12 AM

    • T Opperman
    • Not Ranked
    • Joined on Fri, Feb 15 2013
    • Posts 7
    • Points 125
    Nested foreach loop Reply

    In an attemt to make parametric simulation scripts a bit more readable, I wrote a macro that allows foreach loops to be nested. I have not tested it fully, but I would like the readers' input on my code. The code generates a string containing the foreach loop, before evaluating it. It feels a bit clumsy, but I was unable to think of an simpler way to do this. Any suggestions?

    TOForeachNestFunc=lambda( (Symbols Lists Commands)
    let(((DeclareLoopVars nil) (DeclareLoopHead "") (DeclareLoopBody "") (DeclareLoopTail "")
    	(MainLoop "foreach( (") (LetStringHead "let((") Result )
    ;We'll need to create a loop that declares the expanded sweep lists,
    ;before creating a main loop that runs through all the expanded sweep lists and
    ;executes the commands.
    
    	foreach((List Symbol) Lists Symbols
    	 DeclareLoopVars=cons(sprintf(nil "%sS" Symbol) DeclareLoopVars)
    	 DeclareLoopBody=strcat(DeclareLoopBody sprintf(nil "%sS=cons(%s %sS) " Symbol Symbol Symbol))
    	 DeclareLoopHead=strcat(DeclareLoopHead sprintf(nil "foreach(%s '%L " Symbol List ))
    	 DeclareLoopTail=strcat(DeclareLoopTail ")")
    	 MainLoop = strcat(MainLoop Symbol " ")
    	)
    	MainLoop = strcat(MainLoop ") ")
    
    	foreach(Var reverse(DeclareLoopVars)
    		LetStringHead=strcat(LetStringHead "(" Var " nil) ")
    		MainLoop = strcat(MainLoop Var " ")
    		)
    	LetStringHead=strcat( LetStringHead ")")
    	MainLoop = strcat(MainLoop "\n" Commands "\n) ")
    	Result=strcat(LetStringHead "\n" DeclareLoopHead "\n" DeclareLoopBody "\n" DeclareLoopTail "\n" MainLoop "\n" ")")
    	)
    )
    
    
    defmacro(TOForeachNest (Symbols Lists @rest Commands) ;Executes a nested foreach loop ;Symbols: A list of variables that are used in the commands. ;List:A list of lists that contain the values to be swept ;Example: ; TempL= '(-40.0 27.0 85.0) ; VSupplyL= '(3.2 3.3 3.4) ; ; TOForeachNest('(Temp VSupply) list(VSupplyL TempL) ; printf("Temperature: %e, Supply Voltage: %e", Temp VSupply) ; ) ;expands to: ; foreach(Temp TempL ; foreach(VSupply VSupplyL ; printf("Temperature: %e, Supply Voltage: %e\n", Temp VSupply) ;) ;) let((CommandString) CommandString=sprintf(nil "%L" ,Commands) CommandString=substring(CommandString 2 strlen(CommandString)-2) `let((Result) Result=funcall(,TOForeachNestFunc ,Symbols ,Lists ,CommandString) evalstring(Result) ) ) )
    Filed under:
    • Post Points: 20
  • Mon, Feb 18 2013 1:15 AM

    Re: Nested foreach loop Reply

    You're right, that is a bit cumbersome. What you need is a recursive macro - doing this avoids the need for any run-time evaluation:

    defmacro(TOForeachNest (Symbols Lists @rest Commands)
      `foreach(,car(Symbols) ,car(Lists)
         ,if(cdr(Symbols)
            `TOForeachNest(,cdr(Symbols) ,cdr(Lists) ,@Commands)
            `{,@Commands}
         )
       )
    ) 
    
    Usage is a bit simpler too - no need for a quote or a list() aroudn the variables or lists:

     

    TOForeachNest((Temp VSupply) (VSupplyL TempL)
    	printf("Temperature: %e, Supply Voltage: %e\n", Temp VSupply)
    	)

    Regards,

    Andrew.

     

    • Post Points: 35
  • Mon, Feb 18 2013 2:04 AM

    • T Opperman
    • Not Ranked
    • Joined on Fri, Feb 15 2013
    • Posts 7
    • Points 125
    Re: Nested foreach loop Reply

    Thanks a lot Andrew! Your solution is more elegant and runs fluently. I played around with the idea of a recursive macro, but I was unable to get the syntax right. Could I suggest that the future publications of the Skill User Manual contain more examples on this?

    Regards,

    Tjaart

    • Post Points: 20
  • Mon, Feb 18 2013 2:14 AM

    Re: Nested foreach loop Reply

    Tjaart,

    Macros are a bit of an art - there's an increasing number of them covered in Articles (formerly known as Solutions) on Cadence Online Support, and also in (say) the SKILL for the skilled blog on the Cadence web site - but I agree, having more examples in the SKILL User Guide would be a good idea.

    That said, I tend to advise against creating too many macros. As Peter Norvig writes in Paradigms of Artificial Intelligence [Case Studies in Common Lisp]:

    "The first step in writing a macro is to recognize that every time you write one, you are defining a new language that is just like Lisp except for your new macro. The programmer who thinks that way will rightfuly be extremely frugal in defining macros. (Besides, when someone asks, "What did you get done today?" ti sounds more impressive to say "I defined a new language and wrote a compiler for it" than to say "I just hacked up a couple of macros.") Introducing a macro puts much more memory strain on the reader of your program than does introducing a function, variable, or data type, and so it should not be taken lightly. Introduce macros only when there is a clear need, and when the macro fits in well with your existing system. As C.A.R. Hoare put it, "One thing the language designer should not do is include untried ideas of his own."

    Regards,

    Andrew.

    • Post Points: 20
  • Mon, Feb 18 2013 5:45 AM

    • ztzg
    • Not Ranked
    • Joined on Fri, Dec 31 2010
    • München, Bavaria
    • Posts 15
    • Points 225
    Re: Nested foreach loop Reply

    Tjaart, Andrew,

    I couldn't resist coming up with a non-macro version for completeness (also at http://s.crosstwine.com/spb/8cda9957).

    I usually implement iteration constructs via higher-order functions, and sugar-coat them in a thin layer of macrology where/when it really improves readability.

    This one is a bit nasty because a function cannot know the number of nested loops at compile time; moreover, it reuses/mutates a single list of arguments across the whole iteration to mimimize consing.

    A "pure macro" implementation is arguably nicer in this case, even if less generic. Anyway, here you are:

    defun(MyMapnested1 (fn args argsTail lists)
      cond(
        (lists
         let( ((moreLists cdr(lists))
               (nextArgsTail cdr(argsTail)))
           foreach(item car(lists)
             rplaca(argsTail item)
             MyMapnested1(fn args nextArgsTail moreLists)
           )
         )
        )
        (t
         apply(fn args)
        )
      )
    )
    
    defun(MyMapnested (fn @rest lists)
      let( ((args mapcar(lambda( (_ignore) nil) lists)))
        MyMapnested1(fn args args lists)
      )
    )
    

    Usage via higher-order functions:

    let( ((TempL '(-40 27 85))
          (VSupplyL '(3.2 3.3 3.4)))
      MyMapnested(
        lambda( (Temp VSupply)
          printf("Temperature: %L, Supply Voltage: %L\n" Temp VSupply)
        )
        TempL
        VSupplyL
      )
    )
    

    And here is TOForeachNest implemented in terms of MyMapnested:

    defmacro(TOForeachNest (Symbols Lists @rest Commands)
      `MyMapnested(
         lambda( ,Symbols
           ,@Commands
         )
         ,@Lists
       )
    )
    

    Cheers, -D

    http://www.crosstwine.com tel: +49 89 2189 2939 cell: +49 174 3489 428
    • Post Points: 5
  • Mon, Feb 25 2013 3:16 AM

    • T Opperman
    • Not Ranked
    • Joined on Fri, Feb 15 2013
    • Posts 7
    • Points 125
    Re: Nested foreach loop Reply

    Andrew,

    Ideally, I want to be able to use this macro inside a generic custom sweep function. The arguments would then have to be lists.

    For example:

    VddLV = '(2.0 2.3)

    VddHV = '(Vlow 3.3)

    Symbols = '(Vlow Vhigh)

    TOForeachNest(Symbols list(VddLV VddHV)

        foreach(Symbol Symbols

            printf("%s %e\n" sprintf(nil "%L" Symbol)

                evalstring(sprintf(nil "%L" Symbol)))

            )

    )

    Should expand to:

    foreach(Vlow '(2.0 2.3)

        foreach(Vhigh '(Vlow 3.3)

            foreach(Symbol Symbols

                printf("%s %e\n"

                    sprintf(nil "%L" Symbol

                        evalstring(sprintf(nil "%L" Symbol)))

                    )

                 )

            )

    )

    • Post Points: 20
  • Mon, Feb 25 2013 3:55 AM

    Re: Nested foreach loop Reply

    It can't really expand the outer loops at macro expansion time because it depends on the run-time value of the Symbols variable. However, you want the body (the foreach(Symbol Symbols) bit) not to be expanded - so you can't just make it a recursive function.

    I don't think you can easily do that without run-time evaluation.  I'd have to think about it a bit more...

    Andrew.

     

    • Post Points: 20
  • Thu, Feb 28 2013 1:13 AM

    • T Opperman
    • Not Ranked
    • Joined on Fri, Feb 15 2013
    • Posts 7
    • Points 125
    Re: Nested foreach loop Reply

    To address this issue I wrote a function that calls the macro using evalstring. The lists are modified into enclosed arguments. To pass the commands to the functions one needs to declare a lambda function. I got this idea from ztzg (thanks!).

    procedure(TOForeachList(Symbols Lists Fun)
     let(((Symstring "") (Liststring ""))
      foreach(Sym Symbols Symstring=sprintf(nil "%s %s" Symstring Sym))
      foreach(List Lists Liststring=sprintf(nil "%s %L" Liststring List))
      evalstring(sprintf(nil "TOForeachNest((%s) (%s) funcall(Fun))" Symstring Liststring ) )
     )
    )

    VddLV = '(2.0 2.3)
    VddHV = '(Vlow 3.3)
    Symbols = '(Vlow Vhigh)

    TOForeachList(Symbols '(VddLV VddHV) lambda( ()
     foreach(Symbol Symbols
      printf("%s %.1e\n" Symbol eval(eval(Symbol)))
     )
    ))

    Vlow 2.0e+00
    Vhigh 2.0e+00
    Vlow 2.0e+00
    Vhigh 3.3e+00
    Vlow 2.3e+00
    Vhigh 2.3e+00
    Vlow 2.3e+00
    Vhigh 3.3e+00

    So far this approach seems to work.

    • Post Points: 5
Page 1 of 1 (8 items)
Sort Posts:
Started by T Opperman at 18 Feb 2013 12:12 AM. Topic has 7 replies.