Reputation:
I'm new to Haskell and trying to see how I can write function that will take two integers and produce a list of all integers within that range.
Here's what I have so far but no luck.
rangeList :: Integer -> Integer -> [Integer]
rangeList n m
| n == m = []
| otherwise = n : n + (rangeList n (m-1))
Upvotes: 2
Views: 366
Reputation: 477794
What you aim to accomplish already exists. If both bounds are inclusive, this is:
rangeList :: Enum a => a -> a -> [a]
rangeList n m = [n .. m]
or if the upperbound is exclusive, you can make use of pred :: Enum a => a -> a
:
rangeListExcl :: Enum a => a -> a -> [a]
rangeListExcl n m = [n .. pred m]
The main problem with your own implementation is that n + rangeList n (m-1)
makes not much sense, since rangeList n (m-1)
will be a list of elements, and n
is here an Integer
, so you can not add these together. Even if you could doo that, it would still not work correctly, since the rangeList n (m-1)
would make a sequence between n
and m-1
, by adding n
to that result, you get a range between 2*n
and n+m-1
. The recursion shoud increment the upperbound with one, for example with:
rangeListExl :: (Ord a, Num a) => a -> a -> [a]
rangeListExcl n m
| n >= m = []
| otherwise = n : rangeListExcl (n+1) m
Upvotes: 5
Reputation: 48672
Your rangeList
function already exists in the Prelude
, under the name enumFromTo
.
Upvotes: 6