I have a list. I need to create a a new list, like in example below:
[3, 3, 1, 3] to [3, 3, 3, 1, 1, 3, 3].
can anybody tell what is wrong with my code?
add xs
= let
adding (x : xs) as
=
if x == head(xs) && length(xs) >= 1
then adding xs (x : as)
else adding xs (x : x : as)
adding _ as
= as
in
adding xs []
ghci tells that there is always empty list is xs, but i have xs length control.
I’m not sure what you’re ultimately trying to do, but I can help you avoid the “empty list” problem.
When the list
(x:xs)has one item left in it,xs == []. (For example, if(x:xs)contains only the item1, thenx == 1, andxs == []). In this case,head xscauses an exception becauseheadis not defined for empty lists.Try changing the line
to
After this change, when
xs == [],length(xs) >= 1evaluates toFalse. SinceFalse && p == Falsefor allp, Haskell skips evaluating the other expression (x == head(xs)), and the exception is avoided.