Type comparison in Haskell

99封情书 提交于 2020-01-30 02:26:09

问题


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?


回答1:


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
>


来源:https://stackoverflow.com/questions/4273702/type-comparison-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!