gpt4 book ai didi

haskell - 为什么是 floatRange、floatRadix 和 floatDigits 函数?

转载 作者:行者123 更新时间:2023-12-04 09:38:40 24 4
gpt4 key购买 nike

根据Hackage , RealFloat 的这些功能类是

... constant function[s] ...



如果它们始终保持相同的值,无论参数如何,正如本描述所建议的那样,为什么不简单地使用:
class (RealFrac a, Floating a) => RealFloat a where
floatRadix :: Integer
floatDigits :: Int
floatRange :: (Int, Int)
...

最佳答案

您提出的非功能方法将具有类型

floatRadix' :: RealFloat a => Integer
floatDigits' :: RealFloat a => Int
...

这些是模棱两可的类型:有一个 a类型变量,但它实际上并未出现在 => 的右侧因此无法从上下文中推断出来。也就是说,在标准的 Haskell 中,你可以推断出这样一个类型变量的唯一方法:本地类型签名也只能到签名头,而不是约束。所以无论你写 (floatDigits' :: Int)(floatDigits' :: RealFloat Double => Int) ,它实际上不会工作 - 编译器无法推断您的意思是 instance RealFloat Double方法的版本。
class RealFloat' a where
floatDigits' :: Int
instance RealFloat' Double where
floatDigits' = floatDigits (0 :: Double)
*Main> floatDigits' :: Int<interactive>:3:1: error:    • No instance for (RealFloat' a0)        arising from a use of ‘floatDigits'’    • In the expression: floatDigits' :: Int      In an equation for ‘it’: it = floatDigits' :: Int*Main> floatDigits' :: RealFloat Double => Int<interactive>:4:1: error:    • Could not deduce (RealFloat' a0)        arising from a use of ‘floatDigits'’      from the context: RealFloat Double        bound by an expression type signature:                   RealFloat Double => Int        at :4:17-39      The type variable ‘a0’ is ambiguous    • In the expression: floatDigits' :: RealFloat Double => Int      In an equation for ‘it’:          it = floatDigits' :: RealFloat Double => Int

For this reason, Haskell does not allow you to write methods with ambiguous type in the first place. Actually trying to compile the class as I wrote it above gives this error message:

    • Could not deduce (RealFloat' a0)      from the context: RealFloat' a        bound by the type signature for:                   floatDigits' :: forall a. RealFloat' a => Int        at /tmp/wtmpf-file3738.hs:2:3-21      The type variable ‘a0’ is ambiguous    • In the ambiguity check for ‘floatDigits'’      To defer the ambiguity check to use sites, enable AllowAmbiguousTypes      When checking the class method:        floatDigits' :: forall a. RealFloat' a => Int      In the class declaration for ‘RealFloat'’

The highlighted line cites however a GHC extension that says “it's ok, I know what I'm doing”. So if you add {-# LANGUAGE AllowAmbiguousTypes #-} to the top of the file with the class RealFloat' in it, the compiler will accept that.

What's the point though, when the instance can't be resolved at the use site? Well, it can actually be resolved, but only using another pretty new GHC extension:

*Main> :set -XTypeApplications 
*Main> floatDigits' @Double
53

关于haskell - 为什么是 floatRange、floatRadix 和 floatDigits 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52811334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com