user1544128
user1544128

Reputation: 582

Haskell type inference with Read

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?

Upvotes: 1

Views: 104

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183878

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.

Upvotes: 5

Related Questions