Haskell type inference with Read - haskell

I think I have a problem with Haskell type inference.
I made my own data type and made it instance of the class Read. My data type is actually take an other type as parameter, it's a type parameter.
I redefined readPresc in a way that parse the string and give back my new data. When I write:
read "string that represent MyType a" :: MyType a
it works perfectly fine (at least it does what I expected)
Now I have a function, let's call it insert, that takes an element of type a, MyType a, and gives back a new MyTape a.
insert :: a -> MyType a -> a
but when I write:
insert 3 "string that rapresent MyType Int"
I got Ambigous type.
How can I tell haskell to infer to the read the same type that is the parameter of the insert?

How can I tell haskell to infer to the read the same type that is the parameter of the insert?
You don't need to, that is inferred from the type of insert.
The problem is that in
insert 3 (read "string that rapresent MyType Int" )
(I inserted the read for it to be possibly type correct), the literal 3 is polymorphic. Its type is
3 :: Num a => a
so that is still not enough information to determine what type read should produce, hence the error.
You need to provide the necessary information, for example
insert (3 :: Int) (read "string that rapresent MyType Int" )
or by using the result in a context that determines the type variable a.

Related

Strange behavior of type parameters in "type" versus "newtype": is this a bug or a feature?

I'm writing a typeclass to add type reflection to Haskell data types. Part of it looks like this:
type VarName a = Text
class Reflective a where
-- | A reflective type may have a fixed name, or it may be a union
-- where each variant has a distinct name.
reflectiveName :: a -> VarName a
-- | One default value of the type for each reflective name.
reflectiveDefaults :: [a]
The idea is that if I write
data ExampleType = Foo Int | Bar String
then in the Reflective instance reflectiveName will return either "Foo" or "Bar" as appropriate, and reflectiveDefaults will return [Foo 0, Bar ""]
So now I can write a function to give me all the names of the variants:
reflectiveNames :: (Reflective a) => [VarName a]
reflectiveNames = map reflectiveName reflectiveDefaults
and I can call it like this:
exampleNames = reflectiveNames :: [VarName ExampleType]
When I compile this I get the following error in the type declaration for reflectiveNames:
• Could not deduce (Reflective a0)
from the context: Reflective a
bound by the type signature for:
reflectiveNames :: Reflective a => [VarName a]
The type variable ‘a0’ is ambiguous
However if I replace the VarName with a newtype:
newtype VarName a = VarName Text
then it works.
Is this a feature of the Haskell type system, or is it a bug in GHC? And if the former, why is it inventing a new type variable a0?
Why this fails for a type...
If you write type then you do not construct a new type, you construct an alias. So you defined:
type VarName a = Text
Hence now each time you write VarName SomeType, you have basically written Text. So VarName Char ~ VarName Int ~ Text (the tilde ~ means that the two types are equal).
Type aliases are useful however since they typically minimize the code (frequently the name of the alias is shorter than its counterpart), it reduces the complexity of signatures (one does not have to remember a large hierarchy of types), and finally it can be used if some types are not yet fully decided (for example time can be modelled as an Int32, Int64, etc.) and we want to define some placeholder to easily change a large number of signatures.
But the point is that each time you write a VarName Char for example, Haskell will replace this with Text. So now if we take a look at your function, you have written:
reflectiveNames :: Reflective a => [Text]
reflectiveNames = map reflectiveName reflectiveDefaults
Now there is a problem with this function: there is a type variable a (in Reflective a), but nowhere in the signature do we use this type parameter. The problem is that Haskell does not know what a to fill in in case you call this function, and that is a real problem (here), since the semantics of reflectiveName and reflectiveDefaults can be completely different for an a ~ Char, then for an a ~ Int. The compiler can not just "pick" a type for a, since that would mean that two different Haskell compilers, could end up with functions that generate different output, and thus a different program (usually one of the fundamental desired aspects of a programming language is unambiguity, the fact that there are no two semantically different programs that map on the same source code).
... and why it works for a newtype
Now why doesn't this happen if we use newtype? Basically a newtype is the same as a data declaration, except for some small details: behind the curtains for example, Haskell will not produce such constructor, it will simply store the value that is wrapped inside the constructor but it will see the value as a different type. The newtype definition
newtype VarName a = VarName Text
is thus (conceptually) almost equivalent to:
data VarName a = VarName Text
Although Haskell will (given it is a compiler that can deal with such optimization) factor the constructor away, we can conceptually assume that it is there.
But the main difference is that we did not define a type signature: we defined a new type, so the function signature stays:
reflectiveNames :: Reflective a => [VarName a]
reflectiveNames = map reflectiveName reflectiveDefaults
and we can not just write Text instead of VarName a, since a Text is not a VarName a. It also means that Haskell can perfectly derive what a is. If we would for instance trigger reflectiveNames :: [VarName Char], then it know that a is a Char, and it will thus use the instance of Reflective for a ~ Char. There is no ambiguity. Of course we can define aliasses like:
type Foo = VarName Char -- a ~ Char
type Bar b = VarName Int -- a ~ Int
But then still a is resolved to Char and Int respectively. Since this is a new type, we will always carry the type of a through the code, and hence the code is unambiguous.

