Richard Anthony Hein
Richard Anthony Hein

Reputation: 10650

Type comparison in Haskell

I'm still just learning the basics of Haskell, and I've tried to find an answer to this simple question, so I apologize in advance, because I'm sure it's simple.

Given:

data Fruit = Fruit| Apple | Orange
    deriving (Show, Eq)

a = Apple

How do I check if some a is a Fruit?

Upvotes: 4

Views: 10251

Answers (1)

Joey Adams
Joey Adams

Reputation: 43400

Assuming you really meant type comparison, the simple answer is "you can't". Haskell is statically typed, so the check is done at compile-time, not run-time. So, if you have a function like this:

foo :: Fruit -> Bool
foo Apple = True
foo x     = False

The answer of whether or not x is a Fruit will always be "yes".

What you might be trying to do is find out what data constructor a given value was constructed with. To do that, use pattern matching:

fruitName :: Fruit -> String
fruitName Fruit  = "Fruit"
fruitName Apple  = "Apple"
fruitName Orange = "Orange"

By the way, if you're using GHCi, and you want to know the type of something, use :t

> let a = 123
> :t a
a :: Integer
>

Upvotes: 14

Related Questions