Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Haskell: How to implement my own version of init function

Tags:

haskell

init

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
like image 446
BM. Avatar asked Nov 30 '22 11:11

BM.


2 Answers

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"

like image 68
bobDevil Avatar answered Dec 05 '22 06:12

bobDevil


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.

like image 21
3lectrologos Avatar answered Dec 05 '22 05:12

3lectrologos