Remove item from list of list in Haskell - list

I have a problem with haskell fuction. I want to remove specific elements from list o list [[Int]]
There're many easy way to remove element in list [Int]
for example
removeItem :: Int -> [Int] -> [Int]
removeItem _ [] = []
removeItem x (y:ys) | x == y = removeItem x ys
| otherwise = y : removeItem x ys
but I can't write
removeItem :: Int -> [[Int]] -> [[Int]]
it should give a result:
removeItem 1 [[1],[2,2],[3],[1]]
[[],[2,2],[3],[]]
Can anybody help me

So you can't have removeItem both be Int -> [Int] -> [Int] and Int -> [[Int]] -> [[Int]]. Instead, I'll call the latter removeItem'. You already know how to remove an item from just a regular list, so just use map to do it on a list of those lists. Implementation is then simple:
removeItem' :: Int -> [[Int]] -> [[Int]]
removeItem' x = map (removeItem x)

Related

Haskell how to drop all 0 of the list until one of the elements /= 0?

I'm new to Haskell and I'm trying to figure out how to write a code, that drops all zeros until an element of the list is >0.
So for example:
Input: [0,0,5,6,0]
Output: [5,6,0]
So far I have wrote this:
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (x:xs)
| x == 0 = drop x (xs)
| otherwise = zeroUntil xs
But somehow intead of [5,6,0] i get [ ].
Can anybode please explain what did I do wrong?
You can make use of dropWhile :: (a -> Bool) -> [a] -> [a] and thus drop items as long as these are zeros:
zeroUntil :: [Int] -> [Int]
zeroUntil = dropWhile (0 ==)
If you want to drop zeros until an element is greater than zero, you can make use of recursion. Here your recursive case should yield elements if these are less than zero:
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (0:xs) = zeroUntil xs
zeroUntil (x:xs)
| x > 0 = x : xs -- ← end of recursion, return the list
| otherwise = x : zeroUntil xs -- ← yield x and recurse
for example:
Prelude> zeroUntil [0,0,5,6,0]
[5,6,0]
Prelude> zeroUntil [0,-1,5,6,0]
[-1,5,6,0]
zeroUntil :: [Int] -> [Int]
zeroUntil [] = []
zeroUntil (x:xs)
| x == 0 = drop x (xs)
| otherwise = [x] ++ (zeroUntil xs)
You have to add the first element (x) to the list returned by the recursive call, otherwise you return a empty list.

Adding zeros between elements in list?

I'm trying to change a list in haskell to include 0 between every element. If we have initial list [1..20] then i would like to change it to [1,0,2,0,3..20]
What i thought about doing is actually using map on every function, extracting element then adding it to list and use ++[0] to it but not sure if this is the right approach or not. Still learning haskell so might have errors.
My code:
x = map classify[1..20]
classify :: Int -> Int
addingFunction 0 [Int]
addingFunction :: Int -> [a] -> [a]
addingFunction x xs = [a] ++ x ++ xs
intersperse is made for this. Just import Data.List (intersperse), then intersperse 0 yourList.
You cannot do this with map. One of the fundamental properties of map is that its output will always have exactly as many items as its input, because each output element corresponds to one input, and vice versa.
There is a related tool with the necessary power, though:
concatMap :: (a -> [b]) -> [a] -> [b]
This way, each input item can produce zero or more output items. You can use this to build the function you wanted:
between :: a -> [a] -> [a]
sep `between` xs = drop 1 . concatMap insert $ xs
where insert x = [sep, x]
0 `between` [1..10]
[1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10]
Or a more concise definition of between:
between sep = drop 1 . concatMap ((sep :) . pure)
With simple pattern matching it should be:
addingFunction n [] = []
addingFunction n [x] = [x]
addingFunction n (x:xs) = x: n : (addingFunction n xs)
addingFunction 0 [1..20]
=> [1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,0,14,0,15,0,16,0,17,0,18,0,19,0,20]
If you want to use map to solve this, you can do something like this:
Have a function that get a int and return 2 element list with int and zero:
addZero :: List
addZero a = [0, a]
Then you can call map with this function:
x = map addZero [1..20] -- this will return [[0,1], [0, 2] ...]
You will notice that it is a nested list. That is just how map work. We need a way to combine the inner list together into just one list. This case we use foldl
combineList :: [[Int]] -> [Int]
combineList list = foldl' (++) [] list
-- [] ++ [0, 1] ++ [0, 2] ...
So the way foldl work in this case is that it accepts a combine function, initial value, and the list to combine.
Since we don't need the first 0 we can drop it:
dropFirst :: [Int] -> [Int]
dropFirst list = case list of
x:xs -> xs
[] -> []
Final code:
x = dropFirst $ combineList $ map addZero [1..20]
addZero :: Int -> [Int]
addZero a = [0, a]
combineList :: [[Int]] -> [Int]
combineList list = foldl (++) [] list
dropFirst :: [Int] -> [Int]
dropFirst list = case list of
x:xs -> xs
[] -> []
We here can make use of a foldr pattern where for each element in the original list, we prepend it with an 0:
addZeros :: Num a => [a] -> [a]
addZeros [] = []
addZeros (x:xs) = x : foldr (((0 :) .) . (:)) [] xs
If you don't want to use intersperse, you can write your own.
intersperse :: a -> [a] -> [a]
intersperse p as = drop 1 [x | a <- as, x <- [p, a]]
If you like, you can use Applicative operations:
import Control.Applicative
intersperse :: a -> [a] -> [a]
intersperse p as = drop 1 $ as <**> [const p, id]
This is basically the definition used in Data.Sequence.

