开发者

Type comparison in Haskell

I'm still just learning the basics of Haskell, and I've tried to find an answer to this simple ques开发者_StackOverflow社区tion, 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?


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
>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