Learn how to use filter

Hey guys, I’m new in the forum and the language too. Can you help me, please ?

I bought this book to study Haskell, but I’m stuck in this exercise.

Create a “Day” type with the days of the week. Make a function that receives a “Days” list and filter “Tuesdays”

I created the Day type:
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving Show

But I’m stuck now. I tried using filter alone but it didn’t work
filter (Tuesday) = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]

Can someone help me, please ? And I know that there’s a better way to do it, I’d really appreciate if someone tell me.

Thanks for your help.

1 Like

@Marrows

I think the exercise wants you to write a function that uses filter, not filter itself. There is a function called filter and it has the following signature:

filter :: (a -> Bool) -> [a] -> [a]

So it takes a function (condition), a list and returns a list of the same type, but only with values that satisfy the condition.

Solution
solution list = filter f list
  where
    f Tuesday = False
    f _ = True

Note that my function f has 2 conditions, if the day is “Tuesday” return False, otherwise return True. If I had only “Tuesday” the function would be partial, i.e. it would fail with other days, since it doesn’t know what to do with other days.

1 Like

Thanks for the help, reading again I realize that is a function that uses filter and not the filter itself.

Thanks again, it helped me a lot !

1 Like