2

I'm familiar with the newtype declaration:

newtype MyAge = Age {age :: Int} deriving (Show, Eq, Ord) 

In this instance Age is an Int, however I've come across the code below and I can't understand it:

newtype Ages a = Ages {age :: String -> [(a,String)]} 

This appears to be a function declaration? (takes string, returns list of tuples containing 'a' and string) - is this correct?

N.B I've just realized this is just basic record syntax to declare a function.

Additionally, I've tried to implement this type, but I must be doing something wrong:

newtype Example a = Example {ex :: Int -> Int} myexample = Example {ex = (\x -> x + 1)} 

This compiles, however I don't understand why as I haven't passed the 'a' parameter?

1
  • 1
    Don't add new questions to an existing post. That said, Example a is an example of the use of a phantom type. Commented Oct 4, 2016 at 11:47

1 Answer 1

5

This appears to be a function declaration?

Yes. Specifically, String -> [(a,String)] is a function type. A newtype declaration is analogous to a simple wrapper around any given type. There's no restriction that says you can't make it based on a function type, and it works in exactly the same way.

Also remember that you can always replace newtype with data; in this case, thinking about the resulting type as a record type that has a field that is a function might be helpful; newtype is just a special, optimized case.


One other thing to mention is that your two lines also differ in that the second one is parametrized over a. This can of course be used with regular types:

newtype MyWrapper a = MyWrapper a 

or a function type can be newtype-d without parametrisation

newtype MyFunction = MyFunction (Float -> Float) 

You can also write the above using the record syntax that gives you the "getter" function as well.

Sign up to request clarification or add additional context in comments.

3 Comments

How can I change this newtype declaration into a normal function declaration?
@barbrac Do you mean a function declaration or regular type alias? If the latter, simply use type.
@barbrac this is how the question should look like from the start. Please avoid making edits that substantially change the scope of the Q/A.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.