dexdz
dexdz

Reputation: 43

Why do I get extra element when getting every other element in a list?

I'm new to haskell and I dont know why I'm getting an extra element in a list.

Here's my code:

module Test where

    deal list = hand1
        where list' = fst(splitAt 4 list)
              hand1 = [snd list' | list'<- (zip [0..] list), even (fst list')]

If I were to put in:

Test.deal [1,2,3,4,5,6]

It splits the list to create to create a tuple of two lists one with length of 4: ([1,2,3,4],[5,6])

When I try to get every other element of the first list in the tuple, I get: [1,3,5] instead of [1,3]

Anyone know why it adds the 5 even though it isn't in the list?

Upvotes: 3

Views: 84

Answers (1)

pedrofurla
pedrofurla

Reputation: 12783

You are defining two different list'. The one inside the list comprehension list'<- (zip [0..] list) shadows the previous one. Shadowing means you have two equal names in scope but the one lexically closer is the only one visible. You want something like:

module Test where
    deal list = hand1
        where list0 = fst (splitAt 4 list)
              hand1 = [snd list1 | list1 <- (zip [0..] list0), even (fst list1)]

With these changes, I can do

λ> deal [1,2,3,4,5,6]
[1,3]

Upvotes: 6

Related Questions