Jake
Jake

Reputation: 2907

Haskell: Check if integer, or check type of variable

So let's say you have a variable n.

You want to check if its an integer, or even better yet check what type it is.

I know there is a function in haskell, isDigit that checks if it is a char.

However is there a function that checks if n is in integer, or even better, gives the type of n?

Upvotes: 18

Views: 73775

Answers (3)

Code on the Rocks
Code on the Rocks

Reputation: 17576

You can use the typeOf method from the Data.Typeable package for this.

import Data.Typeable

typeOf myVar

This VS Code extension contains a few snippets to make remembering this easier (checkType, getType, typeOf, etc)

Upvotes: 0

edon
edon

Reputation: 722


import Data.Typeable
isInteger :: (Typeable a) => a -> Bool
isInteger n = typeOf n == typeOf 1

But you should think about your code, this is not very much like Haskell should be, and it probably is not what you want.

Upvotes: 21

Matt Ellen
Matt Ellen

Reputation: 11592

If you are using an interactive Haskell prompt (like GHCi) you can type :t <expression> and that will give you the type of an expression.

e.g.

Prelude> :t 9

gives

9 :: (Num t) => t

or e.g.

Prelude> :t (+)

gives

(+) :: (Num a) => a -> a -> a

Upvotes: 17

Related Questions