是否可以更改内置haskell范围函数或文字的步长?

时间:2021-12-15 22:51:38

The default

[1..5]

gives this

[1,2,3,4,5]

and can also be done with the range function. Is it possible to change the step size between the points, so that I could get something like the following instead?

也可以使用范围功能完成。是否可以更改点之间的步长,以便我可以得到类似下面的内容?

[1,1.5,2,2.5,3,3.5,4,4.5,5] 

3 个解决方案

#1


[1,1.5..5]

#2


You have to be careful with floating point arithmetic. It can't represent 1.1 precisely, so if you try

你必须小心浮点运算。它不能精确地代表1.1,所以如果你试试

Prelude> [0,0.1 .. 1]
[0.0,0.1,0.2,0.30000000000000004,0.4,0.5,0.6,0.7,0.7999999999999999,0.8999999999999999,0.9999999999999999]

Best way is more like:

最好的方式更像是:

Prelude> map (/10) [0..10]
[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]

#3


Actually, [1..5] is syntactic sugar for

实际上,[1..5]是语法糖

enumFromTo 1 5 

and [1,1.5..5] for

和[1,1.5..5]

enumFromThenTo 1 1.5 5

For more information, see http://en.wikibooks.org/wiki/Haskell/Syntactic_sugar

有关更多信息,请参阅http://en.wikibooks.org/wiki/Haskell/Syntactic_sugar

#1


[1,1.5..5]

#2


You have to be careful with floating point arithmetic. It can't represent 1.1 precisely, so if you try

你必须小心浮点运算。它不能精确地代表1.1,所以如果你试试

Prelude> [0,0.1 .. 1]
[0.0,0.1,0.2,0.30000000000000004,0.4,0.5,0.6,0.7,0.7999999999999999,0.8999999999999999,0.9999999999999999]

Best way is more like:

最好的方式更像是:

Prelude> map (/10) [0..10]
[0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]

#3


Actually, [1..5] is syntactic sugar for

实际上,[1..5]是语法糖

enumFromTo 1 5 

and [1,1.5..5] for

和[1,1.5..5]

enumFromThenTo 1 1.5 5

For more information, see http://en.wikibooks.org/wiki/Haskell/Syntactic_sugar

有关更多信息,请参阅http://en.wikibooks.org/wiki/Haskell/Syntactic_sugar