Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numeric type signature

Is it possible to create a type with a numeric argument?

i.e. if I want to create a type of integers with a fixed bit-width:

newtype FixedWidth w = FixedWidth Integer

addFixedWidth :: FixedWidth w -> FixedWidth w -> FixedWidth (w+1)
mulFixedWidth :: FixedWidth w -> FixedWidth w -> FixedWidth (2*w)

So that the type-checker only allows FixedWidths of the same type to be added or multiplied, but also determines the correct precision of the result.

I know you can do something like this:

data Nil = Nil
data Succ x = Succ

addFixedWidth :: FixedWidth w -> FixedWidth w -> FixedWidth (Succ w)

and represent the number 4 as Succ (Succ (Succ (Succ Nil)))), but that's incredibly ugly. I also need to figure out how to append two Succs for the multiply result type.

like image 350
pat Avatar asked Jun 04 '11 19:06

pat


People also ask

What is basic type signature?

There are three basic types of time signatures: simple, compound, and complex.

What is a function's signature?

A function signature (or type signature, or method signature) defines input and output of functions or methods. A signature can include: parameters and their types. a return value and type. exceptions that might be thrown or passed back.

What is type signature in Java?

Java. In Java, a method signature is composed of a name and the number, type and order of its parameters. Return types and thrown exceptions are not considered to be a part of the method signature, nor are the names of parameters; they are ignored by the compiler for checking method uniqueness.

What is included in a method's signature?

Method Signature According to Oracle, the method signature is comprised of the name and parameter types. Therefore, all the other elements of the method's declaration, such as modifiers, return type, parameter names, exception list, and body are not part of the signature.


1 Answers

The feature you are looking for is type-level naturals, know as the -XTypeNats extension to Haskell.

At the moment this is possibly only in an experimental branch of GHC. It is likely to merge into GHC by 7.4 I think.

Some further reading:

  • TypeNats, GHC wiki page.
  • Type-Level Naturals Basics
  • Ticket #4385.
  • The TypeNats branch of GHC
like image 55
Don Stewart Avatar answered Oct 15 '22 08:10

Don Stewart