Reputation: 109
I want to write a function that extracts n number of elements from the start of a list in Haskell. I know it can be done using the built-in 'take' function and I have done it, which works. However, I can't seem to write a function without take. This is my code.
takeElem' :: Int -> [t] -> [t]
takeElem' _ [] = []
takeElem' n (x:xs) = [x] ++ takeElem' (n-1) xs
This code complies fine but when I test it for example
takeElem' 3 "hello"
It returns "hello" instead of "hel"
Any idea what could be wrong?
Upvotes: 0
Views: 97
Reputation: 71
It should be 0 _ instead of _ []. Because you are saying it is [] when you took everything of the list instead of [] when your n reaches 0.
Upvotes: 0
Reputation: 109
I didn't add what should happen in the case when n is zero. I just added
takeElem' 0 list = []
it works now.
Upvotes: 2