I have a data type:
data Days = Mon Int | Tue Int | Wed Int | Thu Int | Fri Int
The problem is I have no idea how to deconstruct it.
For example I need a function that returns a list where the argument is not 0 e.g:
[(Mon 1), (Tue 0), (Wed 2), (Wed 0), (Thu 0)]
it should return: [(Mon 1),(Wed 2)]
CodePudding user response:
I think that you need to write a "deconstruction function"
numberOfDay :: Days -> Int
numberOfDay (Mon v) = v
numberOfDay (Tue v) = v
-- and so on.
days = [(Mon 1), (Tue 0), (Wed 2), (Wed 0), (Thu 0)]
filtered = filter ((/= 0) . numberOfDay) days
After all, you could come in at any time and add another constructor that has, for example no arguments. Any mechanism that generically deconstructs a type where all constructors have the same argument list would fail at this point.
Another solution would be, to structure your code slightly different:
data Days = Mon | Tue | Wed | Thu | Fri
data DayVal = DayVal Days Int