How to remove the first instance 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 deleted: something like

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

What I tried:

 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 that will not work ... it returns a list without the first elements. I think I should make a recursive call to make the list look something like this:

 removeFst (x:xs) m | x == m = xs | otherwise = removeFst (-- return the whole list till element x) m 
+6
source share
2 answers

You are very close, what you skip adds elements to the first m found in the list of results,

 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 single-item lists is redundant.

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

+12
source

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

Here is another version:

 import Data.List removeFst xs x = front ++ drop 1 back where (front, back) = break (==x) xs 
+2
source

Source: https://habr.com/ru/post/948381/


All Articles