Re: goto's, and loops

new topic     » goto parent     » topic index » view thread      » older message » newer message

This is a response to a question I asked about case statment.
from david.

Bernie

____________________________________________________________________________
_

Bernie Ryan wrote:

> Using a sequence of routine id's to make a case (switch)
> statement.

Here's a case statement:

   select case of a:
   case 1: foo()
   case 2: bar()
   case 3: grill
   end select

Here's the same code as an if statement:

   if    a = 1 then foo()
   elsif a = 2 then bar()
   elsif a = 3 then grill()
   end if


Here's the same code using routine_id:

   constant switch = {
      routine_id("foo"),
      routine_id("bar"),
      routine_id("grill") }

   if    a = 1 then call_proc( switch[1], {} )
   elsif a = 2 then call_proc( switch[2], {} )
   elsif a = 3 then call_proc( switch[3], {} )
   end if

The pattern in the if statement should be painfully obvious:

   constant switch = {
      routine_id("foo"),
      routine_id("bar"),
      routine_id("grill") }

   if a > 0 and a <= length( switch ) then
      call_proc( switch[a], {} )
   end if


Or you could use my handy-dandy in_range() function to make the code a bit
cleaner:

   if in_range( a, s ) then
      call_proc( switch[a], {} )
   end if

Sorry, couldn't resist. You can also write a switch procedure:

   procedure switch( integer i, sequence s )
      if i > 0 and i <= length( s ) then
         call_proc( s[i] )
   end procedure

This would work like this:

   switch( a, { "foo", "bar", "grill" } )

-- David Cuny

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu