Friday, September 12, 2008

remove first element from list in Haskell

Hello All~

As you are aware, I am presently reading the beautiful book "The Haskell Road to Logic Maths and Programming" and another book called the "black Swan - The Impact of the highly Improbable" by Nassim Nicholas Taleb. As I have just started reading it yesterday, I will include my views on the book in the coming days.
However what I plan to do today is solve the exercise 1.10 from the haskell book, so here is the problem with my explanation.
Problem: Define a function removeFst that removes the first occurrence of an integer m, from a list of integers. If m does not occur in the list, the list remains unchanged.
For example let us consider the list [1,2,3,4,5,6,2], so if we call the program thus


removeFst 2 [1,2,3,4,5,6,2]


We should get the list [1,3,4,5,6,2] as return. Only the first occurrence of 2 is removed, any other 2 in the list is left unchanged.
I will present 2 solutions.
Solution 1: removes the first occurrence of 2.
Solution 2: removes all occurrences of 2.

Solution 1:

--Test for an empty list, if an empty list throw error.
removeFst n []=error "The list is empty "
--Cover the condition in case there is only 1 element in the array
removeFst n [x]|n==x=[] --Case n==x, show a blank array as output
|otherwise=[x]
--Handle the usual case, in case x==n, we return the tail else
--create a new array and append x recursively.
removeFst n (x:xs)|n==x=xs
|otherwise=x:removeFst n xs


Solution 2:

--Test for an empty list, if an empty list throw error.
removeFst n []=error "The list is empty "
--Cover the condition in case there is only 1 element in the array
removeFst n [x]|n==x=[] --Case n==x, show a blank array as output
|otherwise=[x]
--Handle the usual case, in case x==n, we return the tail else
--create a new array and append x recursively.
removeFst n (x:xs)|n==x=removeFst n xs --Do nothing and move to the next element
|otherwise=x:removeFst n xs


No comments: