Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell pattern match on type

Tags:

haskell

Is there any way of doing something like this in haskell ?

data Fruits = Apple Int | Orange Int deriving (Eq, Show)

basket = [Apple 2, Orange 4]

from_basket t (x:basket) =
    case x of
        (t i) -> i
        _ -> from_basket t basket

Now i want to get the 'apple' from the list of fruits ( basket )

from_basket Apple basket

Without an explicit pattern match

case x of
    Apple i -> ...
    Orange i -> ...
    _ ->
like image 437
jgoday Avatar asked Apr 29 '11 08:04

jgoday


1 Answers

One way would be to define your own helper function isApple and then do filtering:

isApple (Apple _) = True
isApple _         = False

getApples = filter isApple

Pattern matching is the tool of your choice, I don't know whether you can simplify this any further. But apart from some dirty template Haskell, I don't see any other way.

like image 62
fuz Avatar answered Oct 13 '22 01:10

fuz