As part of learning Haskell, I am trying to implement my own version of various functions associated with Lists. Right now I am stuck on the init function. init function in Haskell returns all the elements in a List other than the last element.
Here is what I have done so far.
init' :: [Int] -> [Int]
init' [] = error "This function cannot be applied to an empty list"
init' [x] = [x]
init' (x:xs) = x : init' xs
Your problem is your base case. Here:
init' [x] = [x]
You are saying that when you get down to a list with one element in it, you want to return that same list. This is not the desired outcome. When you have a list with just one element in it, you want to return an empty list (all but the last element for a single item is an empty list).
init' [x] = []
On a side note, you should probably declare it as
init' :: [a] -> [a]
Using 'a' as the type generalizes it to lists of anything, as opposed to just Ints. That way you could call init' on any sort of list. For example init' "abcde" would give you "abcd"
Your second rule should be:
init' [x] = []
When a list has only one element, then it is the last one, so the list without the last element is just the empty list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With