Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the first apperance of a number in a list? Haskell

I need to make a function that takes a list and an element and returns a list in which the first occurrence of the element is removed: something like

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

What I tried is:

main :: IO()
main = do
    putStr ( show $ removeFst [1,5,2,3,5,3,4,5,6] 5)

removeFst :: [Int] -> Int -> [Int]
removeFst [] m = []
removeFst [x] m
    | x == m     = []
    | otherwise  = [x]
removeFst (x:xs) m 
    | x == m     = xs
    | otherwise  = removeFst xs m

But this doesn't work... it returns the list without the first elements. I think I should make the recursive call to make the list something like:

removeFst (x:xs) m
    | x == m     = xs
    | otherwise  = removeFst (-- return the whole list till element x) m
like image 580
Thanatos Avatar asked Jun 29 '13 14:06

Thanatos


2 Answers

You are very close, what you miss is prepending the elements before the first found m to the result list,

removeFst :: [Int] -> Int -> [Int]
removeFst [] m = []
removeFst (x:xs) m 
    | x == m     = xs
    | otherwise  = x : removeFst xs m
    --            ^^^ keep x /= m

Note that the special case for one-element lists is superfluous.

Also note that removeFst = flip delete with delete from Data.List.

like image 127
Daniel Fischer Avatar answered Nov 15 '22 08:11

Daniel Fischer


It should be mentioned that your function is equivalent to Data.List.delete.

Here another version:

import Data.List

removeFst xs x = front ++ drop 1 back where 
  (front, back) = break (==x) xs
like image 44
Landei Avatar answered Nov 15 '22 09:11

Landei