define loop statement?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David Isaac

    define loop statement?

    I would like to be able to define a loop statement
    (nevermind why) so that I can write something like

    loop 10:
    do_something

    instead of

    for i in range(10):
    do_something

    Possible? If so, how?

    Thanks,
    Alan Isaac


  • Jonathan Gardner

    #2
    Re: define loop statement?

    No, not in the way you think it is. What you can do instead is
    something like this:

    def do_something(i) :
    ... do_something ...

    def loop(n, func):
    for i in range(n): func(i)

    loop(10, do_something)

    Comment

    • Georg Brandl

      #3
      Re: define loop statement?

      David Isaac wrote:[color=blue]
      > I would like to be able to define a loop statement
      > (nevermind why) so that I can write something like
      >
      > loop 10:
      > do_something
      >
      > instead of
      >
      > for i in range(10):
      > do_something
      >
      > Possible? If so, how?[/color]

      It's not possible to create a new statement, with suite
      and indentation rules without hacking the interpreter or
      resorting to alternative bytecode compilers such as "pyc".

      Creating a _function_ named "loop" is easy as Jonathan's
      answer shows.

      Georg

      Comment

      • Rene Pijlman

        #4
        Re: define loop statement?

        David Isaac:[color=blue]
        >I would like to be able to define a loop statement
        >(nevermind why) so that I can write something like
        >
        >loop 10:
        > do_something
        >
        >instead of
        >
        >for i in range(10):
        > do_something
        >
        >Possible? If so, how?[/color]

        Yes. By implementing a compiler or an interpreter for your programming
        language. Or a preprocessor that converts your language to Python, or some
        other suitable intermediate language. Or a programmer, that converts your
        pseudocode and some coffee to the desired algorithm :-)

        --
        René Pijlman

        Comment

        • bearophileHUGS@lycos.com

          #5
          Re: define loop statement?

          David Isaac:[color=blue]
          > I would like to be able to define a loop statement
          > (nevermind why) so that I can write something like
          >
          > loop 10:
          > do_something
          >
          > instead of
          >
          > for i in range(10):
          > do_something
          >
          > Possible? If so, how?[/color]

          It seems that you are looking for macros; maybe Logix "language"
          (www.livelogix.net/logix) or Boo (boo.codehaus.o rg) can solve your
          problem.
          Otherwise you can do it with very different languages like Lisp or
          Scheme (with a different syntax) and maybe Dylan too.

          If you tell us your purpose, maybe we can suggest you a
          better/different solution.

          Bye,
          bearophile

          Comment

          • Xavier Morel

            #6
            Re: define loop statement?

            Rene Pijlman wrote:[color=blue]
            > David Isaac:[color=green]
            >> I would like to be able to define a loop statement
            >> (nevermind why) so that I can write something like
            >>
            >> loop 10:
            >> do_something
            >>
            >> instead of
            >>
            >> for i in range(10):
            >> do_something
            >>
            >> Possible? If so, how?[/color]
            >
            > Yes. By implementing a compiler or an interpreter for your programming
            > language. Or a preprocessor that converts your language to Python, or some
            > other suitable intermediate language. Or a programmer, that converts your
            > pseudocode and some coffee to the desired algorithm :-)
            >[/color]
            Or by hacking through the Python source and creating his own "somehow
            pythonish but absolutely not python" language

            Comment

            • Xavier Morel

              #7
              Re: define loop statement?

              Rene Pijlman wrote:[color=blue]
              > David Isaac:[color=green]
              >> I would like to be able to define a loop statement
              >> (nevermind why) so that I can write something like
              >>
              >> loop 10:
              >> do_something
              >>
              >> instead of
              >>
              >> for i in range(10):
              >> do_something
              >>
              >> Possible? If so, how?[/color]
              >
              > Yes. By implementing a compiler or an interpreter for your programming
              > language. Or a preprocessor that converts your language to Python, or some
              > other suitable intermediate language. Or a programmer, that converts your
              > pseudocode and some coffee to the desired algorithm :-)
              >[/color]
              Or by hacking through the Python source and creating his own "somehow
              pythonish but absolutely not python" language

              Comment

              • Jeffrey Schwab

                #8
                Re: define loop statement?

                David Isaac wrote:[color=blue]
                > I would like to be able to define a loop statement
                > (nevermind why) so that I can write something like
                >
                > loop 10:
                > do_something
                >
                > instead of
                >
                > for i in range(10):
                > do_something
                >
                > Possible? If so, how?[/color]

                Ruby and Smalltalk are both good at this kind of thing, since they have
                syntactic support for associating a block with each method call. In
                Python, I think you just have to do a little more setup. How about
                something like this?

                class Loop:
                def __init__(self, n):
                self.n = n
                def __call__(self):
                self.n = self.n - 1
                return self.n != 0


                if __name__ == '__main__':
                loop = Loop(10)
                while loop:
                print "OK"

                Comment

                • Georg Brandl

                  #9
                  Re: define loop statement?

                  Jeffrey Schwab wrote:
                  [color=blue]
                  > class Loop:
                  > def __init__(self, n):
                  > self.n = n
                  > def __call__(self):
                  > self.n = self.n - 1
                  > return self.n != 0
                  >
                  >
                  > if __name__ == '__main__':
                  > loop = Loop(10)
                  > while loop:
                  > print "OK"[/color]

                  Seems you forgot "()" after "while loop" above.

                  Georg

                  Comment

                  • Jeffrey Schwab

                    #10
                    Re: define loop statement?

                    Jeffrey Schwab wrote:
                    [color=blue]
                    > class Loop:
                    > def __init__(self, n):
                    > self.n = n
                    > def __call__(self):
                    > self.n = self.n - 1
                    > return self.n != 0
                    >
                    >
                    > if __name__ == '__main__':
                    > loop = Loop(10)
                    > while loop:[/color]

                    Whoops. Should be "while loop()".
                    [color=blue]
                    > print "OK"[/color]

                    Comment

                    • David Isaac

                      #11
                      Re: define loop statement?

                      [color=blue]
                      > Alan Isaac wrote:[color=green]
                      > > I would like to be able to define a loop statement
                      > > (nevermind why) so that I can write something like
                      > >
                      > > loop 10:
                      > > do_something
                      > >
                      > > instead of
                      > >
                      > > for i in range(10):
                      > > do_something
                      > >
                      > > Possible? If so, how?[/color][/color]


                      "Jeffrey Schwab" <jeff@schwabcen ter.com> wrote in message
                      news:T4LJf.1425 6$915.10437@sou theast.rr.com.. .[color=blue]
                      > class Loop:
                      > def __init__(self, n):
                      > self.n = n
                      > def __call__(self):
                      > self.n = self.n - 1
                      > return self.n != 0
                      >
                      >
                      > if __name__ == '__main__':
                      > loop = Loop(10)
                      > while loop():
                      > print "OK"[/color]

                      OK, that's pretty good.
                      Thanks!
                      Alan Isaac


                      Comment

                      • Felipe Almeida Lessa

                        #12
                        Re: define loop statement?

                        Em Sáb, 2006-02-18 às 20:04 +0000, Jeffrey Schwab escreveu:[color=blue]
                        > if __name__ == '__main__':
                        > loop = Loop(10)
                        > while loop:
                        > print "OK"[/color]

                        Maybe:

                        while Loop(10)():
                        print "OK"

                        Looks rather ugly but requires one less line ;-).

                        --
                        "Quem excele em empregar a força militar subjulga os exércitos dos
                        outros povos sem travar batalha, toma cidades fortificadas dos outros
                        povos sem as atacar e destrói os estados dos outros povos sem lutas
                        prolongadas. Deve lutar sob o Céu com o propósito primordial da
                        'preservação' . Desse modo suas armas não se embotarão, e os ganhos
                        poderão ser preservados. Essa é a estratégia para planejar ofensivas."

                        -- Sun Tzu, em "A arte da guerra"

                        Comment

                        • Nigel Rowe

                          #13
                          Re: define loop statement?

                          Felipe Almeida Lessa wrote:
                          [color=blue]
                          > Em Sáb, 2006-02-18 às 20:04 +0000, Jeffrey Schwab escreveu:[color=green]
                          >> if __name__ == '__main__':
                          >> loop = Loop(10)
                          >> while loop:
                          >> print "OK"[/color]
                          >
                          > Maybe:
                          >
                          > while Loop(10)():
                          > print "OK"
                          >
                          > Looks rather ugly but requires one less line ;-).
                          >[/color]
                          Doesn't work. You get a NEW Loop(10) instance on each pass through the
                          'while'. This is just an expensive way to make an endless loop.

                          --
                          Nigel Rowe
                          A pox upon the spammers that make me write my address like..
                          rho (snail) swiftdsl (stop) com (stop) au

                          Comment

                          • Felipe Almeida Lessa

                            #14
                            Re: define loop statement?

                            Em Dom, 2006-02-19 às 11:08 +1100, Nigel Rowe escreveu:[color=blue]
                            > Felipe Almeida Lessa wrote:
                            >[color=green]
                            > > Em Sáb, 2006-02-18 às 20:04 +0000, Jeffrey Schwab escreveu:[color=darkred]
                            > >> if __name__ == '__main__':
                            > >> loop = Loop(10)
                            > >> while loop:
                            > >> print "OK"[/color]
                            > >
                            > > Maybe:
                            > >
                            > > while Loop(10)():
                            > > print "OK"
                            > >
                            > > Looks rather ugly but requires one less line ;-).
                            > >[/color]
                            > Doesn't work. You get a NEW Loop(10) instance on each pass through the
                            > 'while'. This is just an expensive way to make an endless loop.[/color]

                            Oh, sorry, ignore me on that one. Now I think I should sleep =S...

                            --
                            "Quem excele em empregar a força militar subjulga os exércitos dos
                            outros povos sem travar batalha, toma cidades fortificadas dos outros
                            povos sem as atacar e destrói os estados dos outros povos sem lutas
                            prolongadas. Deve lutar sob o Céu com o propósito primordial da
                            'preservação' . Desse modo suas armas não se embotarão, e os ganhos
                            poderão ser preservados. Essa é a estratégia para planejar ofensivas."

                            -- Sun Tzu, em "A arte da guerra"

                            Comment

                            • Benji York

                              #15
                              Re: define loop statement?

                              David Isaac wrote:[color=blue]
                              > I would like to be able to define a loop statement
                              > (nevermind why) so that I can write something like
                              >
                              > loop 10:
                              > do_something[/color]

                              Here's a flagrant hack:

                              import sys

                              VAR_NAME = '__repeat_count er'

                              def set_repeat_coun ter(value):
                              frame = sys._getframe(2 )
                              frame.f_locals[VAR_NAME] = value

                              def get_repeat_coun ter(value):
                              frame = sys._getframe(2 )
                              if VAR_NAME not in frame.f_locals:
                              frame.f_locals[VAR_NAME] = value

                              return frame.f_locals[VAR_NAME]

                              def repeat(limit):
                              set_repeat_coun ter(get_repeat_ counter(limit)-1)
                              return get_repeat_coun ter(limit)

                              while repeat(10):
                              print 'OK'

                              Without more work it doesn't allow nested loops though.

                              And for the record, if you're worrying about Python's counted loop
                              construct you need better things to worry about.
                              <insert-smilies-as-appropriate>
                              --
                              Benji York

                              Comment

                              Working...