Controlling Flow Using if, ifelse, and ifelse-Value



When commands are to be executed conditionally, that is depending on the outcome of an evaluation, a selection control structure must be used. In NetLogo, knowing when to use if, ifelse, ifelse-value is important. These are oftentimes used to change the properties of agents such as color, position, heading and other user-defined variables.



if reporter [ commands ] 

The reporter must report a boolean (true or false) value. If it reports TRUE, it runs commands. With if, we expect some agents to run commands while others don't, this is because the reporter may have different value for different agents.

if pxcor > 0 [ set pcolor blue ] ;agents with pxcor greater than 0 will be colored blue.


ifelse reporter [ commands1 ] [ commands2 ] 

For ifelse, if reporter's value is TRUE, it runs commands1. If FALSE, runs commands2.  

if pxcor > 0 [ set pcolor blue ][ set pcolor red ] ;agents with pxcor greater than 0 will be colored blue and agents with pxcor less than 0 will have red


ifelse-value reporter [reporter1] [reporter2]

If reporter's value is TRUE, the result is the value of reporter1. If FALSE, the result is the value of reporter2. With the use of ifelse-value, a specific variable can have a different value based on the value of the reporter. This can be used when a conditional is needed in the context of a reporter, where commands (such as ifelse) are not allowed. 


set pcolor ifelse-value (pxcor > 0) [blue] [red] ;pcolor will either have blue or red depending on the reporter value (pxcor > 0)

To get the desired program execution, a correct understanding on the use of logic operators ( AND, OR, XOR) as well as mathematical operators is essential so as to produce the correct results. Here are the example usage from the Virus model:

if age > lifespan [ die ]

if immune? [ set remaining-immunity remaining-immunity - 1 ]

if sick? [ set sick-time sick-time + 1 ]

if sick? [ recover-or-die ]

if random-float 100 < infectiousness[ get-sick ]

if sick-time > duration 

    [ ifelse random-float 100 < chance-recover   
      [ become-immune ]
      [ die ] ]

if count turtles < carrying-capacity and random-float 100 < chance-reproduce
[ hatch 1
      [ set age 1
        lt 45 fd 1
        get-healthy ] ]

ifelse sick? [ infect ] [ reproduce ]

ifelse random-float 100 < chance-recover   ;; either recover or die
      [ become-immune ]
      [ die ]
 

set color ifelse-value sick? [ red ] [ ifelse-value immune? [ grey ] [ green ] ] ]








Share on Google Plus

About SSabal

:)
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment