gpt4 book ai didi

haskell - 类型默认为 `floor . sqrt`

转载 作者:行者123 更新时间:2023-12-02 10:52:45 25 4
gpt4 key购买 nike

-Wtype-defaults (附带-Wall),floor . sqrt . fromIntegral即使我指定了参数的类型和结果,也会给我带来大量警告:

λ> (floor . sqrt . fromIntegral) (10 :: Int) :: Int

<interactive>:356:2-6: warning: [-Wtype-defaults]
• Defaulting the following constraints to type ‘Double’
(RealFrac a0)
arising from a use of ‘floor’ at <interactive>:356:2-6
(Floating a0)
arising from a use of ‘sqrt’ at <interactive>:356:10-13
(Num a0)
arising from a use of ‘fromIntegral’ at <interactive>:356:17-28
• In the first argument of ‘(.)’, namely ‘floor’
In the expression: floor . sqrt . fromIntegral
In the expression: (floor . sqrt . fromIntegral) (10 :: Int) :: Int

<interactive>:356:2-6: warning: [-Wtype-defaults]
• Defaulting the following constraints to type ‘Double’
(RealFrac a0)
arising from a use of ‘floor’ at <interactive>:356:2-6
(Floating a0)
arising from a use of ‘sqrt’ at <interactive>:356:10-13
(Num a0)
arising from a use of ‘fromIntegral’ at <interactive>:356:17-28
• In the first argument of ‘(.)’, namely ‘floor’
In the expression: floor . sqrt . fromIntegral
In the expression: (floor . sqrt . fromIntegral) (10 :: Int) :: Int
3

我可以通过为fromIntegral指定非多态类型来解决这个问题。 :

λ> (floor . sqrt . (fromIntegral :: Int -> Double)) (10 :: Int) :: Int
3

下面的方法也可以,但更麻烦:

λ> (floor . sqrt . (fromIntegral :: (Integral a) => a -> Double)) (10 :: Int) :: Int
3

我的问题是:

  • 是否有更简单的方法来解决类型默认警告? (关闭 -Wtype-defaults 不符合条件。)
  • 这是在 Haskell 中计算复合函数(平方根下限)值的正确方法吗?必须使用fromIntegral并且必须指定中间类型让我想起了谚语“简单的事情是困难的。”

最佳答案

有三种类型可供选择(输入类型、内部使用的中间浮点类型和结果类型),并且您必须以某种方式告诉编译器这三种类型。有很多组合可以修复它们,但不能少于三个。

我认为 TypeApplications 是指定这些类型的特别方便的方法。这是一种从原始版本开始的方法,其中有两个注释,然后仅添加一个以避免默认:

> :set -XTypeApplications -Wtype-defaults
> (floor . sqrt @Double . fromIntegral) (10 :: Int) :: Int
3

这是另一个可能更符合人体工程学的方法(因为它对于括号的确切位置更加灵活):

> (floor . sqrt . fromIntegral @Int @Double) 10 :: Int
3

我喜欢你的第三个例子的想法,它是修改你的第二个例子,这样你就不必重复Int,从而避免潜在的脆弱点。您可以使用类型应用程序通过使用特殊的 _ 类型应用程序以稍微不那么麻烦的方式实现此目的,该应用程序允许编译器对其中一个类型变量使用通常的推理过程:

> (floor . sqrt . fromIntegral @_ @Double) (10 :: Int) :: Int
3

关于haskell - 类型默认为 `floor . sqrt`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52537287/

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