range icon indicating copy to clipboard operation
range copied to clipboard

Great Addition

Open john9631 opened this issue 3 years ago • 3 comments

As a keen Pythonista I loved the idea of implementing range for V but I didn't like having to label the arguments. Here's an adaptation of your implementation using variable length args and generics. If you'd like to use it with credit, please do.

https://github.com/john9631/range

module range

pub fn range<T>(best ...T) []T {
	mut begin, mut end, mut step := T(0), T(1), T(1)
	mut arr := []T{}
	match best.len {
		1 {
			end = best[0]
		}
		2 {
			begin, end = best[0], best[1]
		}
		3 {
			begin, end, step = best[0], best[1], best[2]
		}
		else {
			eprintln('eprintln('Please input 1 to 3 integers or floats: range(start, stop, step)')')
			exit(1)
		}
	}

	if step == T(0) {
		eprintln('range: step cannot be zero')
		exit(1)
	}
	if (begin > end && step > T(0)) || (begin < end && step < T(0)) {
		return []
	}
	if step > T(0) {
		for i := begin; i < end; i += step {
			arr << i
		}
	} else {
		for i := begin; i > end; i += step {
			arr << i
		}
	}
	return arr
}

john9631 avatar Aug 14 '22 02:08 john9631

Oh. Yes, and import it with import range { range } to give a perfectly pythonic usage !

john9631 avatar Aug 14 '22 02:08 john9631

I was looking to rewrite the module and looks like you are already working on it. So far your code seems great but I would like to know how will range(1.1, 1.2) gonna work with your implementation because it has to be a part of this.

Delta456 avatar Aug 14 '22 14:08 Delta456

Surprisingly well seeing I hadn't looked at the numpy variations much. I started on V last week so I'm a bit new to it.

FYI, I also did a new test file which you can find at my git. Not sure how to test deliberate fails yet so haven't. Also not sure that this should fail to exit as my grasp of idiomatic V isn't strong - surprised you chose to fail with 1 rather than -1 (I'm a C/C++/Python person but am really enjoying V).

The numpy reverse looks ok too:

>>> range.range(1.25, 0.0, -.25)
[1.25, 1, 0.75, 0.5, 0.25]
>>> range.range(1.25, -0.25, -.25)
[1.25, 1, 0.75, 0.5, 0.25, 0]
>>> range.range(1.25, -0.000001, -.25)
[1.25, 1, 0.75, 0.5, 0.25, 0]
>>>

john9631 avatar Aug 14 '22 22:08 john9631

I have decided to go with https://github.com/Delta456/range/pull/5

Delta456 avatar Mar 02 '23 13:03 Delta456