Here is the data type:
data Fruit = Apple | Banana | Orange
data Basket = Basket Fruit Int
now in the code ,there is a list of Basket
which could have any of Fruit
inside. How to filter out all the Baskets
with Apple
in it ? in Python there is a function type
or instanceof
that may help but not sure how Haskell can handle this ?
baskets = [Baseket (Apple 10),Baseket (Banana 2),Baseket (Apple 6)]
CodePudding user response:
First, there are a couple of typos in your code. If Basket
is meant to have a fruit and and integer inside it, then it should be
data Basket = Basket Fruit Int
Second, the constructor for Basket
should be called with two arguments and no parentheses around the arguments, so your list is
baskets :: [Basket]
baskets = [Basket Apple 10, Basket Banana 2, Basket Apple 6]
Finally, you use the word "filter" so I suspect you've already surmised that the operation you're looking for is the filter
function.
filter :: (a -> Bool) -> [a] -> [a]
In your case, a ~ Basket
. So we need to give it a mapping from baskets to Bool
which returns true if (and only if) the basket has apples in it. Since we're comparing fruits for equality, we need an Eq
instance on Fruit
(technically, we could pattern match, but since Fruit
is clearly an enumeration to begin with, it should have Eq
, Ord
, Enum
, and all of the nice instances).
data Fruit = Apple | Banana | Orange deriving (Eq)
Now our filter
.
appleBaskets :: [Basket]
appleBaskets = filter (\(Basket fruitType _) -> fruitType == Apple) baskets
We destructure the Basket
inside of the lambda using pattern matching and then compare the fruit type against the Apple
value.