我已经开始学习F#了,我遇到的一件事是我不知道用Python表达等同于range
函数的方法。我知道[1..12]
相当于范围(1,13)。但我想要做的是range(3, 20, 2)
(我知道Haskell有[3,5..19]
)。我怎么能表达这个呢?
答案 0 :(得分:11)
seq { 3 .. 2 .. 20 }
结果
3 5 7 9 11 13 15 17 19
答案 1 :(得分:4)
While the F# sequence expression seq { 3 .. 2 .. 20 }
is comparable in functionality if you have ever converted Python to F# you will find that the
IEnumerable<T>
which is immutable.The better way to interpret a Python range with regards to F# is to look at how it is often used. As the Python 2 documentation states
It is most often used in for loops.
and the Python 3 documentation states
is commonly used for looping a specific number of times in for loops.
and the Python 2 for
for x in range(0, 3):
print "We're on time %d" % (x)
and the Python 3 for
for i in range(5):
... print(i)
The closest F# is for in:
for i in 10 .. -1 .. 1 do
printf "%d " i