Does the Either type constructor contain a phantom type each for the left/right case?

AFAIK, only types are inhabited by values in Haskell, not type constructors. Either is a binary type constructor of kind * -> * -> *. Left and Right both apply this type constructor to a single type, which is provided by the passed value. Doesn't that mean that in both cases Either is merely partially applied and thus still a type constructor awaiting the missing type argument?
let x = Right 'x' -- Either a Char
x has the type Either a Char. I would assume that this type would have the kind * -> *. This is clearly a polymorphic type, not a ground one. Yet Either a Char can be inhabited by values like 'x'.
My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left. I know phantom types in connection with Const, where the respective type variable isn't used at all. Am I on the right tack?
AFAIK, only types are inhabited by values in Haskell, not type constructors.
Spot on.
Left and Right both apply this type constructor to a single type
You can't say that. Left and Right don't live in the type language at all, so they don't apply anything to any types, they only apply themselves to values.
x has the type Either a Char. I would assume that this type would have the kind * -> *
You need to distinguish between function/constructor arguments, and type variables. It's basically the distinction between free and bound variables. Either a Char still has kind *, not * -> *, because it is already applied to a. Yes, that's a type variable, but it still is an argument that's already applied.
Yet Either a Char can be inhabited by values like 'x'.
Not quite – it can be inhabited by values like Right 'x'.
My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left
kind of, but I wouldn't call it “phantom” because you can't just count out Left or Right. At least not unless you choose Either Void b, but in that case you don't have the a variable.
I would argue that a type variable is phantom if and only if the choice of the type variable does not restrict what values can be passed to the type's constructors. The important part is that this is a type-centric definition. It is determined by looking only at the type definition, not at some particular value of the type.
So does it matter that no value of type String appears in the value Left 5 :: Either Int String? Not at all. What matters is that the choice of String in Either Int String prevents Right () from type-checking.
Haskell has "implicit universal quantification", which means that type variables have an implicit forall. Either a Int is equivalent to forall a. Either a Int.
One way to consider a forall is that it's like a lambda, but for type variables. If we use the syntax # for type application, then, you can "apply" a type to this and get a new type out.
let foo = Right 1 :: forall a. Either a Int
foo #Char :: Either Char Int
foo #Double :: Either Double Int

What is the value of the type?

