gpt4 book ai didi

haskell - 如何在 Haskell 中进行类型转换?

转载 作者:行者123 更新时间:2023-12-04 18:18:47 29 4
gpt4 key购买 nike

我在文件 main.hs 中有以下代码:

teste :: Integral a => a -> a
teste n = truncate (sqrt n) + mod n 2

当我尝试加载它时,我从 ghci 收到以下错误:
Prelude> :l main.hs 
[1 of 1] Compiling Main ( main.hs, interpreted )

main.hs:12:11:
Could not deduce (RealFrac a) arising from a use of ‘truncate’
from the context (Integral a)
bound by the type signature for teste :: Integral a => a -> a
at main.hs:11:10-29
Possible fix:
add (RealFrac a) to the context of
the type signature for teste :: Integral a => a -> a
In the first argument of ‘(+)’, namely ‘truncate (sqrt n)’
In the expression: truncate (sqrt n) + mod n 2
In an equation for ‘teste’: teste n = truncate (sqrt n) + mod n 2

main.hs:12:21:
Could not deduce (Floating a) arising from a use of ‘sqrt’
from the context (Integral a)
bound by the type signature for teste :: Integral a => a -> a
at main.hs:11:10-29
Possible fix:
add (Floating a) to the context of
the type signature for teste :: Integral a => a -> a
In the first argument of ‘truncate’, namely ‘(sqrt n)’
In the first argument of ‘(+)’, namely ‘truncate (sqrt n)’
In the expression: truncate (sqrt n) + mod n 2
Failed, modules loaded: none.

但是当我在交互模式下运行相同的代码时,它工作正常:
Prelude> truncate (sqrt 5) + mod 5 2
3

最佳答案

在您的来电 truncate (sqrt 5) + mod 5 2 , 5 s 有不同的类型。确实是5sqrt 5应该有类型 Floating a => a ,而 5mod 5 2有类型 Integral b => b .尽管严格来说可以在 Haskell 中构造一个属于这两个类型家族的类型,但从概念上讲,一个类型同时是 Integral 是很奇怪的。和 Floating ,它也仅适用于此类类型,使其不太有用。因此,我们可以将签名更改为:

teste :: (Integral a, Floating a, RealFrac a) => a -> a
teste n = truncate (sqrt n) + mod n 2

但如前所述,这不是很有用。

您可以使用 fromIntegral :: (Integral a, Num b) => a -> b 在这里从 Integral 转换输入任意 Num类型,如:
teste :: Integral a => a -> a
teste n = truncate (sqrt (fromIntegral n)) + mod n 2

例如:
Prelude> teste 5
3

关于haskell - 如何在 Haskell 中进行类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56294359/

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