Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

haskell - Type of a double

Learning Haskell, in ghci:

Prelude Data.Ratio> :type 0.15
0.15 :: Fractional a => a

Prelude Data.Ratio> 0.15
0.15
it :: Double

Why are types different? Are those two instances of 0.15 actually different types?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This due to the dreaded monomorphism restriction. Basically, GHCi likes to choose default types when executed (the default Fractional type is Double), but when you ask the type using :type it chooses the most general version. You can disable this behavior with the NoMonomorphismRestriction extension:

> :set -XNoMonomorphismRestriction
> :set +t
> 0.15
0.15
it :: Fractional a => a
> :t 0.15
0.15 :: Fractional a => a

While this this extension has one of the scarier names, it's rather simple when you break it down:

Mono  -> One
Morph -> shape (type)
ism   -> thingy
Monomorphism -> one shape thingy -> one type thingy -> thing with a single type

So basically it's a really long word that means "single type". Then with "restriction", you get that the monomorphism restriction is restricting things to a single type. In this case, it's restricting numbers (the things) to the type Double. Without this restriction, the type of the numbers is only constrained by a type class, which can in theory be an infinite number of types.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...