Groovy range with a 0.5 step size

2020-02-10 04:29发布

What's the most elgant way in Groovy to specify a range of integers and the 0.5 steps between them? e.g.: 1, 1.5, 2, 2.5, 3, 3.5, 4

Edit: To clarify: As an end result I need a range object for use in a Grails constraint. Though I suppose a list would be OK too.

8条回答
爷的心禁止访问
2楼-- · 2020-02-10 05:03

(1..7).collect{0.5*it} is the best I can think of

查看更多
淡お忘
3楼-- · 2020-02-10 05:09

my answer is the following:

(1..4).step(0.5)
查看更多
狗以群分
4楼-- · 2020-02-10 05:13

A little late, but this works too

A one-liner for your above set:

(2..8)*.div(2)

查看更多
Melony?
5楼-- · 2020-02-10 05:19

Soo, to build on above. To test if a value val is in the range 1..n but with half values:

def range = 2..(n*2).collect { return it/2.0 }
return range.contains( val )

Something like that would work, but isn't as pretty as I'd like, but it lets you build the range once and use it multiple times, if you need that.

查看更多
Anthone
6楼-- · 2020-02-10 05:23

FYI, as of Groovy 1.6.0, it seems not to support natively. There exists only ObjectRange.step(int) at the moment.

http://groovy.codehaus.org/api/groovy/lang/ObjectRange.html#step%28int%29

查看更多
We Are One
7楼-- · 2020-02-10 05:23
def r = []
(0..12).each() {
  r << it
  r << it + 0.5
}
查看更多
登录 后发表回答