Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# Equivalent of Python range

Tags:

python

f#

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?

like image 532
Edward Minnix Avatar asked Apr 21 '16 21:04

Edward Minnix


2 Answers

seq { 3 .. 2 .. 20 }

results in

3 5 7 9 11 13 15 17 19

https://msdn.microsoft.com/en-us/library/dd233209.aspx

like image 85
trydis Avatar answered Nov 10 '22 20:11

trydis


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

  • Python 2 range method returns a Python list which is mutable.
  • Python 3 range method returns a Python range type which represents an immutable sequence of numbers.
  • F# sequence expression returns an 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
like image 20
Guy Coder Avatar answered Nov 10 '22 21:11

Guy Coder