Haskell: Check if integer, or check type of variable
Asked Answered
A

3

18

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?

Albumenize answered 9/11, 2010 at 8:5 Comment(0)
E
17

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
Ettaettari answered 9/11, 2010 at 8:18 Comment(2)
What if you're using Intellij's Haskell plugin?Trimetallic
@Trimetallic edon's answer seems to cover that.Ettaettari
S
21

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.

Seafowl answered 9/11, 2010 at 8:26 Comment(2)
Given that he mentioned isDigit, I think he wants to check whether a string represents an integer - not whether a given variable is an integer, even though that's what the title said. Also your type signature is wrong: you're missing the Typeable constraint.Deracinate
This is almost always a wrong approach. It looks like the poster is a Haskell beginner, and we should try to understand his problem better, not give solutions like this.Gregarine
E
17

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
Ettaettari answered 9/11, 2010 at 8:18 Comment(2)
What if you're using Intellij's Haskell plugin?Trimetallic
@Trimetallic edon's answer seems to cover that.Ettaettari
D
0

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)

Donettedoney answered 16/3 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.