Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: Check if integer, or check type of variable

Tags:

haskell

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?

like image 641
Jake Avatar asked Nov 09 '10 08:11

Jake


People also ask

How do you check variable type in Haskell?

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. or e.g.

What does == mean in Haskell?

The == is an operator for comparing if two things are equal. It is quite normal haskell function with type "Eq a => a -> a -> Bool". The type tells that it works on every type of a value that implements Eq typeclass, so it is kind of overloaded.

How do you check if a element is in a list Haskell?

elem :: element -> list -> Bool. Use elem if you want to check whether a given element exists within a list.

What is a type variable in Haskell?

A type variable is a way to have polymorphism by writing a single function/method that works on multiple different types of values. Here is an example in Haskell: id :: forall a. a -> a id x = x. The a in the type signature is a type variable, and as the forall implies, this function works "for all" different types.


2 Answers


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.

like image 135
edon Avatar answered Oct 17 '22 21:10

edon


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
like image 14
Matt Ellen Avatar answered Oct 17 '22 23:10

Matt Ellen