[Haskell-cafe] Haskell-Cafe Digest, Vol 151, Issue 22

Barak A. Pearlmutter barak at pearlmutter.net
Sat Mar 19 14:05:48 UTC 2016


> If I were to propose this, which I'm not, I would discuss what the
> [a,b..c] notation is meant to represent.  To me, personally and for no
> good reason, it looks like an iterator that yields numbers starting at
> a, adding (b-a) at each step and yielding the next number as long as
> it's less than or equal to c, and continuing as long as c is neither
> reached nor exceeded.

Yes, the current situation is somewhat odd.

$ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help

Prelude> [0,5..9]
[0,5]

Prelude> [0,0.5..0.9]
[0.0,0.5,1.0]

Prelude> [0.0..0.49999999999999991]
[0.0]

Prelude> [0.0..0.49999999999999992]
[0.0,1.0]

Prelude> :m Data.Ratio
Prelude Data.Ratio> [0..1%2]
[0 % 1,1 % 1]

This makes the construct into a serious bug generator for anything numeric.
For instance, consider a naive numeric integration of the sort one might wish to
exhibit while teaching Haskell this past pi day, Monday the fourteenth of March.

Prelude> let h=1e-1 in sum $ map (\x -> 4*h*sqrt(1-x^2)) [0,h..1]
3.304518326248318

Prelude> let h=1e-2 in sum $ map (\x -> 4*h*sqrt(1-x^2)) [0,h..1]
NaN

Prelude> let h=1e-3 in sum $ map (\x -> 4*h*sqrt(1-x^2)) [0,h..1]
NaN

Prelude> let h=1e-4 in sum $ map (\x -> 4*h*sqrt(1-x^2)) [0,h..1]
3.141791477784753

Prelude> let h=1e-5 in sum $ map (\x -> 4*h*sqrt(1-x^2)) [0,h..1]
3.1416126164824103

Prelude> let h=1e-6 in sum $ map (\x -> 4*h*sqrt(1-x^2)) [0,h..1]
NaN

One invariant that people seem to find natural regarding [x,y..z] is that its
elements are all between x and z (inclusive), regardless of the value of y.
This is, in part, because the mathematical notation [x,z] often denotes
the closed interval whose endpoints are x and z. I myself cannot think of
any advantage of the behaviour exhibited above.

To take a slightly deeper violated invariant, it seems like

  map f [x,y..z]

and

  [f x,f y..f z]

should be the same when f is a linear (in the numeric sense) function.
The current behaviour violates this.


More information about the Haskell-Cafe mailing list