Learning Haskell: How to implement my own version of init function
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] -&g开发者_Python百科t; [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.
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.
Here is my version try this.
init' :: [a] -> [a]
init' [] = error("This is not right, empty list is not allowed here")
init' (x:[]) = [x]
init' (x:xs:[]) = [x]
init' (x:xs) = x: init' xs
精彩评论