Reputation: 51
I'm currently working on function which takes 2 integers and a list as arguments and returns a list with the elements of the first list which are at the positions between these 2 integers (function :: Int->Int->[u]->[u]). For example:
>function 2 5 [1..10]
returns
[2,3,4,5]
The above example is working with my current code...but if I insert an infinite list like [0..] it returns an "ERROR - Garbage collection fails to reclaim sufficient space". Any suggestions? Here is the code
function :: Int->Int->[u]->[u]
function i j s
|i<0 = function 0 j s
|j< length s = function i j (init s)
|j-i< (length s)-1 = function i j (tail s)
|otherwise = s
Upvotes: 0
Views: 164
Reputation: 20415
An approach based in zipping with indexes and filtering out those not within the given range,
f :: Int -> Int -> [a] -> [a]
f i j = map (snd) . filter (\v -> fst v `elem` [i..j]) . zip [1..]
Upvotes: 0
Reputation: 7360
The problem with your implementation is the use of length
. Using length
with an infinite list as parameter is not a good idea because, well, the list in infinitely long.
I would suggest altering the implementation to use other functions which can work on infinite lists, such as drop
and take
:
function :: Int -> Int -> [a] -> [a]
function i j list = take (i - j + 1) (drop (i - 1) list)
Or, pointfree:
function i j = take (j - i + 1) . drop (i - 1)
Upvotes: 8
Reputation: 31
How about: the length of an infinite list? I think that is not possible.
Upvotes: 1