Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type as a String in Haskell?

Let's say I have a type MyType defined in module My.Module. I want to have the String "My.Module.MyType" (or something like that). If I just type the String directly, I might have a typo, and if the module or type name changes, I'd like to know at compile time.

Ah, there appears there might be confusion about what I'm asking. Please look at the question carefully. Given the code:

module My.Module
type MyType = Int
data MyType2 = MyConstructor2 Int
main = do
  putStrLn $ theMagic MyType
  putStrLn $ theMagic MyType2

The output I want is:

My.Module.MyType
My.Module.MyType2

I'm looking for the type name, not the type definition. typeOf would output Int and such, that's not what I want.

like image 906
mentics Avatar asked Mar 18 '11 15:03

mentics


People also ask

How to create a string in Haskell?

In Haskell it is also very easiest form of data type which can be used, easy to handle and create as well. String can be created by using double quotes (“”) inside this we can write our string or value that we want string type to be hold for us.

How do I use I/O in Haskell?

The most common I/O operations are defined in the System.IO library. For the most basic stdin/stdout Unix-style programs in Haskell, we can use the interact function: interact :: (String -> String) -> IO () This higher-order function takes, as an argument, some function for processing a string (of type String -> String).

How do you declare a type in Haskell?

1 Data declarations. One introduces, or declares, a type in Haskell via the data statement. In general a data declaration looks like: data [context =>] type tv1 ...

What is the difference between string and char types in Haskell?

We'll examine their different use cases, and observe how to convert between them. The String type is the most basic form of representing strings in Haskell. It is a simple type synonym for a list of unicode characters (the Char type). So whenever you see [Char] in your compile errors, know this refers to the basic String type.


1 Answers

You can use a Proxy for this:

Prelude> import Data.Typeable
Prelude Data.Typeable> show $ typeRep (Proxy :: Proxy [Int])
"[Int]"
like image 188
Chris Stryczynski Avatar answered Oct 09 '22 10:10

Chris Stryczynski