简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM