Type comparison in Haskell

后端 未结 1 382
-上瘾入骨i
-上瘾入骨i 2021-01-15 05:46

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.

1条回答
  •  醉梦人生
    2021-01-15 06:03

    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 讨论(0)
提交回复
热议问题