user721588
user721588

Reputation:

list recursion in haskell

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.

Upvotes: 1

Views: 310

Answers (2)

aemxdp
aemxdp

Reputation: 1339

Try this:

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

Upvotes: 0

zoo
zoo

Reputation: 1911

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.

Upvotes: 3

Related Questions