Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Great Addition #4

Closed
john9631 opened this issue Aug 14, 2022 · 4 comments
Closed

Great Addition #4

john9631 opened this issue Aug 14, 2022 · 4 comments

Comments

@john9631
Copy link

john9631 commented Aug 14, 2022

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
Copy link
Author

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

@Delta456
Copy link
Owner

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.

@john9631
Copy link
Author

john9631 commented Aug 14, 2022

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]
>>>

@Delta456
Copy link
Owner

Delta456 commented Mar 2, 2023

I have decided to go with #5

@Delta456 Delta456 closed this as completed Mar 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants