KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ how to create temp variable inside $[]

  • how to create temp variable inside $[]

    Posted by chan_chenyanj on April 14, 2022 at 12:00 am

    if i use $[] for if how can i add temp variable there? my understanding is it is either condition or the return value. so how can i put the below logic into this? suppose i have only input x and the if else logic below.

    $[x=`a;5; ?]
    
    if x = 'a' return 5
    
    if x='b'
    
           y = x*x +5
    
          if( y > 6 ) return 6 
    
          if(y>9) return 10
    
    
    
    chan_chenyanj replied 8 months, 1 week ago 2 Members · 2 Replies
  • 2 Replies
  • davidcrossey

    Member
    April 14, 2022 at 12:00 am

    You can do something like the following:

    q)f:{[x] $[x~`a;5;x~`b;[y:6*6;$[y<6;6;y>9;10;y]];x]} 
    q)f {[x] $[x~`a;5;x~`b;[y:6*6;$[y<6;6;y>9;10;y]];x]} 
    q)f `a 5 
    q)f `b 10

    I would use a function (as above) or a lambda (anonymous function), that way your temp variable will only remain for the scope of the function i.e. in the example above, does not exist in my global namespace after execution. You can read more about conditional scope here

    You can see if x is b in the above we have square brackets [ ] which defines a contained block of code to run if the statement is true. See more here

    Please find more on the extended if-else / switch statement here

  • chan_chenyanj

    Member
    April 15, 2022 at 12:00 am

    thanks a lot!

Log in to reply.