Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the step size of the built-in haskell range function or literal?

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] 
like image 781
Paul Wicks Avatar asked Feb 09 '09 19:02

Paul Wicks


3 Answers

[1,1.5..5]
like image 127
Johannes Weiss Avatar answered Nov 20 '22 01:11

Johannes Weiss


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

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]
like image 35
Paul Johnson Avatar answered Nov 20 '22 02:11

Paul Johnson


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

enumFromTo 1 5 

and [1,1.5..5] for

enumFromThenTo 1 1.5 5

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

like image 7
mattiast Avatar answered Nov 20 '22 00:11

mattiast