Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

haskell - Couldn't Match Expected Type Against Inferred Type, Rigid Type Variable Error

What is wrong with this function ?

test :: Show s => s
test = "asdasd"

String is an instance of the Show class, so it seems correct.

The error is

srcMain.hs:224:7:
    Couldn't match expected type `s' against inferred type `[Char]'
      `s' is a rigid type variable bound by
          the type signature for `test' at srcMain.hs:223:13
    In the expression: "asdasd"
    In the definition of `test': test = "asdasd"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

test :: Foo a => a means "for any type which is an instance of Foo, test is a value of that type". So in any place where you can use a value of type X where X is an instance Foo, you can use a value of type Foo a => a.

Something like test :: Num a => a; test = 42 works because 42 can be a value of type Int or Integer or Float or anything else that is an instance of Num.

However "asdasd" can't be an Int or anything else that is an instance of Show - it can only ever be a String. As a consequence it does not match the type Show s => s.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...