m (This edit provides another method of computing the range without using reverse)
(added one solution with scanl)
Revision as of 23:15, 13 January 2012
Create a list containing all integers within a given range.
range x y = [x..y]
range = enumFromTo
range x y = take (y-x+1) $ iterate (+1) x
range start stop | start > stop = reverse (range stop start) | start == stop = [stop] | start < stop = start:range (start+1) stop
The following does the same but without using a reverse function
range :: Int -> Int -> [Int] range n m | n == m = [n] | n < m = n:(range (n+1) m) | n > m = n:(range (n-1) m)
or with scanl
range l r = scanl (+) l (replicate (l - r) 1)
Since there's already syntactic sugar for ranges, there's usually no reason to define a function like 'range' in Haskell. In fact, the syntactic sugar is implemented using the enumFromTo function, which is exactly what 'range' should be.