为什么我的一些范围是疯狂的? [英] Why are some of my ranges insane?

查看:41
本文介绍了为什么我的一些范围是疯狂的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将范围的常见字符串描述(例如 1-9)解析为实际范围(例如 1 .. 9),但在包含时经常得到奇怪的结果两位数.例如,1-10 产生单个值 1 而不是十个值的列表,11-20 给了我四个值(11 10 21 20),其中一半甚至不在预期的数值范围内:

I tried parsing a common string depiction of ranges (e.g. 1-9) into actual ranges (e.g. 1 .. 9), but often got weird results when including two digit numbers. For example, 1-10 results in the single value 1 instead of a list of ten values and 11-20 gave me four values (11 10 21 20), half of which aren't even in the expected numerical range:

put get_range_for('1-9');
put get_range_for('1-10');
put get_range_for('11-20');

sub get_range_for ( $string ) {

    my ($start, $stop) = $string.split('-');

    my @values = ($start .. $stop).flat;

    return @values;
}

打印:

1 2 3 4 5 6 7 8 9
1
11 10 21 20

而不是预期:

1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20

<小时>

(我在发布这个问题之前就想到了这一点,所以我在下面进行了回答.如果您想详细说明,请随意添加您自己的答案).


(I figured this out before posting this question, so I have answered below. Feel free to add your own answer if you'd like to elaborate).

推荐答案

问题确实在于 .split 返回的是 Str 而不是 Int,原来的答案解决了.但是,我宁愿像这样实现我的get_range_for":

The problem is indeed that .split returns Str rather than Int, which the original answer solves. However, I would rather implement my "get_range_for" like this:

sub get_range_for($string) {
    Range.new( |$string.split("-")>>.Int )
}

这将返回一个 Range 对象而不是一个 Array.但是对于迭代(这是您最有可能使用它的目的),这没有任何区别.此外,对于更大的范围,get_range_for"的其他实现可能会占用大量内存,因为它将Range 生动地转化为Array.这对于3-10"来说无关紧要,但对于1-10000000"却很重要.

This would return a Range object rather than an Array. But for iteration (which is what you most likely would use this for), this wouldn't make any difference. Also, for larger ranges the other implementation of "get_range_for" could potentially eat a lot of memory because it vivifies the Range into an Array. This doesn't matter much for "3-10", but it would for "1-10000000".

请注意,此实现使用 >>.Int 对从 .split 返回的所有值调用 Int 方法,然后将它们作为单独的参数使用|Range.new.如果 .split 返回 1 个值(如果它无法拆分)或超过 2 个值(如果字符串中出现多个连字符),这也会爆炸.

Note that this implementation uses >>.Int to call the Int method on all values returned from the .split, and then slips them as separate parameters with | to Range.new. This will then also bomb should the .split return 1 value (if it couldn't split) or more than 2 values (if multiple hyphens occurred in the string).

这篇关于为什么我的一些范围是疯狂的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