I have following type declaration:
data MyType = MyVal Int deriving (Eq, Show)
As you can see, it has only one data type constructor with an argument.
In the book, it says:
Because MyVal has one Int argument, a value of type MyType must
contain one — only one — Int value
Why is Int a value of type MyType or what does it mean?
It doesn't say that Int is of type MyType, it says that MyVal (constructor) must only contain an Int, so for example you can not do MyVal "hey!"
Check this
Prelude> data MyType = MyVal Int deriving (Eq, Show)
Prelude> :t MyVal 9
MyVal 9 :: MyType
Prelude> MyVal '9'
<interactive>:12:7: error:
• Couldn't match expected type ‘Int’ with actual type ‘Char’
• In the first argument of ‘MyVal’, namely ‘'9'’
In the expression: MyVal '9'
In an equation for ‘it’: it = MyVal '9'
As you can see, the only way of using MyVal wich is of type MyType is with an Int, so no other type is allowed.
To be super-explicit and clear, which is hopefully helpful: you said that "As you can see, it has only one data type constructor with an argument.", but I would adjust that slightly.
data MyType = MyVal Int deriving (Eq, Show)
Here MyType is the type. It's a type constructor with zero arguments, is one way of viewing it. Or, you could say it's the data type constructor.
However, MyVal is a value constructor. It's one of MyType data type's value constructors (which there are only one of in this example). That is, it's actually a function that constructs values of type MyType. So, MyType has one value constructor called MyVal that takes one argument. That argument has type Int.
If we ask GHCi what the type of this function is, it's clear its one argument is of type Int:
Main> :t MyVal
MyVal :: Int -> MyType
Why is it useful to "wrap" the type Int when it's already a type? One reason is that it separates the meaning of MyVal from Int, and you can thus have your own type, which is distinct from Int according to the type checker and your code, even though its representation happens to be an Int for now.
Maybe tomorrow you may decide to change it to an Integer, in which case all you probably have to do is change that one spot, and the rest of your code will work (assuming you don't use Int to refer to your unwrapped MyVals, and that you have data access functions to deal with the base operations on the internal value of MyVal).
As an aside, just FYI, wrapping a single type in a data declaration like this is usually not done in professional code because it costs execution cycles to wrap and unwrap it. There's another way of declaring single-value types such as this, called newtype which gives a cost-free (at runtime) way to explain to the compiler and typechecker that you want a distinct value that has a representation as one of the existing values. I'm sure whatever book you're reading will explain this in due course, but if it doesn't, make a note to look these up later.

Type Signature of functions with Lists in haskell

I am just beginning to learn Haskell and am following the book "Learnyouahaskell".I have come across this example
tell :: (Show a) => [a] -> String
tell [] = "The list is empty"
I understand that (Show a) here is a class constraint and the type of parameter , in this case a has to be able to be "showable" .
Considering that a here is a list and not an element of the list , why am i unable to declare the function like :-
tell :: (Show a) =>a->String
Edit 1:-from the answers below i seem to understand that one would need to specify the concrete type of a for pattern matching. Considering this,what would be a correct implementation of the below:-
pm :: (Show a) =>a->String
pm 'g'="wow"
It gives me the error as below
Could not deduce (a ~ Char)
from the context (Show a)
bound by the type signature for pm :: Show a => a -> String
at facto.hs:31:7-26
`a' is a rigid type variable bound by
the type signature for pm :: Show a => a -> String at facto.hs:31:7
In the pattern: 'g'
In an equation for `pm': pm 'g' = "wow"
Failed, modules loaded: none.
I understand from the error message that it s not able to deduce the concrete type of a , but then how can it be declared using Show.
I know I can solve the above like this:-
pmn :: Char->String
pmn 'g'="wow"
But I am just trying to understand the Show typeclass properly
List does implement Show type class but when you say: Show a => a -> String It means the function will accept any type which implements Show AND most importantly you can only call show class functions on a nothing else, your function will never know the concrete type of a. Whereas you are trying to call list pattern matching on a
Update for new edit in question:
The correct implementation would be: pm c ="wow". You can call any Show type class functions on parameter c. You cannot pattern match as you were trying before because you dont know the exact type of parameter, you only know that it implements Show type class. But when you specific Char as the type then the pattern matching works
In both signatures, a isn't a list -- it's any type at all, and you don't get to pick which (except that it must be an instance of Show).
In
tell₁ :: Show a => [a] -> String
tell₁ [] = "The list is empty"
... -- (remember to match the non-empty list case too!)
You're matching on the list of as, not on a value of type a itself.
If you wrote
tell₂ :: Show a => a -> String
tell₂ [] = "The list is empty"
...
You would be assuming that the type a is the type of lists (of something). But it could be any type at all, such as Bool.
(But it's possible that I don't understand your question -- you haven't really said what the problem is. When asking a question like this you should generally specify what you did, what you expected, and what happened. None of these is really specified here, so people can only guess at what you might've meant.)
The problem isn't with Show. Indeed if we try:
tell2 :: a -> String
tell2 [] = "The list is empty"
We get a type check error. Lets see what it says:
test.hs:5:7:
Couldn't match expected type `a' with actual type `[t0]'
`a' is a rigid type variable bound by
the type signature for tell2 :: a -> String at test.hs:4:10
In the pattern: []
In an equation for `tell2': tell2 [] = "The list is empty"
Now we ask ourselves, what is this does this so-called 'type' construct really mean? When you write tell2 :: a -> String, you are saying is that for any type that is exactly a, tell2 will give us a String. [a] (or [c] or [foo] - the name doesn't matter) is not exactly a. This may seem like an arbitrary distinction, and as far as I know, it is. Let's see what happens when we write
tell2 [] = "The list is empty"
> :t tell2
> tell2 :: [t] -> [Char]
As you well know there is no difference between writing t and a, and [Char] is just a type synonym for String, so the type we wrote and the type GHC infers are identical.
Well, not quite. When you, yourself, the programmer, specify the type of a function manually in your source, the type variables in your type signature become rigid. What does that mean exactly?
from https://research.microsoft.com/en-us/um/people/simonpj/papers/gadt/:
"Instead of "user-specified type", we use the briefer term rigid
type to describe a type that is completely specified, in some
direct fashion, by a programmer-supplied type annotation."
So a rigid type is any type specified by a programmer type signature.
All other types are "wobbly"[1]
So, just by virtue of the fact that you wrote it out, the type signature has become different. And in this new type grammar, we have that a /= [b]. For rigid type signatures, GHC will infer the very least amount of information it can. It must infer that a ~ [b] from the pattern binding; however it cannot make this inference from the type signature you have provided.
Lets look at the error GHC gives for the original function:
test.hs:2:6:
Could not deduce (a ~ [t0])
from the context (Show a)
bound by the type signature for tell :: Show a => a -> String
at test.hs:1:9-29
`a' is a rigid type variable bound by
We see again rigid type variable etc., but in this case GHC also claims it could not deduce something. (By the way - a ~ b === a == b in the type grammar). The type checker is actually looking for a constraint in the type that would make the function valid; it doesn't find it and is nice enough to tell you exactly what it would need to make it valid:
{-# LANGUAGE GADTs #-}
tell :: (a ~ [t0], Show a) => a -> String
tell [] = "The list is empty"
If we insert GHC's suggestion verbatim, it type checks, since now GHC doesn't need to make any inferences; we have told it exactly what a is.
As soon as you pattern match on 'g', eg
pm 'g' = "wow"
your function no longer has a type of (Show a) => a -> String; instead it has has a concrete type for 'a', namely Char, so it becomes Char -> String
This is in direct conflict with the explicit type signature you gave it, which states your function works with any type 'a' (as long as that type is an instance of Show).
You can't pattern match in this case, since you are pattern matching on an Int, Char, etc. But you can use the show function in the Prelude:
pm x = case show x of
"'g'" -> "My favourite Char"
"1" -> "My favourite Int"
_ -> show x
As you may have guessed, show is a bit magical ;). There's actually a whole bunch of show functions implemented for each type that is an instance of the Show typeclass.
tell :: (Show a) =>a->String
This says tell accepts a value of any type a that is showable. You can call it on anything showable. Which implies that inside the implementation of tell, you have to be able to operate on anything at all (that is showable).
You might think that this would be an okay implementation for that type signature:
tell [] = "The list is empty"
Because lists are indeed showable, and so are valid values for the first parameter. But there I'm checking whether the argument is an empty list; only values of the list type can be matched against list patterns (such as the empty list pattern), so this doesn't make sense if I'd called tell 1 or tell True or tell (1, 'c'), etc.
Inside tell, that type a could be any type that is an instance of Show. So the only things I can do with that value are things that are valid to do with all types that are instances of Show. Which basically means you can only pass it to other similar functions with a generic Show a => a parameter.1
Your confusion is stemming from this misconception "Considering that a here is a list and not an element of the list" about the type signature tell :: (Show a) => [a] -> String. Here a is in fact an element of the list, not the list itself.
That type signature reads "tell takes a single paramter, which is a list of some showable type, and returns a string". This version of tell knows it receives a list, so it can do listy things with its argument. It's the things inside the list which are members of some unknown type.
1 Most of those functions will also be unable to do anything with the value other than pass it on to another Show function, but sooner or later the value will either be ignored or passed to one of the actual functions in the Show typeclass; these have specialised implementations for each type so each specialised version gets to know what type it's operating on, which is the only way anything can eventually be done.

Haskell typing for Int's and Double's

Just quick question about typing.
If I type into ghci :t [("a",3)] I get back [("a",3)] :: Num t => [([Char], t)]
Inside a file I have defined a type as:
type list = [(String, Int)]
How can I change the type to support both Ints and Doubles with the type I have defined, similar to what I wrote in ghci?
First, you have an error in your code. Data types must start with capital letters:
type List = [(String, Int)]
(Note that String is a type synonym for [Char], i.e. they are exactly the same type). We'll solve your problem in a roundabout way. Note that you can make the type completely general in the second slot of the tuple:
type List a = [(String,a)]
so that your type parameterizes over arbitrary types. If you need to specialize to numeric types in some function, then you can make that specialization for each function individually. For example:
foo :: Num a => List a
foo = [("Hello",1),("World",2)]
We could have included a constraint in the data type, like this:
data Num a => List a = List [(String,a)]
but you would still have to include the constraint Num a => ... in every function declaration, so you don't actually save any typing. For this reason, Haskell programmers generally follow the rule "Don't include type constraints in data declarations."

Resources