1

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.

5
  • 1
    Can you clarify what exactly you want your code to do? Commented May 17, 2012 at 20:23
  • adds one element to the list like in the example Commented May 17, 2012 at 20:25
  • 2
    Your example says [3, 3, 1, 3] turns into [3, 3, 3, 1, 1, 3, 3]. That's more than one element added. Did you mean that each element should be duplicated, resulting in a list of twice the original length? Your example doesn't show that either. Did you intend that the result should be [3, 3, 3, 3, 1, 1, 3, 3]? Commented May 17, 2012 at 20:28
  • Well then I still don't know what you're trying to do. Please specify what the output should be for each of these lists: [1,2,3], [2,2,2], [], [1]. Commented May 17, 2012 at 20:36
  • @Neil: I'm fairly sure he wants concatMap (\(x:xs) -> x:x:xs)) . group. Commented May 17, 2012 at 20:40

2 Answers 2

3

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 item 1, then x == 1, and xs == []). In this case, head xs causes an exception because head is not defined for empty lists.

Try changing the line

if x == head(xs) && length(xs) >= 1

to

if length(xs) >= 1 && x == head(xs)

After this change, when xs == [], length(xs) >= 1 evaluates to False. Since False && p == False for all p, Haskell skips evaluating the other expression (x == head(xs)), and the exception is avoided.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

import Data.List
add xs = concat $ map (\(x:xs) -> x:x:xs) $ group xs

2 Comments

This looks more readable to me: add xss = concat [x:x:xs | (x:xs) <- group xss]
Complete code & no derivation, explanation, or analysis of OP's attempt. -1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.