Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a function in Haskell that returns the type of its argument (or a string showing the type)?

Tags:

haskell

Is there a function one can call within a Haskell program that does what :t does interactively? Or is this something Haskell cannot do since it's type would not make sense. What about a function that returned the name of the type as a String?

like image 913
RussAbbott Avatar asked May 14 '18 18:05

RussAbbott


People also ask

Does every Haskell function have a type?

Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it. Unlike Java or Pascal, Haskell has type inference. If we write a number, we don't have to tell Haskell it's a number.

How do I check my 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. e.g. or e.g.

What does the show function do in Haskell?

The shows functions return a function that prepends the output String to an existing String . This allows constant-time concatenation of results using function composition.

What are function types in the Haskell programming language?

Function types Ordinary data types are for primitive data (like (Int) and (Char)) and basic data structures (like ([Int]) and ([Char])). Algebraic data types are types that combine other types either as records ('products'), e.g. or as variants ('sums'), e.g.


1 Answers

The question can be understood twofold:

  1. can a polymorphic function inquire the concrete type it is called with. The other questions describe how it could be done.

  2. can we get to runtime statically known information about a binding. This is what actually the :t does. There are ways to get it:

a. to just print it during compilation, you could enable PartialSignatures extension, and add to arbitrary expression signature :: _, then its type will be printed during compilation.

b. to actually get the type as a data for runtime handling, you could use TemplateHaskell extension and function reify from it.

like image 70
max630 Avatar answered Oct 23 '22 22:10

max630