Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

haskell

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?

like image 522
dexdz Avatar asked Mar 02 '23 16:03

dexdz


1 Answers

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]
like image 166
pedrofurla Avatar answered Apr 30 '23 10:04

pedrofurla