范围A至B,其中A> F#中的B [英] Ranges A to B where A > B in F#

查看:66
本文介绍了范围A至B,其中A> F#中的B的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在F#中找到了一个我称之为怪癖的东西,想知道它是出于设计还是出于误解,如果是出于设计原因,为什么会这样... 如果您写的任何范围表达式的第一项都大于第二项,则返回的序列为空.观察反射器表明这是设计使然,但是我真的找不到为什么一定要这样做的原因. 复制它的示例是:

I've just found something I'd call a quirk in F# and would like to know whether it's by design or by mistake and if it's by design, why is it so... If you write any range expression where the first term is greater than the second term the returned sequence is empty. A look at reflector suggests this is by design, but I can't really find a reason why it would have to be so. An example to reproduce it is:


[1..10] |> List.length
[10..1] |> List.length

第一个将打印出10,第二个将打印出0. 测试是在F#CTP 1.9.6.2.中进行的.

The first will print out 10 while the second will print out 0. Tests were made in F# CTP 1.9.6.2.

编辑:感谢您建议明确显示范围,但仍然有一个案例(这是促使我提出此问题的原因).如果A和B是变量,并且尽管它们始终不同,但又一个常数却始终大于另一个,该怎么办呢? 考虑到范围表达式似乎无论如何都不会在编译时进行优化,如果A和B的整数不允许负数步,那么代码是否有充分的理由确定该步(未明确指定)?

EDIT: thanks for suggesting expliciting the range, but there's still one case (which is what inspired me to ask this question) that won't be covered. What if A and B are variables and none is constantly greater than the other although they're always different? Considering that the range expression does not seem to get optimized at compiled time anyway, is there any good reason for the code which determines the step (not explicitly specified) in case A and B are ints not to allow negative steps?

推荐答案

根据其他答案的建议,您可以

As suggested by other answers, you can do

[10 .. -1 .. 1] |> List.iter (printfn "%A")

例如

[start .. step .. stop]

这篇关于范围A至B,其中A> F#中的B的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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