Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Macro parsing question.


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: Macro parsing question.
Date   Thu, 14 Feb 2013 09:55:35 +0000

Should be

local d = cond("a" == "c", "%", "Value")

Nick

On Thu, Feb 14, 2013 at 9:54 AM, Nick Cox <[email protected]> wrote:
> Parsing is not the issue here; it's what happens in a loop.
>
> The code can be simplified to
>
> loc list2 a b c
> foreach k of loc list2 {
>   if "a" == "`k'" loc d %
>   else loc d Value
> }
> di "`d'"
>
> As Amadou says, this is what happens
>
> . loc list2 a b c
>
> . foreach k of loc list2 {
>   2.   if "a" == "`k'" loc d %
>   3.   else loc d Value
>   4. }
>
> . di "`d'"
> Value
>
> So, what's happening? The loop is cycling over "a" "b" "c" and the
> code sets -d- to "%" if each of these is equal to "a", otherwise to
> "Value".
>
> We can do this step by step.
>
> Is "a" == "a"? Yes. Set -d- to "%"
> Is "a" == "b"? No. Set -d- to "Value".
> Is "a" == "c"? No. Set -d- to "Value".
>
> Once the loop is done, -d- is still "Value".
>
> In fact, the loop can be short-circuited. Only the last element in the
> list has an effect on -d- that survives beyond the loop, so it boils
> down to
>
> local d = cond("a" == "c", "Value", "%")
>
> Nick
>
> . loc list2 a b c
>
> . foreach k of loc list2 {
>   2.   if "a" == "`k'" loc d %
>   3.   else loc d Value
>   4. }
>
> . di "`d'"
> Value
>
>
> On Thu, Feb 14, 2013 at 9:24 AM, Amadou DIALLO <[email protected]> wrote:
>
>> I spent the night programming some stuffs but cannot understand why I
>> don't obtain the expected results. I was expecting "%" but got
>> "Value". What am I doing wrong?
>>
>>         noi se tr on
>>         loc list1 a
>>         loc list2 a b c
>>         loc d
>>         foreach j of loc list1 {
>>            foreach k of loc list2 {
>>               if "`j'" == "`k'" loc d %
>>               else loc d Value
>>            } // foreach k
>>                 }
>>         di "`d'"
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index