Haskell: Pattern Matching with Lists
Posted
by
user1670032
on Stack Overflow
See other posts from Stack Overflow
or by user1670032
Published on 2012-10-06T21:34:41Z
Indexed on
2012/10/06
21:37 UTC
Read the original article
Hit count: 256
I'm trying to make a function that takes in a list, and if one of the elements is negative, then any elements in that list that are equal to its positive counterpart should be changed to 0. Eg, if there is a -2 in a list, then all 2's in that list should be changed to 0.
Any ideas why it only works for some cases and not others? I'm not understanding why this is, I've looked it over several times.
changeToZero [] = []
changeToZero [x] = [x]
changeToZero (x:zs:y:ws) | (x < 0) && ((-1)*(x) == y) = x : zs : 0 : changeToZero ws
changeToZero (x:xs) = x : changeToZero xs
*Main> changeToZero [-1,1,-2,2,-3,3]
[-1,1,-2,2,-3,3]
*Main> changeToZero [-2,1,2,3]
[-2,1,0,3]
*Main> changeToZero [-2,1,2,3,2]
[-2,1,0,3,2]
*Main> changeToZero [1,-2,2,2,1]
[1,-2,2,0,1]
© Stack Overflow or respective owner