Breaking up a list into sublists with recursion

I'm trying to write a function with the type declaration [(Int, Bool)] -> [[Int]]. I want the function to only add Ints to the same nested sublist if the Boolean is True. However if the Boolean is False, I want the Int associated with the next True bool to be added to a new sublist. For example: An input of
[(1,True),(2,True),(3,False),(4,True),(5,False),(6,False),(7,True)]
should return
[[1,2],[4],[7]].
My code so far:
test:: [(Int, Bool)] -> [[Int]]
test xs = case xs of
[]->[]
x:xs
| snd x == True -> [(fst x)] : test xs
| snd x == False -> test xs
I'm currently having issues on adding concurrent Ints to the same list if their bools are both True.
You can break this problem into two sub-problems.
For any given list, take the head of this list and match it against the rest of list. There are two possibilities during this matching: i) You are successful i.e. you match, and if so, you collect the matched value and continue looking for more values, or ii) You fail, i.e. you don't match, and if so, you stop immediately and return the so far matched result with rest of, not-inspected, list.
collectF :: (Eq a) => (a -> Bool) -> [a] -> ([a], [a])
collectF f [] = ([], [])
collectF f (x : xs)
| f x = let (ys, zs) = collectF f xs in (x : ys, zs)
| otherwise = ([], x : xs)
Now that you have the collectF function, you can use it recursively on input list. In each call, you would get a successful list with rest of, not-inspected, list. Apply collectF again on rest of list until it is exhausted.
groupBy :: (Eq a) => (a -> a -> Bool) -> [a] -> [[a]]
groupBy _ [] = []
groupBy f (x : xs) =
let (ys, zs) = collectF (f x) xs in
(x : ys) : groupBy f zs
*Main> groupBy (\x y -> snd x == snd y) [(1,True),(2,True),(3,False),(4,True),(5,False),(6,False),(7,True)]
[[(1,True),(2,True)],[(3,False)],[(4,True)],[(5,False),(6,False)],[(7,True)]]
I am leaving it to you to remove the True and False values from List. Also, have a look at List library of Haskell [1]. Hope, I am clear enough, but let me know if you have any other question.
[1] http://hackage.haskell.org/package/base-4.12.0.0/docs/src/Data.OldList.html#groupBy
Repeatedly, drop the Falses, grab the Trues. With view patterns:
{-# LANGUAGE ViewPatterns #-}
test :: [(a, Bool)] -> [[a]]
test (span snd . dropWhile (not . snd) -> (a,b))
| null a = []
| otherwise = map fst a : test b
Works with infinite lists as well, inasmuch as possible.
Here's how I'd write this:
import Data.List.NonEmpty (NonEmpty(..), (<|))
import qualified Data.List.NonEmpty as NE
test :: [(Int, Bool)] -> [[Int]]
test = NE.filter (not . null) . foldr go ([]:|[])
where
go :: (Int, Bool) -> NonEmpty [Int] -> NonEmpty [Int]
go (n, True) ~(h:|t) = (n:h):|t
go (n, False) l = []<|l
Or with Will Ness's suggestion:
import Data.List.NonEmpty (NonEmpty(..))
test :: [(Int, Bool)] -> [[Int]]
test = removeHeadIfEmpty . foldr prependOrStartNewList ([]:|[])
where
prependOrStartNewList :: (Int, Bool) -> NonEmpty [Int] -> NonEmpty [Int]
prependOrStartNewList (n, True) ~(h:|t) = (n:h):|t
prependOrStartNewList (n, False) l = []:|removeHeadIfEmpty l
removeHeadIfEmpty :: NonEmpty [Int] -> [[Int]]
removeHeadIfEmpty (h:|t) = if null h then t else h:t

Making List of Lists Haskell

i am trying to get pairs of coords and i have got this function that outputs: [9,0,9,1]....... etc
addVal :: Int -> [Int] -> [Int]
addVal i [] = []
addVal i (x:xs) = i:x : addVal i xs
but i want the output to be a list of lists : [[9,0],[9,1]]
addVal :: Int -> [Int] -> [[Int]]
addVal i [] = [[]]
how do i get it so the it will make each pair a list so i i can use it with my other functions to get the smallest of the pairs
You are almost there, instead of i:x you have to use [i,x]. Note that you want the elements in the new list, so you create [i,x] and pass it up.
addVal :: Int -> [Int] -> [[Int]]
addVal i [] = []
addVal i (x:xs) = [i,x] : addVal i xs
Demo in ghci
λ> addVal 9 [1,2]
[[9,1],[9,2]]

Learning Haskell: How to remove an item from a List in Haskell

Trying to learn Haskell. I am trying to write a simple function to remove a number from a list without using built-in function (delete...I think). For the sake of simplicity, let's assume that the input parameter is an Integer and the list is an Integer list. Here is the code I have, Please tell me what's wrong with the following code
areTheySame :: Int -> Int-> [Int]
areTheySame x y | x == y = []
| otherwise = [y]
removeItem :: Int -> [Int] -> [Int]
removeItem x (y:ys) = areTheySame x y : removeItem x ys
The others are right that the problem is the : operator. I would say that your areTheySame function that returns a list is the wrong approach anyway, though. Rather than switch to the ++ operator, a better implementation of that function would be:
removeItem _ [] = []
removeItem x (y:ys) | x == y = removeItem x ys
| otherwise = y : removeItem x ys
As you can see, this is a pretty simple implementation. Also, consing like this is much less taxing for your program than appending a bunch of lists together. It has other benefits as well, such as working lazily.
The : operator doesn't do what you think it does:
(:) :: a -> [a] -> [a]
It takes an item of type a and adds it to the beginning of a list of type a. You're using it to join two lists of type a. For that, you need to use ++:
(++) :: [a] -> [a] -> [a]
Also, if you make a recursive function, it needs an ending condition. So try this:
removeItem _ [] = []
removeItem x (y:ys) = areTheySame x y ++ removeItem x ys
That way, when you get to the end of the list, the function will stop recursing.
You can also do this as a list-comprehension
delete :: Eq a => a -> [a] -> [a]
delete deleted xs = [ x | x <- xs, x /= deleted ]
I wrote a function in just one line of code:
remove element list = filter (\e -> e/=element) list
For example:
remove 5 [1..10]
[1,2,3,4,6,7,8,9,10]
remove 'b' ['a'..'f']
"acdef"
This is the minimal fix to make your example work:
removeItem :: Int -> [Int] -> [Int]
removeItem _ [] = []
removeItem x (y:ys) = areTheySame x y ++ removeItem x ys
First, you need to use ++ to concatenate lists, as the : operator used by you adds just one element to the beginning of a list (it can neither be used to add lists with one element nor to add empty lists). You first compare the head of the list (y) to the item you want to remove and correctly return the item or an empty list using areTheySame. Then you want to recursively continue using removeItem on the rest of the list (ys). The resulting list needs to be concatenated using ++.
Second, as Chris Lutz noted, you need an ending condition when you reach the end of the list. By adding this line, Haskell knows what to do with an empty list (that is, nothing, just return an empty list).
As Chuck said, you can simplify the code for this task by having removeItem not delegate the task of the comparison, but compare itself and throw away the element if it should be removed, otherwise keep it at the list head (using :). In any case, continue recursively with the rest of the list.
-- nothing can be removed from an empty list
-- ==> return empty list and stop recursion
removeItem _ [] = []
-- if the list is not empty, cut off the head in y and keep the rest in ys
-- if x==y, remove y and continue
removeItem x (y:ys) | x == y = removeItem x ys
-- otherwise, add y back and continue
| otherwise = y : removeItem x ys
For reference, you may be interested in seeing how it's done in delete from Data.List.
You could leave areTheySame as is, but you'd then need to use concatMap in removeItem to collapse the empty lists:
removeItem :: Int -> [Int] -> [Int]
removeItem x xs = concatMap (areTheySame x) xs
or equivalently
removeItem :: Int -> [Int] -> [Int]
removeItem x = concatMap (areTheySame x)
Note that the types of your functions could be more general:
areTheySame :: (Eq a) => a -> a -> [a]
removeItem :: (Eq a) => a -> [a] -> [a]
This allows removal of items from lists of any type for which == is defined, not just Int.
I believe all the solutions given so far work differently than Data.List.delete, which only deletes the first member.
deleteFromList x xs =
case break (==x) xs of
(_,[]) -> xs
(notsat,sat) -> notsat ++ tail sat
was my attempt to delete only the first member (haven't peaked at D.L yet).
It's unclear which behavior the top poster wants.