views:

163

answers:

3

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
+2  A: 

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.

3lectrologos
+3  A: 
init' [x] = [x]

This is not correct. If you remove the last element of a one-element list, you don't get back the same list, you get back an empty list.

sepp2k
+7  A: 

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"

bobDevil
Thank you... That fixed it.
BM