1
for i in range(0,30,3):
    print(i)

What is the functional style of the imperative loop above?

lambda x: print(x), range(0,30,3)
cs95
  • 330,695
  • 80
  • 606
  • 657
ERJAN
  • 22,540
  • 20
  • 65
  • 127

3 Answers3

6

A lambda isn't necessary here. Just use the * unpacking operator.

In [163]: print(*range(0, 30, 3))
0 3 6 9 12 15 18 21 24 27

If you want them printed in separate lines, that's doable too.

In [164]: print(*range(0, 30, 3), sep='\n')
0
3
6
9
12
15
18
21
24
27
cs95
  • 330,695
  • 80
  • 606
  • 657
0

if you are using python 2.x you'll need future import:

from __future__ import print_function #dont't need this for python 3.x
print(*range(0,30,3), sep='\n')
zipa
  • 26,044
  • 6
  • 38
  • 55
0

The functional way of doing things is mapping collections to functions

map(print, range(30))

However, because in python map returns a generator, you need to somehow iterate it, which you can do by converting it to a list

list(map(print, range(30)))
blue_note
  • 25,410
  • 6
  • 56
  • 79
  • 1
    Realise that this is called "producing side effects" and generates a list of `[None, None, None, ...]`. This is generally discouraged and reduces readability. – cs95 Oct 26 '17 at 11:20
  • @cᴏʟᴅsᴘᴇᴇᴅ: Indeed. However, `print` inherently is used for its side effects. In a pure functional style, it wouldn't exist. In general however, given a pure function, this would be the way. – blue_note Oct 26 '17 at 11:22
  • Yes, but you don't use `map` to exploit that? – cs95 Oct 26 '17 at 11:23
  • I just wanted to give an example of mapping. Not saying it should be done this way. A simple for loop would be the clearest way in this case. – blue_note Oct 26 '17 at 11:26