Remove an element from a list of lists Haskell - list

I' am trying to remove an element from a list of lists, but only if the element is on a list with length 1. For example:
removeElement 1 [[2,3],[1,2],[1]]
[[2,3],[1,2]]
removeElement 2 [[1,2,3,4]]
[[1,2,3,4]]
removeElement 3 [[3],[1,4,5]]
[[1,4,5]]
So far I have this, but I don't know how to continue, or which function use.
removeElement :: (Eq a) => a -> [[a]] -> [[a]]
removeElement a [[]] = []
removeElement a ((x:xs):rs) = if a == x then (xs:rs) else [x] :( removeElement a (xs:rs))

This is an example of filtering:
removeElement :: Eq a => a -> [[a]] -> [[a]]
removeElement e = filter (/= [e])
Testing your examples with ghci:
> removeElement 1 [[2,3],[1,2],[1]]
[[2,3],[1,2]]
> removeElement 2 [[1,2,3,4]]
[[1,2,3,4]]
> removeElement 3 [[3],[1,4,5]]
[[1,4,5]]

Related

How do I split a list on certain conditions in Haskell?

As a programming exercise I'm trying to build a function in Haskell where given a list it splits the list whenever an element is repeated. [1,2,3,3,4,5] would split into [[1,2,3],[3,4,5]] for example. My first idea was to split the list into a list of lists with single elements, where [1,2,3,3,4,5] would become [[1],[2],[3],[3],[4],[5]] and then merge lists only when the elements being compared are not equal, but implementing this has been a headache for me as I'm very new to Haskell and recursion has always given me trouble. I think something is wrong with the function I'm using to combine the lists, it will only ever return a list where all the elements that were broken apart are combined, where [1,2,3,3,4,5] becomes [[1],[2],[3],[3],[4],[5]] but my split_help function will transform this into [[1,2,3,3,4,5]] instead of [[1,2,3],[3,4,5]]
I've pasted my incomplete code below, it doesn't work right now but it should give the general idea of what I'm trying to accomplish. Any feedback on general Haskell code etiquette would also be welcome.
split_breaker breaks the list into a list of list and split_help is what I'm trying to use to combine unequal elements.
split_help x y
| x /= y = x ++ y
| otherwise = []
split_breaker :: Eq a => [a] -> [[a]]
split_breaker [] = []
split_breaker [x] = [[x]]
split_breaker (x:xs) = [x]:split_breaker xs
split_at_duplicate :: Eq a => [a] -> [[a]]
split_at_duplicate [x] = [[x]]
split_at_duplicate (x:xs) = foldl1 (split_help) (split_breaker [xs])
Do you want to work it something like this?
splitAtDup [1,2,3,3,3,4,4,5,5,5,5,6]
[[1,2,3],[3],[3,4],[4,5],[5],[5],[5,6]]
Am I right?
Then do it simple:
splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup (x : y : xs) | x == y = [x] : splitAtDup (y : xs)
splitAtDup (x : xs) =
case splitAtDup xs of
x' : xs' -> (x : x') : xs'
_ -> [[x]]
splitAtDup [] = []
Here's a maximally lazy approach:
splitWhen :: (a -> a -> Bool) -> [a] -> [[a]]
splitWhen f = foldr go [[]] where
go x acc = (x:xs):xss where
xs:xss = case acc of
(z:_):_ | f x z -> []:acc
_ -> acc
splitAtDup :: Eq a => [a] -> [[a]]
splitAtDup = splitWhen (==)
To verify the laziness, try this:
take 2 $ take 4 <$> splitAtDup (1:2:3:3:4:5:6:undefined)
It can be fully evaluated to normal form as [[1,2,3],[3,4,5,6]].

Is there a way to count the number of occurrences of the first index of a list of tuples

I am trying to write a function in Haskell that takes in a list of tuples (the first index of each tuple is an int and the second index a char) and an integer and will return the number of occurrences in the first index of each tuple. So far I have:
counter :: Eq a => [a] -> a -> Int
counter [] find = 0
counter ys find = length xs
where xs = [xs | xs <- ys, xs == find]
For example, if I run:
counter [(3,"a"),(4,"b"),(2,"a"), (3, "f"),(3,"t")] 3
This should return 3 since there are 3 tuples in the list where the first index is 3.
You need to unpack the 2-tuple and check the first item, so:
counter :: Eq a => [(a, b)] -> a -> Int
counter ys find = length [ x | (x,_) <- ys, x == find]
or with filter :: (a -> Bool) -> [a] -> [a]:
counter :: Eq a => [(a, b)] -> a -> Int
counter ys find = length (filter ((find ==) . fst) ys)

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

How do I generate all combinations of list elements to a given length with iterate?

I'm trying to write a function using iterate which should generate all combinations of the elements:
f :: [a] -> [[[a]]]
f [1,2] =
[ [[1] , [2]] -- all combinations of length 1
, [[1,1],[1,2],[2,1],[2,2]], -- all combinations of length 2
, [[1,1,1],... ] -- all combinations of length 3
, ... -- and so on
] -- infinitely
I've tried the following approach
f :: [a] -> [[[a]]]
f list = iterate genLists list
genLists :: [a] -> [[a]]
genLists list = [ [k] | k<-list ]
However, Hugs gives me the following error:
Type error in application
*** Expression : iterate genLists list
*** Term : genLists
*** Type : [a] -> [[a]]
*** Does not match : [[a]] -> [[a]]
*** Because : unification would give infinite type
I don't really know why I get the error. Also, how can I generate those combinations using only iterate? I cannot import any other module since this is an assignment.
Lets see why you get the error:
iterate :: (a -> a ) -> a -> [a]
genLists :: [a] -> [[a]]
As you can see, iterate takes a function that takes and returns the same type. However, genLists doesn't do that. It takes a list and returns a list of lists.
Since you actually want f :: [a] -> [[[a]]], genLists return type is actually fine. However, its argument type is wrong. It has to be of type genLists :: [[a]] -> [[a]]:
f :: [a] -> [[[a]]]
f xs = iterate genLists [[x] | x <- xs]
where
genLists yss = [ x : ys | x <- xs , ys <- yss]
Here is one possible implementation, using the applicative style (which you can learn more about here).
import Control.Applicative
f :: [a] -> [[[a]]]
f xs = iterate genLists $ map pure xs
where
genLists xss = (:) <$> xs <*> xss
Then,
λ> take 3 $ f [1,2]
[[[1],[2]],[[1,1],[1,2],[2,1],[2,2]],[[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]]
Here is an alternative, if you don't want to or cannot use applicative stuff:
f :: [a] -> [[[a]]]
f xs = iterate genLists $ map (\x -> [x]) xs
where
genLists xss = [y : ys | y <- xs, ys <- xss]

Repeatedly call a function: Haskell

Basically, I want to create a function that takes a list of integers and another list (this list can be of any type) and produce another list that has the elements in it from the "other list" at intervals specified by the list of integers. If I input:
ixs [2,3,1] [3,2,1]
[2,1,3]
So far I have:
ix :: Int -> [a] -> a
ix a [] = error "Empty list"
ix 1 (x:xs) = x
ix a (x:xs) = ix (a-1) xs
ixs :: [Int] -> [a] -> [a]
ixs [] _ = []
ixs _ [] = []
ixs (x:xs) (y) = ix x y: []
With this code I only get one value returned like so:
ixs [1,2] [2,1]
[2]
How can I call the ix function repeatedly on (x:xs) so that it returns all the values I want?
Edit: I want to do this without using any standard prelude functions. I just want to use recursion.
This is (almost) a map of an indexing ("getting the value at") of the first list over the second list
import Data.List ((!!))
-- (!!) :: [a] -> Int -> a
ixs :: [Int] -> [b] -> [b]
ixs ary ixes = map (ary !!) ixes
But you also have wraparound when you index a 3-element list by (3 mod 3 = 0), so we ought to just map mod over the indexes
ixs ary ixes = map (ary !!) (map (`mod` length ary) ixes)
And then we can simplify to "pointless style"
ixs ary = map (ary !!) . map (`mod` length ary)
which reads nicely as "map the indices modulo the array length then map the array indexing over the resultant indices". And it gives the right result
> ixs [2,3,1] [3,2,1]
[2,1,3]
To break down the Prelude function and Data.List function, we have
(!!) :: [b] -> Int -> b
(x:_) !! 0 = x
(_:xs) !! n
| n > 0 = xs !! (n-1)
| otherwise = error "List.(!!): negative argument."
_ !! _ = error "List.(!!): index too large."
and
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
You could reverse the order of the arguments
ix' :: [a] -> Int -> a
ix' [] a = error "Empty list"
ix' (x:xs) 1 = x
ix' (x:xs) a = ix' xs (a-1)
to make it easier to map ix over a list of indeces:
ixs' :: [a] -> [Int] -> [a]
ixs' xs is = map (ix' xs) is
Like this:
> ixs' "Hello Mum" [1,5,6,1,5,6,1,5]
"Ho Ho Ho"
but it would be nicer to use flip to swap the arguments - ix' is just flip ix, so you could do
ixs :: [Int] -> [a] -> [a]
ixs is xs = map (flip ix xs) is
which you then call the way round you'd planned:
> ixs [1,5,6,1,5,6,1,5] "Hello Mum"
"Ho Ho Ho"
Perhaps something like this
ixs :: [Int] -> [a] -> [a]
ixs idx a = map (`ix` a) idx
What you want to do is map your index function across all the values in the list of
indices to index the second list. Note that your ix function is just !! function, but starts indexing from 1 instead of 0.