I've started learning F#, and one thing I've run into is I don't know any way to express the equivalent of the range
function in Python. I know [1..12]
is the equivalent of range(1,13). But what I want to be able to do is range(3, 20, 2)
(I know Haskell has [3,5..19]
). How can I express this?
seq { 3 .. 2 .. 20 }
results in
3 5 7 9 11 13 15 17 19
https://msdn.microsoft.com/en-us/library/dd233209.aspx
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With