本文介绍了双重类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习Haskell, ghci

  Prelude Data.Ratio> ; :类型0.15 
0.15 ::小数a => a

Prelude Data.Ratio> 0.15
0.15
it :: Double

为什么类型不同? 0.15这两个实例实际上是不同的类型吗?

解决方案

这是由于。基本上,GHCi喜欢在执行时选择默认类型(默认小数类型是 Double ),但是当您询问使用键入:type 它会选择最通用的版本。您可以使用 NoMonomorphismRestriction 扩展名停用此行为:

 > :set -XNoMonomorphismRestriction 
> :set + t
> 0.15
0.15
it ::小数a => a
> :t 0.15
0.15 ::小数a => a

虽然这个扩展名有一个可怕的名字,但在分解时很简单:

Mono - >一
Morph - >形状(类型)
ism - > thingy
单形 - >一个形状thingy - >一种类型的东西 - >单一类型的东西

所以基本上这是一个很长的单词,意思是单一类型。然后通过限制,你会发现单态限制将事物限制为单一类型。在这种情况下,它将数字(东西)限制为 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?

解决方案

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.

这篇关于双重类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:02